​Working With Queue - Azure Service Bus

Introduction

 
Azure Service Bus is a fully managed multi-tenant cloud messaging service. It is an enterprise integration message broker. It is used to decouple the application and service from each other. The service bus queues support a brokered messaging model of communication. In this model, the components of a distributed application communicate with each other via Queues. Queue acts as a broker (intermediary). The message sender hands-off the message to the Queue and does not wait for the reply from the message receiver or consumer. Queue supports FIFO (First in, First out) message delivery to one or more receivers. Each message is received and processed by only one receiver. Queue helps us to scale our applications more easily. Once the consumer reads the message, it gets deleted from the Queue.
 
​Working With Queue - Azure Service Bus
 
The namespace is a scoping container for all message components. A queue is created under the namespace. You can read my previous article to learn what Azure Service Bus is and how to create a namespace.
 

Create a Queue in the Azure portal

 
Namespace is the scoping container for message components, so Queue is created under the namespace. To create a queue, click on the "Queue" button. We can view all the queues under namespace in "Entities >> Queues" tab. On the "Create new queue" screen, there are multiple fields that need to be filled up, such as name, max queue size, message time to live, lock duration, and other option.
 
​Working With Queue - Azure Service Bus
 
In the following example, I have created one sender and one receiver. The sender sends the message to the queue and the receiver reads a message from the queue and processes it. Here, I am using .NET Core console application to send and receive the message.
 
At the initial part of the code, I have created an instance of QueueClient using a connnection string and a queue name. The QueueClient is available in Microsoft.Azure.ServiceBus NuGet package. It can be downloaded using the NuGet Package Manager.
 
​Working With Queue - Azure Service Bus
  
Using the SendAsync method of queue client, we can send the message to the queue.
 
Sender Code
  1. static IQueueClient queueClient;  
  2. static void Main(string[] args)  
  3. {  
  4.     string connectionStringServiceBus = "<<Namespace connection string>>";  
  5.     string queueName = "<<queue name>>";  
  6.   
  7.     SendMessage(connectionStringServiceBus, queueName).GetAwaiter().GetResult();  
  8. }  
  9.   
  10. static async Task SendMessage(string connectionStringServiceBus, string queueName)  
  11. {  
  12.     const int numberOfMessages = 5;  
  13.     queueClient = new QueueClient(connectionStringServiceBus, queueName);  
  14.   
  15.     Console.WriteLine("======================================================");  
  16.     Console.WriteLine("Press any key to exit after sending all the messages.");  
  17.     Console.WriteLine("======================================================");  
  18.   
  19.     // Send Messages  
  20.     await SendMessagesToQueueAsync(numberOfMessages);  
  21.   
  22.     Console.ReadKey();  
  23.   
  24.     await queueClient.CloseAsync();  
  25. }  
  26.   
  27. static async Task SendMessagesToQueueAsync(int numberOfMessages)  
  28. {  
  29.     try  
  30.     {  
  31.         for (var i = 0; i < numberOfMessages; i++)  
  32.         {  
  33.             // Message that send to the queue  
  34.             string messageBody = $"GNR-MSG dataid:{i}";  
  35.             var message = new Message(Encoding.UTF8.GetBytes(messageBody));  
  36.   
  37.             Console.WriteLine($"Sending message to queue: {messageBody}");  
  38.   
  39.             // Send the message to the queue  
  40.             await queueClient.SendAsync(message);  
  41.         }  
  42.     }  
  43.     catch (Exception exception)  
  44.     {  
  45.         Console.WriteLine($"Exception: {exception.Message}");  
  46.     }  
  47. }  
The RegisterMessageHandler method of queue is used to register the function that will process the message. This method expects two parameters: handler and message handler options. The handler processes the message.
 
Receiver Code
  1. static IQueueClient queueClient;  
  2. static void Main(string[] args)  
  3. {  
  4.     string connectionStringServiceBus = "<<Namespace connection string>>";  
  5.     string queueName = "<<queue name>>";  
  6.   
  7.     Console.WriteLine("======================================================");  
  8.     Console.WriteLine("Press any key to exit after receiving all the messages.");  
  9.     Console.WriteLine("======================================================");  
  10.   
  11.     queueClient = new QueueClient(connectionStringServiceBus, queueName);  
  12.   
  13.     RegisterMessageHandlerAndReceiveMessages();  
  14.   
  15.     Console.ReadKey();  
  16.   
  17.     queueClient.CloseAsync().Wait();  
  18. }  
  19. static void RegisterMessageHandlerAndReceiveMessages()  
  20. {  
  21.     // Configure the MessageHandler Options in terms of exception handling, number of concurrent messages to deliver etc.  
  22.     var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)  
  23.     {  
  24.         MaxConcurrentCalls = 1,  
  25.         AutoComplete = false  
  26.     };  
  27.   
  28.     // Register the function that will process messages  
  29.     queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);  
  30. }  
  31.   
  32. static async Task ProcessMessagesAsync(Message message, CancellationToken token)  
  33. {  
  34.     // Process the message  
  35.     Console.WriteLine($"Received message: Sequence Number:{message.SystemProperties.SequenceNumber} \t Body:{Encoding.UTF8.GetString(message.Body)}");  
  36.   
  37.     await queueClient.CompleteAsync(message.SystemProperties.LockToken);  
  38. }  
  39. // Use this Handler to look at the exceptions received on the MessagePump  
  40. static Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs)  
  41. {  
  42.     Console.WriteLine($"Exception:: {exceptionReceivedEventArgs.Exception}.");  
  43.     return Task.CompletedTask;  
  44. }  
Output
 
​Working With Queue - Azure Service Bus
 
When we run the sender application and check on the Azure portal under Queue >> Overview tab, the following screen is displayed. Here, we can see that "Active Message Count" has a value of 5. This value denotes the number of messages in the queue. It also contains the current size of the messages.
 
​Working With Queue - Azure Service Bus
 

Summary

 
A Queue is used to send and receive messages. It enables us to store these messages until the receiver is available to receive such messages and process them. It allows one-way communication. The messages are in FIFO (first in, first out) order in the queue and are timestamped based on their arrival. The queue is used for point-to-point communication.
 
You can view and download the source code from GitHub.