Getting Started With Azure Service Bus Queues And ASP.NET Core - Part 1

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 which 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,
  • Queues
  • Topic (we will cover this in next articles) 

Azure Service Bus: Queues

 
Queues follow a 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 the queue until the receiver processes and completes the messages.
 
Getting Started With Azure Service Bus Queues And ASP.NET Core
 
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,
  • Create Azure Service Bus Queue using Azure Portal (Covered in this article)
  • Create Web API to push the message into Queue (Covered in this article)
  • Create a Background Service to receive a message from Queue (Covering in Part 2) 
Getting Started With Azure Service Bus Queues And ASP.NET Core
 
Creating Azure Service Bus Queue using Azure Portal
  • Login to Azure and click on Create a resource button. 
  • In the search box type service bus and select it.
Getting Started With Azure Service Bus Queues And ASP.NET Core
  • Click on Create button. You will see the Create Namespace page. 
Getting Started With Azure Service Bus Queues And ASP.NET Core
  • Azure has Resource Groups (RG) which acts as a container for your resources. So now we are going to create a Service bus resource. 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 a unique RG name. 
Getting Started With Azure Service Bus Queues And ASP.NET Core
  • 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,
    • Basic
    • Standard
    • Premium
Getting Started With Azure Service Bus Queues And ASP.NET Core
  • We have filled in all details so click on Review + create button.
Getting Started With Azure Service Bus Queues And ASP.NET Core
  • Review everything is added property and finally click on Create button. 
Getting Started With Azure Service Bus Queues And ASP.NET Core
  • Creating resources will take time. 
Getting Started With Azure Service Bus Queues And ASP.NET Core
  • Now our order queue is created successfully.
Getting Started With Azure Service Bus Queues And ASP.NET Core
  • 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. 
Getting Started With Azure Service Bus Queues And ASP.NET Core
 
That's it. We have created our first 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:
Getting Started With Azure Service Bus Queues And ASP.NET Core
 
Create a new class called Order.cs and add below properties,
  1. namespace Order.Web.API  
  2. {  
  3.     public class Order  
  4.     {  
  5.         public int Id { getset; }  
  6.         public int Quantity { getset; }  
  7.         public decimal Price { getset; }  
  8.     }  
  9. }  
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 appsettings.json file. 
Getting Started With Azure Service Bus Queues And ASP.NET Core
 
appsettings.json
  1. {  
  2.   "QueueConnectionString""<replace your RootManageSharedAccessKey here>",  
  3.   "QueueName":  "order-queue",  
  4.   "Logging": {  
  5.     "LogLevel": {  
  6.       "Default""Information",  
  7.       "Microsoft""Warning",  
  8.       "Microsoft.Hosting.Lifetime""Information"  
  9.     }  
  10.   },  
  11.   "AllowedHosts""*"  
  12. }  
 Create a new controller called OrdersController and add below code to push message into queue,
  1. using System;  
  2. using System.Text;  
  3. using System.Threading.Tasks;  
  4. using Microsoft.AspNetCore.Mvc;  
  5. using Microsoft.Azure.ServiceBus;  
  6. using Microsoft.Extensions.Configuration;  
  7. using Newtonsoft.Json;  
  8.   
  9. namespace Order.Web.Api.Controllers  
  10. {  
  11.     [Route("api/[controller]")]  
  12.     [ApiController]  
  13.     public class OrdersController : ControllerBase  
  14.     {  
  15.         private readonly IConfiguration _configuration;  
  16.   
  17.         public OrdersController(IConfiguration configuration)  
  18.         {  
  19.             _configuration = configuration;  
  20.         }  
  21.   
  22.         [HttpPost]  
  23.         public async Task<IActionResult> CreateOrderAsync([FromBody] Order order)  
  24.         {  
  25.             IQueueClient queueClient = new QueueClient(_configuration["QueueConnectionString"], _configuration["QueueName"]);  
  26.             var orderJSON = JsonConvert.SerializeObject(order);  
  27.             var orderMessage = new Message(Encoding.UTF8.GetBytes(orderJSON))  
  28.             {  
  29.                 MessageId = Guid.NewGuid().ToString(),  
  30.                 ContentType = "application/json"  
  31.             };  
  32.             await queueClient.SendAsync(orderMessage).ConfigureAwait(false);  
  33.   
  34.             return Ok("Create order message has been successfully pushed to queue");  
  35.         }  
  36.     }  
  37. }  
  • 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. 
Getting Started With Azure Service Bus Queues And ASP.NET Core
  • 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. 
Getting Started With Azure Service Bus Queues And ASP.NET Core
 

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


Similar Articles