Introduction

Azure Service Bus enables asynchronous communication by allowing applications to send and receive messages. In this guide, we will explore the process of sending and receiving messages using Azure Service Bus, including key concepts and sample code to get you started.


Prerequisites

Before you begin, make sure you have the following prerequisites:

  • An Azure Service Bus namespace with queues or topics created.
  • Connection details, including the connection string.
  • A programming environment to write and run code (e.g., Visual Studio, VS Code, or a code editor of your choice).

Sending Messages

To send messages to an Azure Service Bus queue or topic, follow these steps:

  1. Create a sender client with the appropriate connection string.
  2. Create a message with the content you want to send.
  3. Send the message to the queue or topic.

Here's an example of sending a message using C# and the Azure SDK:

using Microsoft.Azure.ServiceBus;
using System;
using System.Text;
using System.Threading.Tasks;
var connectionString = "Endpoint=sb://YourNamespaceName.servicebus.windows.net/;SharedAccessKeyName=YourKeyName;SharedAccessKey=YourKey";
var queueName = "YourQueueName";
var client = new QueueClient(connectionString, queueName);
var message = new Message(Encoding.UTF8.GetBytes("Hello from Azure Service Bus!"));
await client.SendAsync(message);

Receiving Messages

To receive messages from an Azure Service Bus queue or subscription, follow these steps:

  1. Create a receiver client with the appropriate connection string.
  2. Register a message handler to process incoming messages.

Here's an example of receiving messages using C# and the Azure SDK:

var connectionString = "Endpoint=sb://YourNamespaceName.servicebus.windows.net/;SharedAccessKeyName=YourKeyName;SharedAccessKey=YourKey";
var queueName = "YourQueueName";
var client = new QueueClient(connectionString, queueName);
client.RegisterMessageHandler(async (message, token) =>{
Console.WriteLine($"Received message: {Encoding.UTF8.GetString(message.Body)}");
await client.CompleteAsync(message.SystemProperties.LockToken);
}, new MessageHandlerOptions(ExceptionReceivedHandler) { AutoComplete = false });
static Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs)
{
Console.WriteLine($"Message handler encountered an exception {exceptionReceivedEventArgs.Exception}.");
return Task.CompletedTask;
}

Conclusion

Sending and receiving messages with Azure Service Bus is essential for building scalable and decoupled applications. By following the steps and using the sample code outlined in this guide, you can effectively send and receive messages in your Azure-based applications.