Azure Service Bus Publisher and Subscriber

Cloud-based distributed application components often need to provide information to other components as events happen within a program. The asynchronous messaging pattern is an effective way to decouple senders from consumers to avoid blocking the sender while it waits for a response.

During this process, a message is sent from a sender or publisher to an Azure Service Bus topic. A topic is very similar to a queue. One or more receivers – or consumers – can subscribe to these subscriptions in order to receive the messages. This is known as implementing a one-to-many asynchronous messaging pattern.

In this .NET programming tutorial, I will explain everything you need to know about implementing Azure Service Bus Topics and Subscriptions with code examples, which is commonly known as pub-sub in .NET developer communities.

Implementing Azure Service Bus and Subscriptions

To begin, log-in to the Azure portal at www.portal.azure.com. Search for Service Bus, as depicted in the figure below:

Azure Service Bus

Figure 1 – Search Azure Service Bus

Next, click ‘Create’ as depicted here:

Create Azure Service Bus

Figure 2 – Create New Azure Service Bus

Enter the proper name for a namespace. Select a pricing tier. For demo purposes, I have selected Basic, Subscription, and Resource group. Select your desired location and click the ‘Review and Create‘ button:

Azure Service Bus Namespace

Figure 3 – Create New Azure Service Bus Namespace

Once the new namespace is created, you can explore it from the dashboard, where you can find all the details which you have provided while creating your namespace.

Next, we have to create a Queue. Click on the new namespace in the Dashboard. Click on ‘Queues‘ in the left pane and select ‘+Queue‘ to create a new Queue as depicted here:

Azure Service Bus Queue

Figure 4 – Create New Queue

Enter the Queue name and click on the ‘Create‘ button, keeping the rest of the input as is:

Azure Service Bus Queue Details

Figure 5 – Create New Queue Update Details

Next, we will create a Topic by clicking on ‘+Topic‘ under Topics to create a new Topic. See below:

Create Service Bus Topic

Figure 6 – Create New Topic

Add an appropriate name for the newly created Topic. Keep the rest of the input values as is and click on the ‘Create‘ button.

We can see that the Topic is created and it is shown under the Topics list:

Azure Service Bus Topic Created

Figure 7 – New Topic Created

Read: How to Deploy a Webjob in Azure

How to Create Azure Service Bus Subscriptions

Next, click on the previously created Topic, which will show the list of subscriptions. As of now it shows empty. Click on ‘+Subscription‘ under Subscriptions to create a Subscription.

Next, add details to the new Subscription. Add a proper name for the Subscription, change Lock duration to 5 minutes, and click the ‘Create‘ button, which will create a Subscription for the Topic. See below:

Azure Service Bus Create

Figure 8 – Add Details to New Subscription

Follow the previous steps and create one more Subscription before moving on to the next step.

Azure Service Bus Subscription

Figure 9 – One More Subscription Created

We can now see both Subscriptions in the list:

Azure Service Bus Subscriptions

Figure 10 – Two Subscriptions Created

Next, click on ‘Shared access policies‘ from the left panel, the click on ‘RootManageSharedAccessKey‘ to explore keys and connection strings, which we will user to connect to in our C# code.

Azure Service Bus Primary Keys

 

Figure 11 – Primary Keys to Connect

Read: How to Access Azure Storage Account File Shares from .NET

How to Publish a Message to a Service Bus in C#

To publish a message to a Service Bus, I have created a console application in Visual Studio and written the following C# code snippet:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PubSub
{
    class Program
    {
        static ITopicClient topicClient;
        static void Main(string[] args)
        {
            string sbConnectionString = "Endpoint=sb://mobilerecharge.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=KVb9ubc9XaV0dT/1dMjW9CzPWvA/JGvVvUZ64U21IBI=";
            string sbTopic = "Test";

            string messageBody = string.Empty;
            try
            {
                Console.WriteLine("-------------------------------------------------------");
                Console.WriteLine("Publish Offer");
                Console.WriteLine("-------------------------------------------------------");
                Console.WriteLine("Test");
                Console.WriteLine("1. Test message 1 pushed");
                Console.WriteLine("2. Test message 2 pushed");
                Console.WriteLine("3. Test message 3 pushed");
                Console.WriteLine("-------------------------------------------------------");

                Console.WriteLine("Test:");
                string Testmessage = Console.ReadLine();

                Console.WriteLine("-------------------------------------------------------");

                switch (Testmessage)
                {
                    case "1":
                        Testmessage = "Test message 1 pushed";
                        break;
                    case "2":
                        Testmessage = "Test message 2 pushed";
                        break;
                    case "3":
                        Testmessage = "Test message 3 pushed";
                        break;
                    default:
                        break;
                }

                messageBody = Testmessage;
                topicClient = new TopicClient(sbConnectionString, sbTopic);

                var message = new Message(Encoding.UTF8.GetBytes(messageBody));
                Console.WriteLine($"Message Published: {messageBody}");

                topicClient.SendAsync(message);

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                Console.ReadKey();
                topicClient.CloseAsync();
            }


        }
    }
}

In order to read the published message, I have created another console application in Visual Studio IDE. Refer to the following C# code example showing how to read published Service Bus messages:

class Program
{
    static ISubscriptionClient subscriptionClient;
    static void Main(string[] args)
    {
        string sbConnectionString = "Endpoint=sb://mobilerecharge.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=KVb9ubc9XaV0dT/1dMjW9CzPWvA/JGvVvUZ64U21IBI=";
        string sbTopic = "Test";
        string sbSubscription = "Test";
        try
        {
            subscriptionClient = new SubscriptionClient(sbConnectionString, sbTopic, sbSubscription);

            var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
            {
                MaxConcurrentCalls = 1,
                AutoComplete = false
            };
            subscriptionClient.RegisterMessageHandler(ReceiveMessagesAsync, messageHandlerOptions);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            Console.ReadKey();
            subscriptionClient.CloseAsync();
        }
    }

    static async Task ReceiveMessagesAsync(Message message, CancellationToken token)
    {
        Console.WriteLine($"Subscribed message: {Encoding.UTF8.GetString(message.Body)}");

        await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
    }

    static Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs)
    {
        Console.WriteLine(exceptionReceivedEventArgs.Exception);
        return Task.CompletedTask;
    }
}

Conclusion of Azure Service Bus and Subscriber Examples

In this article, I have shown how to use the Azure Portal to quickly create a Service Bus topic containing multiple subscriptions and how to push and read messages. I have also provided some C# code samples showing how to connect to the subscription and process the messages.

More by Author

Must Read