Azure Service Bus Topic And Subscription (Pub-Sub)

Azure Service Bus - Topic 

This articles explains about Azure Service Bus Topic and Subscription which is commonly known as pub-sub with a real world scenario.

Business Requirement

The business requirement is in my previous article,

So far we have seen about mobile recharge where we have used queuing mechanism. Now a company wants to provide some offers on regular recharge. But how will registered users come to know about these offers?

So again the company has started looking for some solution and finally it has come up with the solution of Azure Service Bus - Topic. Topic works like pub-sub model where one is the publisher and there can be many subscribers for the same publisher. In our scenario the publisher will publish offers and subscribed users will get the offers immediately.

Azure Service Bus Topic And Subscription (Pub-Sub) 

Now let's see the step by step implementation of the below to design a solution:

  • Log in to the Azure portal via portal.azure.com
  • Explore previously created Service Namespace; i.e. Mobile Recharge
  • Click on '+Topic' under Topics to create a new topic

    Azure Service Bus Topic And Subscription (Pub-Sub)
  • Give appropriate name for Topic
  • Keep the rest of the input values as is and click on 'Create' button

    Azure Service Bus Topic And Subscription (Pub-Sub)

We can see that Topic is created in it is shown under topics list.

Azure Service Bus Topic And Subscription (Pub-Sub) 
  • Click on previously created topic; i.e. 'Offers', which will show the list of subscriptions. As of now it shows empty
  • Click on '+Subscription' under subscriptions to create subscription

    Azure Service Bus Topic And Subscription (Pub-Sub)
  • Give proper name of subscription
  • Change Lock duration to 5 minutes and click on 'Create' button, which will create subscription for topic

    Azure Service Bus Topic And Subscription (Pub-Sub)
  • Follow the preceding steps and create one more subscription

    Azure Service Bus Topic And Subscription (Pub-Sub)

We can see both the subscriptions in the list.

Azure Service Bus Topic And Subscription (Pub-Sub) 

Credentials

Click on 'Shared access policies' from the left panel, click on 'RootManageSharedAccessKey' to explore keys and connection strings which will be used further to connect.

Azure Service Bus Topic And Subscription (Pub-Sub) 

Publish Message

  • Create a console application in Visual Studio
  • Set variables, one for connection string which you can copy from Shared access policies section and another is topic name; i.e. offers
  • In order to publish the offers, we need an offer from user
  • Add Microsoft.Azure.ServiceBus from a NuGet package manager
  • Create topic client using connection string and queue name
  • Convert string message to Azure Service Bus message
  • Using topic client, call SendAsync method to publish the message.
  • Call CloseAsync to close opened connection in finally block.
    1. class Program  
    2.     {  
    3.         static ITopicClient topicClient;  
    4.         static void Main(string[] args)  
    5.         {  
    6.             string sbConnectionString = "Endpoint=sb://mobilerecharge.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=KVb9ubc9XaV0dT/1dMjW9CzPWvA/JGvVvUZ64U21IBI=";  
    7.             string sbTopic = "offers";  
    8.    
    9.             string messageBody=string.Empty;  
    10.             try  
    11.             {  
    12.                 Console.WriteLine("-------------------------------------------------------");  
    13.                 Console.WriteLine("Publish Offer");  
    14.                 Console.WriteLine("-------------------------------------------------------");  
    15.                 Console.WriteLine("Offers");  
    16.                 Console.WriteLine("1. Recharge with 100 and get talk time of 110");  
    17.                 Console.WriteLine("2. Get 5 GB data on recharge of 300. Validity 28 days");  
    18.                 Console.WriteLine("3. 1000 SMS in recharge of 100");  
    19.                 Console.WriteLine("-------------------------------------------------------");  
    20.    
    21.                 Console.WriteLine("Offer:");  
    22.                 string offer = Console.ReadLine();  
    23.    
    24.                 Console.WriteLine("-------------------------------------------------------");  
    25.    
    26.                 switch (offer)  
    27.                 {  
    28.                     case "1":  
    29.                         offer = "Recharge with 100 and get talk time of 110";  
    30.                         break;  
    31.                     case "2":  
    32.                         offer = "Get 5 GB data on recharge of 300. Validity 28 days";  
    33.                         break;  
    34.                     case "3":  
    35.                         offer = "1000 SMS in recharge of 100";  
    36.                         break;  
    37.                     default:  
    38.                         break;  
    39.                 }  
    40.    
    41.                 messageBody = offer;  
    42.                 topicClient = new TopicClient(sbConnectionString, sbTopic);  
    43.    
    44.                 var message = new Message(Encoding.UTF8.GetBytes(messageBody));  
    45.                 Console.WriteLine($"Message Published: {messageBody}");  
    46.    
    47.                 topicClient.SendAsync(message);  
    48.    
    49.             }  
    50.             catch (Exception ex)  
    51.             {  
    52.                 Console.WriteLine(ex.Message);  
    53.             }  
    54.             finally  
    55.             {  
    56.                 Console.ReadKey();  
    57.                 topicClient.CloseAsync();  
    58.             }  
    59.         }  
    60.     }  
  • Run the application and select the offer which you would like to publish
  • You can see the published message 'Message Published…'

    Azure Service Bus Topic And Subscription (Pub-Sub)

We can see that published message is added in all available subscriptions.

Azure Service Bus Topic And Subscription (Pub-Sub) 

 Read message from subscription

  • Create a console application in the Visual Studio
  • Set variables, one for connection string which you can copy from Shared access policies section and another is topic name; i.e. offers
  • Create topic client using connection string and queue name
  • Using topic client, call RegisterMessageHandler which is used to receive messages continuously from the entity. It registers a message handler and begins a new thread to receive messages. This handler is waited on every time a new message is received by the receiver.
  • Inside ReceiveMessageAsync, call CompleteAsync which completes a message using its lock token and deletes the message from the queue.
    1. class Program  
    2.     {  
    3.         static ISubscriptionClient subscriptionClient;  
    4.         static void Main(string[] args)  
    5.         {  
    6.             string sbConnectionString = "Endpoint=sb://mobilerecharge.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=KVb9ubc9XaV0dT/1dMjW9CzPWvA/JGvVvUZ64U21IBI=";  
    7.             string sbTopic = "offers";  
    8.             string sbSubscription = "akki5677";  
    9.             try  
    10.             {  
    11.                 subscriptionClient = new SubscriptionClient(sbConnectionString, sbTopic, sbSubscription);  
    12.    
    13.                 var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)  
    14.                 {  
    15.                     MaxConcurrentCalls = 1,  
    16.                     AutoComplete = false  
    17.                 };  
    18.                 subscriptionClient.RegisterMessageHandler(ReceiveMessagesAsync, messageHandlerOptions);  
    19.             }  
    20.             catch (Exception ex)  
    21.             {  
    22.                 Console.WriteLine(ex.Message);  
    23.             }  
    24.             finally  
    25.             {  
    26.                 Console.ReadKey();  
    27.                 subscriptionClient.CloseAsync();  
    28.             }  
    29.         }  
    30.    
    31.         static async Task ReceiveMessagesAsync(Message message, CancellationToken token)  
    32.         {  
    33.             Console.WriteLine($"Subscribed message: {Encoding.UTF8.GetString(message.Body)}");  
    34.    
    35.             await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);  
    36.         }  
    37.    
    38.         static Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs)  
    39.         {  
    40.             Console.WriteLine(exceptionReceivedEventArgs.Exception);  
    41.             return Task.CompletedTask;  
    42.         }  
    43.     }  
  • Run the application and you can see the previously added message in the subscription.

    Azure Service Bus Topic And Subscription (Pub-Sub)

Now if you closely observe message count for all available subscriptions, one of the subscriptions has a zero message count as we have already read from that subscription and another subscription shows 1 as a message count means we need to publish once and it will be available for all subscriptions and whom so ever is read that only will be deleted and for rest it will be as it is.

Azure Service Bus Topic And Subscription (Pub-Sub) 
  • Now run both the applications simultaneously and select the offer which you would like to publish
  • You can observe that the message will be read by the second application immediately.

    Azure Service Bus Topic And Subscription (Pub-Sub)

Azure service bus topic is very similar to Azure service bus queue, the difference is queue works on one to one; i.e. one sender and one receiver whereas topic works on one to many; i.e. One publisher and many subscribers.

Note
Download complete sample code from here.