Using .Net Core With RabbitMQ For Async Operations

Using .Net Core with RabbitMQ for async operations

This article will explain RabbitMQ and its usage. Also, I will present a practical example of how to post data on a RabbitMQ queue and how to read the data from this queue.
To publish in the queue we will use a .Net Core Web Api and to read from the queue we will use a .Net Core Console application. 

What is RabbitMQ?

RabbitMQ is an open-source message broker that implements the message queue protocol, being able to exchange messages between publishers and listeners among different channels and routes.
Among RabbitMQ's main features, find some important ones below, with a brief explanation of it
A message is a key part of RabbitMQ communication. It moves through channels, from publisher to listeners, and can have any kind of information, from simple text to complex objects serialized.
Channel is a logical communication line between the publisher and the listeners. It stands on an existent connection and may transfer messages through different protocols.
A RabbitMQ queue works following FIFO pattern for storing messages between publishers and listeners.
A RabbitMQ connection is based on protocols, is the base for having channels running and, as its names say, connects the server to the client. 
RabbitMQ client, which is connected to a channel listening to its queues in order to read the messages published on it.
RabbitMQ client, which is connected to a queue publishing messages to it.
Notifications are related to monitoring the service health and may be customized in order to alert based on metrics.
Dead letter
In RabbitMQ, the dead letters are used to store messages that were not able to be read by their listeners. It may not be read because the message was rejected by the listeners, or because the queue was full or due to the message expiration time.
RabbitMQ routes are responsible to send the messages to their correct queues based on their routing keys and exchanges. 
Virtual Host 
Comparing with a SQL Server database, a RabbitMQ Virtual Host would be a SQL Server Database. Virtual Hosts have their own settings and are independent of others Virtual Hosts, they have their own channels, bindings, protocols, users, etc..
RabbitMQ exchange is responsible for routing messages to their queues based on their attributes.
A RabbitMQ binding works like a link from the queue to an exchange.

Main benefits of RabbitMQ usage

  • Multi-platform communication, with messages being serialized/deserialized in common languages such as JSON;
  • Async operations, not leaving services locked waiting for an answer;
  • Open-Source, with a large community working to improve its features daily;
  • Multi-language, with a wide range of languages accepted;
  • Multi-protocol, with different types of protocols used to exchange messages.

Implementation Step by Step

In this sample, will be used a Web Api posting user locations in a RabbitMQ queue and a console application in a different solution reading and displaying this data.
Downloads required
Default RabbitMQ configuration
  • Endpoint address: http://localhost:15672/
  • Login: guest
  • Password: guest 
  • Windows Service Name: RabbitMQ
  • Windows menu item to start the service: RabbitMQ Service - start

Creating the .Net Core Web Api to publish user locations in the RabbitMQ queue

For this sample, I used my previous Web Api project using swagger as a base. You may find the complete article explaining how to create a .Net Core Web Api using swagger below as far as the GitHub URL to download the project.

Remove the controller and model

In order to have a better experience, we are using a new model and controller so the old ones were removed.

Add a new class

This class will have location properties as follows, 
  1. public class Location  
  2.   {  
  3.       public DateTime Date { getset; }  
  4.       public double Latitude { getset; }  
  5.       public double Longitude { getset; }  
  6.   }  

Add a new controller 

This controller will have an HTTP Post to publish in the RabbitMQ queue as follows,
  1. [Route("api/[controller]")]  
  2.     [ApiController]  
  3.     public class LocationController : ControllerBase  
  4.     {  
  5.         [HttpPost]  
  6.         public void Post([FromBody]Location location)  
  7.         {  
  8.             var factory = new ConnectionFactory() { HostName = "localhost" };  
  9.             using (var connection = factory.CreateConnection())  
  10.             using (var channel = connection.CreateModel())  
  11.             {  
  12.                 channel.QueueDeclare(queue: "locationSampleQueue",  
  13.                                      durable: false,  
  14.                                      exclusive: false,  
  15.                                      autoDelete: false,  
  16.                                      arguments: null);  
  18.                 string message = "Latitude: " + location.Latitude + ", Longitude: " + location.Longitude + " and Time: " + location.Date;  
  19.                 var body = Encoding.UTF8.GetBytes(message);  
  21.                 channel.BasicPublish(exchange: "",  
  22.                                      routingKey: "locationSampleQueue",  
  23.                                      basicProperties: null,  
  24.                                      body: body);  
  25.             }  
  26.         }  
  27.     }  

Run your Web Api Project

If you used my project base, or have installed and configured Swagger, you may access your endpoint from it.
Validating results
Inputting sample data,
Date: 2019-11-17
Latitude: 1922.970
Longitude -1293.3120
Validate the controller
Checking if input data is correct, as follows,
Validate RabbitMQ
Checking if RabbitMQ was created,
Checking the message in the queue,
Creating the .Net Core console application to read user locations from the RabbitMQ queue
Now that we are able to publish messages in our RabbitMQ queue, the next step is to create a listener to subscribe to this queue and read its messages, as follows:
Create the .Net Core Console Application project
Update the Program.cs
In order to subscribe to this queue and write its information on the console, we only need the following code, 
  1. static void Main(string[] args)  
  2.    {  
  3.        var factory = new ConnectionFactory() { HostName = "localhost" };  
  4.        string queueName = "locationSampleQueue";  
  5.        var rabbitMqConnection = factory.CreateConnection();  
  6.        var rabbitMqChannel = rabbitMqConnection.CreateModel();  
  8.        rabbitMqChannel.QueueDeclare(queue: queueName,  
  9.                             durable: false,  
  10.                             exclusive: false,  
  11.                             autoDelete: false,  
  12.                             arguments: null);  
  14.        rabbitMqChannel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);  
  16.        int messageCount = Convert.ToInt16(rabbitMqChannel.MessageCount(queueName));  
  17.        Console.WriteLine(" Listening to the queue. This channels has {0} messages on the queue", messageCount);  
  19.        var consumer = new EventingBasicConsumer(rabbitMqChannel);  
  20.        consumer.Received += (model, ea) =>  
  21.         {  
  22.             var body = ea.Body;  
  23.             var message = Encoding.UTF8.GetString(body);  
  24.             Console.WriteLine(" Location received: " + message);  
  25.             rabbitMqChannel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);  
  26.             Thread.Sleep(1000);  
  27.         };  
  28.        rabbitMqChannel.BasicConsume(queue: queueName,  
  29.                             autoAck: false,  
  30.                             consumer: consumer);  
  32.        Thread.Sleep(1000 * messageCount);  
  33.        Console.WriteLine(" Connection closed, no more messages.");  
  34.        Console.ReadLine();  
  35.    }  
Validate the result
Checking that the console application is running:
Checking the console application,
Projects on GitHub,
Congratulations! You have successfully created your first application to publish and listen to a RabbitMQ queue.
External References