In this article, we are going to discuss Microsoft Azure Service Bus Queues. First, we will see what is Azure Service Bus and then discuss more about queues. We are also going to build a simple application to send and receive messages in queues using ASP.NET Core. So let’s grab a cup of coffee and start learning.

What is Azure Service Bus?

Azure Service Bus is a message broker service that is hosted on the Azure platform and it provides functionality to publish messages to various applications and also decouple the applications.

According to Microsoft documentation,

Microsoft Azure Service Bus is a fully managed enterprise integration message broker. Service Bus can decouple applications and services. Service Bus offers a reliable and secure platform for asynchronous transfer of data and state.

Data is transferred between different applications and services using messages. A message is in binary format and can contain JSON, XML, or just text.

Microsoft service bus comes in different flavors,

Azure Service Bus Queues

Queues follow a First-In-First-Out (FIFO) pattern. Queues provide one-way transport the sender is going to send the message in the queue and the receiver collects messages from the queue. In queues, there is a 1:1 relationship between the sender and receiver. Messages are present in the queue until the receiver processes and completes the messages.

Azure Service Bus

The queue contains a secondary sub-queue, called a dead-letter queue (DLQ). Whenever we create a queue DLQ is automatically added in our main queue. When the messages are not delivered to the receiver or cannot be processed by the receiver then such messages are pushed to DLQ.

Now we have discussed enough regarding Queues so let's create queues in Azure and build a simple application to send and receive messages from the queue.

Creating a simple application to send and receive messages from the queue.

Prerequisites

Overview of the application

We will be creating a simple application which consists of 3 parts,

That's it. We have created our first queue.

Create Web API to push the message into Queue

Prerequisites

The first thing is to create a new ASP.NET Core Web API project. For those who are new to ASP.NET Core, I have listed down the steps to create a new Web API project.

Create a new class called Order.cs and add below properties,

namespace Order.Web.API
{
    public class Order
    {
        public int Id { get; set; }
        public int Quantity { get; set; }
        public decimal Price { get; set; }
    }
}

To interact with Azure Service Bus Microsoft.Azure.ServiceBus package provides something called QueueClient which accepts queue connection string and queue name as input and returns the QueueClient object. First, we grab the connection string of Queue from Azure Portal. So open the queue and click on Shared access policies then select RootManageSharedAccessKey and copy it into the appsettings.json file.

RootManageShared

appsettings.json

{
  "QueueConnectionString": "<replace your RootManageSharedAccessKey here>",
  "QueueName": "order-queue",
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Create a new controller called OrdersController and add the below code to push messages into the queue,

using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.ServiceBus;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;

namespace Order.Web.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class OrdersController : ControllerBase
    {
        private readonly IConfiguration _configuration;

        public OrdersController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        [HttpPost]
        public async Task<IActionResult> CreateOrderAsync([FromBody] Order order)
        {
            IQueueClient queueClient = new QueueClient(_configuration["QueueConnectionString"], _configuration["QueueName"]);
            var orderJSON = JsonConvert.SerializeObject(order);
            var orderMessage = new Message(Encoding.UTF8.GetBytes(orderJSON))
            {
                MessageId = Guid.NewGuid().ToString(),
                ContentType = "application/json"
            };

            await queueClient.SendAsync(orderMessage).ConfigureAwait(false);

            return Ok("Create order message has been successfully pushed to queue");
        }
    }
}

So we created the QueueClient object and then we created Message. We used the SendAsync() method to push messages to the queue.

We are testing this using Postman. Run the app and hit post API to push the order into Queue.

Post API

After a successful POST call let's go to Azure Portal and see if the message is pushed to the queue. So we have 1 active message in the queue.

POST call

Conclusion

In Part 1 of the Azure Service Bus Queue series, we have learned how to create a queue through Azure Portal and also we have created a Web API that pushes a message to the Queue. In Part 2 we will create a Background Service which will read messages from the Queue.

I really hope that you enjoyed this article, share it with friends and please do not hesitate to send me your thoughts or comments.

You can follow me on Twitter @sumitkharche01

Happy Coding!!