Getting Started with Azure Service Bus Queues & ASP.NET Core - Part 1

Getting Started with Azure Service Bus Queues & ASP.NET Core - Part 1

In this article, we are going to discuss to about Microsoft Azure Service Bus Queues. First, we will see what is Azure Service Bus and then discuss about queues. We are also going to build a simple application to send and receive message 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 message broker service which is hosted on Azure platform and it provides functionality to publish messages to various application 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:

  • Queues
  • Topic (we will cover this in next articles)

Azure Service Bus: Queues

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

queue-dig

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 can not 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 application

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

  • Create Azure Service Bus Queue using Azure Portal(Covering in this article)
  • Create Web API to push the message into Queue(Covering in this article)
  • Create a Background Service to receive a message from Queue(Covered in next article)

App Structure

Creating Azure Service Bus Queue using Azure Portal

  • Login to Azure and click on Create a resource button.
  • In search box type service bus and select it.

service-bus-new

  • Click on Create button. You will see the Create Namespace page.

create-namespace-page

  • Azure has Resource Groups(RG) which acts as a container for your resources. So now we are going to create a Service bus resource then first we need to create Resource Group. If you have already created RG then you can use the same here. Under Resource group click on Create New button and give unique RG name.

new-rg

  • Now we have to specify the Namespace name. A namespace is a container for all messaging components. Multiple queues and topics can be in a single namespace, and namespaces often serve as application containers.
  • Select the location.
  • Select pricing tier. Azure provides 3 pricing tiers: 1 Basic 2 Standard 3 Premium

pricing-tier

  • We have filled all details the click on Review + create button.

all-filled

  • Review everything added property and finally click on Create button.

final-create

  • Creating resources will take time.

deployment-processing

  • Now our order queue is created successfully.

order-queue

  • Go to the Queues section in the left panel and click on Queue and give a unique name for queue and click on the Create button.

create-queue

Create Web API to push the message into Queue

Prerequisites

  • Visual Studio 19(if you are using .NET Core 3.1)
  • .NET Core 3.1 SDK installed

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.

  • Open Visual Studio and click on File -> New -> Project. Then select ASP.NET Core Web Application and click on the Next button.
  • Give the project name and click on Create button.
  • After that select API and click on Create button.
  • So now your ASP.NET Core Web API project is setup.
  • First we need to install Azure Service Bus NuGet package.

asb-nuget

  • 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 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 appsettings.json file.

connection-string

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 below code to push message into 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 have created QueueClient object and then we created Message. We used SendAsync() method to push message to the queue.

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

postman

  • 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.

queue-message

Conclusion

In this 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!!