Introduction to Azure Service Bus on the Azure Portal

Azure Service Bus is a cloud-based messaging service provided by Microsoft Azure.

Enables communication between different applications and services in a distributed environment.

It is a fully managed, publish-subscribe-based messaging service that provides reliable and secure messaging between various components of a distributed system.

 Service Bus allows you to send and receive messages between different components of your application, whether they are hosted on-premises or in the cloud.

It supports a variety of messaging patterns, including.

  1. publish/subscribe (Refer the E-commerce Scenario)
  2. request/response, and (Refer the credit card payments)
  3. peer-to-peer messaging. (Refer Marketing automation and CRM scenario)

Example: (Publish/Subscribe)

Suppose an e-commerce company has a web application for customers to place orders,

  • A payment processing system,
  • An inventory management system, and
  • A shipping system.

Each of these systems may be hosted in a different location or managed by a different team.

To enable communication between these systems, the e-commerce company can use Service Bus to handle messaging between them.

When a customer places an order on the web application, the application can send an order message to Service Bus. The payment processing system can then subscribe to this message and process the payment.

Once the payment is processed, the payment system can send a payment confirmation message back to Service Bus. The inventory management system can then subscribe to this message and update the inventory to reflect the sale. The shipping system can also subscribe to the message and prepare the order for shipment.

If there is any delay or failure in any of these systems, Service Bus can handle the messaging retries and can also move messages to dead-letter queues, which can help in diagnosing the issue. Service Bus can also be configured to handle different message formats, message priorities, and message delivery guarantees to ensure reliable messaging between different components of the e-commerce system.

Overall, by using Service Bus, the e-commerce company can enable real-time communication between different applications and services in a distributed environment, enabling a seamless and efficient customer experience.

Example 2: (Request/Response)

Suppose a web application needs to process credit card payments from customers. When a customer submits their payment information on the web application, the application needs to verify the payment information with a payment gateway service. The payment gateway service responds with a message indicating whether the payment was accepted or declined.

To enable this interaction, the web application can use Service Bus to send a request message to the payment gateway service. The request message contains the payment information, such as the credit card number and amount.

The payment gateway service can then process the payment information and send a response message back to Service Bus. The response message contains a result code indicating whether the payment was accepted or declined, along with any additional information, such as an error message.

The web application can then subscribe to the response message and retrieve the result code and error message, if applicable. Based on the result code, the web application can display a success or failure message to the customer and take appropriate actions, such as updating the customer’s account balance or cancelling the order.

By using Service Bus to handle the request/response pattern, the web application and payment gateway service can communicate efficiently and reliably, without the need for complex point-to-point integrations. Service Bus provides features such as message queuing, message routing, and message sequencing, which can ensure reliable message delivery and reduce the risk of message loss or duplication.

Example 3: (Peer to peer)

Suppose a company has two applications, a marketing automation system and a customer relationship management (CRM) system, that need to exchange data with each other in a peer-to-peer fashion.

The marketing automation system generates leads and sends them to the CRM system for further processing, while the CRM system sends customer data to the marketing automation system for segmentation and targeted marketing.

To enable this interaction, both applications can use Service Bus as a messaging middleware. The marketing automation system can send a message to Service Bus, which contains the lead data that the CRM system needs to process. This message can be sent to a specific queue or topic that the CRM system subscribes to.

Once the CRM system receives the message, it can process the lead data and send a response message back to Service Bus. This response message can contain information such as the lead status, any updates made to the customer profile, or any other relevant information that the marketing automation system needs to know. The marketing automation system can then subscribe to this response message and retrieve the data.

Service Bus Getting Started with Console Based Application C# using Visual Code:

  • Steps to create a console-based application in C# using Visual Studio Code and Azure Service Bus:
  1. Install Visual Studio Code and the C# extension.

  2. Create a new console application project in Visual Studio Code by navigating to File > New Project > Console Application.

  3. Add the Azure Service Bus SDK package to your project by running the following command in the terminal:

         dotnet add package Microsoft.Azure.ServiceBus

  •        Install Visual Studio Code and the C# extension.
  • Create a new console application project in Visual Studio Code by navigating to File > New Project > Console Application.

  • Add the Azure Service Bus SDK package to your project by running the following command in the terminal:

    dotnet add package Microsoft.Azure.ServiceBus
  • Import the Service Bus namespace in your code:

    using Microsoft.Azure.ServiceBus;
  • Add your Azure Service Bus connection string and queue name as environment variables:

    string connectionString = Environment.GetEnvironmentVariable("SERVICE_BUS_CONNECTION_STRING");
    string queueName = Environment.GetEnvironmentVariable("SERVICE_BUS_QUEUE_NAME");
  • Create a new instance of the ServiceBusClient class:

    ServiceBusClient client = new ServiceBusClient(connectionString);
  • Create a new instance of the ServiceBusSender class:

    ServiceBusSender sender = client.CreateSender(queueName);
  • Create a new message:

    string messageBody = "Hello, Service Bus!";
    Message message = new Message(Encoding.UTF8.GetBytes(messageBody));
  • Send the message to the queue:

    await sender.SendMessageAsync(message);
  • Create a new instance of the ServiceBusReceiver class:

    ServiceBusReceiver receiver =                 
    client.CreateReceiver(queueName);
  • Receive messages from the queue:
    ServiceBusReceivedMessage receivedMessage = await   
    receiver.ReceiveMessageAsync();
string messageBody =
        Encoding.UTF8.GetString(receivedMessage.Body);
         Console.WriteLine(messageBody);

With these  you have created a console-based application in C# using Visual Studio Code and Azure Service Bus, and you have sent and received messages from a Service Bus queue.

  • Complete the message to remove it from the queue:

    await receiver.CompleteMessageAsync(receivedMessage);

    Note that if you do not complete the message, it will remain in the queue and may be received again by another receiver.

  • Handle errors and exceptions:

    It’s important to handle errors and exceptions that may occur when sending or receiving messages. For example, you can handle exceptions when creating the ServiceBusClient or ServiceBusSender instances, or when receiving messages from the queue. Here’s an example of how to handle exceptions:

    try
    {
    // Create ServiceBusClient and ServiceBusSender instances
    // Send and receive messages
    }
    catch (Exception ex)
    {
    Console.WriteLine(ex.Message);
    }

    You can also use retry policies to automatically retry message processing in case of transient errors. Azure Service Bus provides built-in retry policies that can be configured to retry message processing with exponential backoff. For example:

    ServiceBusSenderOptions senderOptions = new ServiceBusSenderOptions
    {
    RetryOptions = new ServiceBusRetryOptions
    {
    Mode = ServiceBusRetryMode.Exponential,
    MaxRetries = 10,
    Delay = TimeSpan.FromSeconds(10),
    MaxDelay = TimeSpan.FromSeconds(30)
    }
    };
    ServiceBusSender sender = client.CreateSender(queueName, senderOptions);

    These are the basic steps to create a console-based application in C# using Visual Studio Code and Azure Service Bus, and to send and receive messages from a Service Bus queue. You can use these steps as a starting point to build more complex messaging scenarios with Azure Service Bus.

 
Send Message using Service Bus and Console Based Application C#
 
  1. Install the Azure Service Bus SDK package by running the following command in the terminal:

    dotnet add package Microsoft.Azure.ServiceBus
  2. Import the Service Bus namespace in your code:

    using Microsoft.Azure.ServiceBus;
  3. Add your Azure Service Bus connection string and queue name as environment variables:

    string connectionString = Environment.GetEnvironmentVariable("SERVICE_BUS_CONNECTION_STRING");
    string queueName = Environment.GetEnvironmentVariable("SERVICE_BUS_QUEUE_NAME");
  4. Create a new instance of the ServiceBusClient class:

    ServiceBusClient client = new ServiceBusClient(connectionString);
  5. Create a new instance of the ServiceBusSender class:

    ServiceBusSender sender = client.CreateSender(queueName);
  6. Create a new message:

    string messageBody = "Hello, Service Bus!";
    Message message = new Message(Encoding.UTF8.GetBytes(messageBody));
  7. Send the message to the queue:

    await sender.SendMessageAsync(message);

With these steps, you have created a console-based application in C# and sent a message to an Azure Service Bus queue.

Conclusion:

Azure Service Bus is a powerful messaging service that can help you build robust and scalable applications in the cloud and is a key component in many enterprise-grade solutions.With Service Bus, you can decouple components of your distributed systems and reduce the risk of service outages by ensuring that messages are delivered and processed in a reliable and scalable way.We have also gone through the steps to create a console-based application in C# using Visual Studio Code and the Azure Service Bus SDK, and to send and receive messages from a Service Bus queue

Author: Syed Haroon

Microsoft Certified Trainer |Azure Developer Associate | Technical Coordinator at Kovai.co having 13 years of experience in training on. Net Full Stack and Software Development, Pursuing Ph.D. in Computer Science, and Master of Computer Applications.

Get notified about any future events

Interested in learning more about TechMeet360 or knowing about any future events? Sign up below to get notified.

Back to Top