...

/

Using Service Bus Triggers

Using Service Bus Triggers

Explore how to use Service Bus bindings in Azure Functions.

Azure Service Bus is an Azure-specific message broker service. It allows applications to exchange messages via queues and topics. Here is the difference between the two:

  • Queue: Each message is present only once and it’s instantly removed from the queue by a subscriber. So if many subscribers are connected to the queue, there is no way of configuring which subscriber receives which message.

  • Topic: It is similar to a queue, but each subscriber receives its own copy of the message. Therefore, if a specific subscriber has read the message, it will disappear from the topic only for that subscriber. All other subscribers will still be able to read it if they haven’t already.

Press + to interact
Queue vs. topic
Queue vs. topic

Functions can also be connected to it and act both as message publishers and subscribers. This is what we will cover in this lesson with the help of the interactive code playground below:

using System;
using Microsoft.Azure.WebJobs;

namespace AzureFunctionApp
{
    public class Functions
    {
        [FunctionName("ServiceBusOutputTrigger")]
        [return: ServiceBus("examplequeue", Connection = "ServiceBusConnectionString")]
        public string ServiceBusOutput([HttpTrigger] dynamic input)
        {
            try
            {
                return input.Text;
            }
            catch (Exception ex)
            {
                Console.WriteLine("No Service Bus connection found.");
            }

            return null;
        }

        [FunctionName("ServiceBusTopicTrigger")]
        public void SubscribeToTopic(
            [ServiceBusTrigger("exampletopic", "examplesubscription", Connection = "ServiceBusConnectionString")] string message)
        {
            Console.WriteLine($"Message received from topic: {message}");
        }

        [FunctionName("ServiceBusQueueTrigger")]
        public void SubscribeToQueue(
            [ServiceBusTrigger("examplequeue", Connection = "ServiceBusConnectionString")] string message,
            int deliveryCount,
            DateTime enqueuedTimeUtc,
            string messageId)
        {
            Console.WriteLine($"C# ServiceBus queue trigger function processed message: {message}");
            Console.WriteLine($"EnqueuedTimeUtc={enqueuedTimeUtc}");
            Console.WriteLine($"DeliveryCount={deliveryCount}");
            Console.WriteLine($"MessageId={messageId}");
        }
    }
}
Function app with Service Bus bindings

Note: Because Service Bus is an Azure-specific resource that cannot be emulated locally, some ...