Implementing RabbitMQ🐰, For Point to Point Communication 🚀

In this tutorial, we are going to discuss RabbitMQ, a very popular and user-friendly Message Broker. To get started, let us understand what Message Broker is.
 

What is a Message Broker?

 
A message broker is an architectural pattern for message validation, transformation and routing. It mediates the communication among applications. They are inter-application communication technologies. They help us in building common integration mechanisms for Microservices and other distributed based architectures. The applications built on different languages can also communicate with each other through this. They rely on message queues. The message is consumed in the order they are produced. This message queue is just like traditional queue data structure. It is based on First In First Out Basis.
 
The message brokers offer two message distribution styles,
  1. Point-To-Point
  2. Publisher/Subscriber
The examples of message brokers are,
  1. RabbitMQ
  2. Apache Kafka
  3. ActiveMQ
  4. KubeMQ
  5. Amazon MQ
  6. Azure Service Bus

What is RabbitMQ?

 
RabbitMQ is an open-source message broker. It is lightweight and can be easily deployed to on-premise or cloud. It can run on many operating systems and provides a wide range of developer tools for many languages. Some features of RabbitMQ are:
  1. Asynchronous Messaging
  2. Distributed Deployment
  3. Management and Monitoring
  4. Extensible through Plugins and Tools
What will be covered in this Tutorial?
 
In this tutorial we are going to implement Point-To-Point communication. In this one message will be sent from Producer to Consumer. We will write 2 methods that can be used in C#. How to Invoke the functions though UI is entirely the choice of the developer. Once invoked, we will then monitor their execution flows.
 
Pre-Requisites
  1. RabbitMQ server is up and running in local or cloud. For local setup details, check here.
  2. Visual Studio 2019, For details check here.
  3. Some Exposure of ASP.NET Core
  4. Some Exposure of RabbitMQ
Install Nuget Package - RabbitMQ.Clientec
 
Package Manager - Install-Package RabbitMQ.Client
 
.NET CLI - dotnet add package RabbitMQ.Client
 
Package Reference - <PackageReference Include="RabbitMQ.Client" Version="6.1.0" />
 
Now, let us look at the source code for Producer and Consumer, we will create 2 functions.
 
Configuration in appsettings.json
  1. {  
  2.    ….  
  3.   "Rabbit-MQ-AMPQ""amqp://[username]:[password]-@[server]/[path]"  
  4.   ….  
  5. }  
Producer, In Application 1
  1. /* 
  2. using RabbitMQ.Models; 
  3. using RabbitMQ.Client; 
  4. using Microsoft.Extensions.Configuration; 
  5. using System.Text; 
  6. */  
  7.  public void Produce(string message)  
  8.         {  
  9.             var factory = new ConnectionFactory()  
  10.             {  
  11.                 Uri = new Uri(configuration["Rabbit-MQ-AMPQ"])  //Through DI
  12.             };  
  13.   
  14.             using (var conn = factory.CreateConnection())  
  15.             {  
  16.                 using (var channel = conn.CreateModel())  
  17.                 {  
  18.   
  19.                     channel.QueueDeclare(queue: "messages_share",  
  20.                                 durable: false,  
  21.                                 exclusive: false,  
  22.                                 autoDelete: false,  
  23.                                 arguments: null);  
  24.   
  25.                     var body = Encoding.UTF8.GetBytes(message);  
  26.                     channel.BasicPublish(exchange: "",  
  27.                                          routingKey: "messages_share",  
  28.                                          basicProperties: null,  
  29.                                          body: body);  
  30.   
  31.                     Console.WriteLine(" [x] Sent {0}", message);  
  32.                 }  
  33.             }  
  34.   
  35.         }  
Explanation of Producer Code
 
Create a connection, open a channel, create the queue. Send the message to the queue. After completion of the task, auto dispose the connections.
 
Consumer, In Application 2
  1. /* 
  2. using Microsoft.Extensions.Configuration; 
  3. using RabbitMQ.Client; 
  4. using RabbitMQ.Client.Events; 
  5. using System; 
  6. using System.Text; 
  7. */  
  8.   
  9. public void Consume()  
  10.         {  
  11.             var factory = new ConnectionFactory()  
  12.             {  
  13.                 Uri = new Uri(configuration["Rabbit-MQ-AMPQ"]) //Through DI  
  14.             };  
  15.   
  16.             var conn = factory.CreateConnection();  
  17.   
  18.             var channel = conn.CreateModel();  
  19.   
  20.             channel.QueueDeclare(queue: "messages_share",  
  21.                             durable: false,   
  22.                             exclusive: false,  
  23.                             autoDelete: false,  
  24.                             arguments: null);  
  25.   
  26.             var consumer = new EventingBasicConsumer(channel);  
  27.               
  28.             consumer.Received += (ch, ea) =>  
  29.             {  
  30.                 var body = Encoding.UTF8.GetString(ea.Body.ToArray());  
  31.                 Console.WriteLine(body + "\n");  
  32.                 channel.BasicAck(ea.DeliveryTag, false);  
  33.             };  
  34.             channel.BasicConsume("messages_share"false, consumer);  
  35.         }  
Explanation of Consumer Code

Connect to the channel, declare the queue (this helps us to ensure that the queue exists). Subscribe to the channel. When a message is received, then perform logic on that message. Do not close the connection, as the channel is open for messages to arrive.

Execution Flow
  1. Call the Consumer function once, only at startup of the application to open the communication channel. The channel will be visible in RabbitMQ Channels Admin UI,
  1. Now send the execution call from the producer function.
  2. The consumer will automatically catch this as the channel is open.
  3. Monitor the activity in Queues Section of RabbitMQ
Overall communication will look like this, the image should be self explanatory:
 
This image shows that the message “Hello There” was fired from Application 1. This message went to RabbitMQ server. The Application 2 had subscribed through a Received event. The message was forwarded from RabbitMQ to Application 2 as part of subscription. This Application 2 Channel was open so it was able to receive the message at same time.
 

SUMMARY

 
We covered Message Broker, About RabbitMQ, Implement RabbitMQ in .NET for Point to Point Communication.
 
Please feel free to share your thoughts, comments and share your knowledge for improvement.