In last article we have seen some basic concepts on how service bus works. In this article, let’s try to create service bus queues and try creating a POC application to demonstrate messaging solution.
You will need access to Azure Portal. If you don’t have an Azure subscription, create a free account before you begin.
You can write the sender and receiver of the message in different programming languages. For this article, I have created two c# console applications – one for publishing messages and the other for consuming the message. You can get source code in my GitHub repository.
Adding a Namespace
For using service bus, you will have to create a namespace. For creating namespace, click on “+ Create a resource“, then search for service bus.
Alternatively, you can click on integration menu on New panel, and then select service bus.
On create namespace panel, provide below details:
- Name: unique globally
- Pricing Tier: basic, standard or premium. For using topics, you will have to use standard or premium tier.
- Subscription: your azure subscription under which this resource should be created
- Resource group: for logically grouping resources together. You can either specify existing or you can create new one by using “create new” link.
- Location: Azure region / data center where the resource should be created
Then click on create button.
After namespace creation is done, you can navigate to the namespace and open it. The overview blade should be similar to below snapshot:
Get the connection string
Follow below steps to get the connection string:
- Click on Shared access policies
- This will show policies configured. You can add new policies or select existing ones. For this demo, select the existing property.
- It will open a panel on right side, from where you can copy primary connection string.
Adding a Queue
When new namespace is created, there are no queues in that instance. You can click on Queue option and then Add queue button highlighted below.
This should open Create queue panel. For this demo purpose we will just specify queue name.
As you can see, you can also specify time to leave, lock duration, duplicate detection, enable sessions, dead letter queuing, partitioning. Let’s keep these settings to the default state and click on Create.
Sending Messages
This is first console application – MessagePublisher.
It has SendMessageAsync method which sends messages to the service bus queue. Sending message to the queue is pretty straight forward task. Below is code:
Please note that you will have to add reference to Microsoft.Azure.ServiceBus nuget package to access QueueClient and Message classes.
// Creating queue client
queueClient = new QueueClient(serviceBusConnectionString, queueName);
// Create a new message to send to the queue
string messageBody = $"Message {i}";
var message = new Message(Encoding.UTF8.GetBytes(messageBody));
// Write the body of the message to the console
Console.WriteLine($"Sending message: {messageBody}");
// Send the message to the queue
await queueClient.SendAsync(message);
Receiving Messages
This is the consumer console application with name MessageConsumer.
For consuming queue messages, you need to perform two steps:
Register Message Handler
You have to specify message handler options. In these options you can specify maximum concurrent calls, or exception handler, etc.
// Configure the MessageHandler Options in terms of exception handling, number of concurrent messages to deliver etc.
var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
{
// Maximum number of Concurrent calls to the callback `ProcessMessagesAsync`, set to 1 for simplicity.
// Set it according to how many messages the application wants to process in parallel.
MaxConcurrentCalls = 1,
// Indicates whether MessagePump should automatically complete the messages after returning from User Callback.
// False below indicates the Complete will be handled by the User Callback as in `ProcessMessagesAsync` below.
AutoComplete = false
};
// Register the function that will process messages
queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);
Writing message handling logic
This is the place which will contain the logic for handling the queue message. After processing is done, this method will mark the message as complete.
Below is the code snippet to understand how it is done:
// Process the message
Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");
// Complete the message so that it is not received again.
// Can be done if queueClient created with ReceieveMode.PeekLock option
// (which is default)
await queueClient.CompleteAsync(message.SystemProperties.LockToken);
Running these Applications
You can download code from git repository and open solution in Visual Studio. Then you can specify values of serviceBusConnectionString and queueName in Main method of both applications.
And that’s it. This sample is ready to run. You can then play with this sample to understand other aspects related to service bus Queues.
Remember to Clear the Resources
Once you are done with completing the demo, you can use the portal to remove the resource group, namespace, and queue.
I hope this article has provided clear vision on how Azure messaging solutions can be designed using Service Bus Queues. Please do comment and let me know your thoughts.