RabbitMQ Direct Exchange in C# to Publish or Consume Messages

In rabbitmq, Direct Exchange will deliver messages to the queues based on the message routing key. In direct exchange, the message is routed to the queues whose binding key exactly matches the routing key of the message.

 

Generally, in rabbitmq when the producer creates a message that will not directly send to the queue, instead first the message will be sent to exchanges, then after that, a routing agent reads and sends it to the appropriate queue with help of header attributes, bindings and routing keys.

 

In rabbitmq, we have different types of exchanges available are

 

  • Direct
  • Fanout
  • Topic
  • Headers

To know more about exchanges in rabbitmq, check this RabbitMQ Exchanges.

 

Following is the pictorial representation of message flow in rabbit direct exchange.

 

RabbitMQ Direct Exchange Process Flow Diagram

 

Now, we will learn how to use Direct Exchange to push and read messages from rabbitmq in c# or .net application with examples.

C# Create RequestRabbitMQ Application

Let’s create a simple console application with the Name “RequestRabbitMQ” as shown below to publish messages to the rabbitmq queue using direct exchange in c#.

 

C# Create Application to Publish Messages to RabbitMQ

 

After creating an application, now we will add the “RabbitMQ.Client” NuGet package in our c# application to communicate with rabbitmq server to publish or consume messages from queues in rabbitmq.

Add RabbitMQ.Client NuGet Package

In c#, we can publish or consume messages from rabbitmq by using RabbitMQ.Client NuGet package for that, right-click on your application and select Manage NuGet Packages as shown below.

 

C# Add RabbitMQ.Client Nuget Package Reference to Application

 

Now search for RabbitMQ.Client package and install it in your application as shown below.

 

C# Adding RabbitMQ.Client NuGet Package Reference

 

Following is another way to install RabbitMQ.Client package by using Package Manager Console as shown below by entering the following command.

 

Command to install - Install-Package RabbitMQ.Client -Version 5.1.0 

 

C# Add RabbitMQ.Client Nuget Package Reference from Package Manager Console

 

Before we start writing a code in c# to publish messages to rabbitmq, we will create a direct exchange, queue and will bind a queue to exchange using the web admin console.

RabbitMQ Create Direct Exchange

To create an exchange in rabbitmq web management portal, open http://localhost:15672/#/exchanges url and then go to Add a new exchange panel and enter details as shown below by selecting Type as “direct” and click on Add exchange button to create an exchange (request.exchange).

 

RabbitMQ Create New Direct Exchange

 

After creating an exchange (request.exchange), next, we will create a queue (request.queue) in the web management portal.

RabbitMQ Create a Queue

To create a queue in rabbitmq web management portal, open http://localhost:15672/#/queues url and then go to Add a new queue panel and enter details as shown below, and click on add queue button to create a queue (request.queue).

 

RabbitMQ Direct Exchange Create New Queue

 

After creating a queue and exchange, next, we need to bind a queue with an exchange in rabbitmq web admin console.

RabbitMQ Bind Queue to Exchange

To bind a queue with an exchange, click on the queue (request.queue) name, then the Bindings panel will expand and enter details like exchange name as “request.exchange”, routing key as “directexchange_key”, and click on Bind button. After binding a queue to exchange, the binding will be as shown below.

 

RabbitMQ Binding a Queue to Direct Exchange

 

After the completion of binding a queue to exchange, now we will publish messages from the c# application to rabbitmq queue using RabbitMQ.Client service.

 

In c#, by using the BasicPublish method of RabbitMQ.Client service we can publish a messages to particular queue based on our requirements.

 

Following is the definition of rabbitmq BasicPublish method in c#.

 

RabbitMQ.Client Service BasicPublish method to publish messages to queue

 

If you observe the BasicPublish method, it accepts multiple parameters like a model, exchange, routing key, properties, and required message to publish in rabbitmq queue.

 

Following is the sample way of calling the BasicPublish method to publish a message to rabbitmq queue in c# programming language.

 

// Publish message to Queue
model.BasicPublish("demoExchange", "directexchange_key", properties, messagebuffer);

C# Publish Messages to RabbitMQ

To publish messages to the rabbitmq queue, add a class with the name “Directmessages.cs” in your application as shown below.

 

RabbitMQ Publisher Add Class File to Publish Messages to Queue

 

Now, open Directmessages.cs class file and write the code as shown below.

Directmessages.cs

using RabbitMQ.Client;
using System;
using System.Text;

namespace RequestRabbitMQ
{
  public class Directmessages
  {
     private const string UName = "guest";
     private const string PWD = "guest";
     private const string HName = "localhost";
     public void SendMessage()
     {
        //Main entry point to the RabbitMQ .NET AMQP client
        var connectionFactory = new ConnectionFactory()
        {
           UserName = UName,
           Password = PWD,
           HostName = HName
        };
        var connection = connectionFactory.CreateConnection();
        var model = connection.CreateModel();
        var properties = model.CreateBasicProperties();
        properties.Persistent = false;
        byte[] messagebuffer = Encoding.Default.GetBytes("Direct Message");
        model.BasicPublish("request.exchange", "directexchange_key", properties, messagebuffer);
        Console.WriteLine("Message Sent");
     }
  }
}

If you observe the above code, to establish a connection with rabbitmq server we are passing the required credentials along with the HostName to ConnectionFactory() method. After that, we are publishing a message (Direct Message) to the queue by passing the required parameters like an exchange, routing key, properties, and message to the BasicPublish method.

 

Now open Program.cs class file and write a code in the Main method to call Directmessages.cs class to get messages from rabbitmq.

Program.cs

Following is the code which we need to write in Program.cs class file Main method to publish messages to rabbitmq server.

 

using System;

namespace RequestRabbitMQ
{
   class Program
   {
     static void Main(string[] args)
     {
        Directmessages directmessages = new Directmessages();
        directmessages.SendMessage();
        Console.ReadLine();
     }
   }
}

When we execute the above c# program, we will get the result as shown below.

 

C# Publish Message RabbitMQ Queue using Direct Exchange Example Result

 

After executing the above program, if we check the queue (request.queue) details in the rabbitmq web management portal, the Ready column is having 1 as shown below which means the message was published successfully to request.queue.

 

RabbitMQ Queue with Messages

 

After publishing a message to the queue, now will learn how to consume or get messages from rabbitmq using RabbitMQ.Client service in c# or .net application with examples.

C# Create RabbitMQConsumer Application

Let’s create a simple console application with the Name “RabbitMQConsumer” as shown below to consume or read messages from the rabbitmq queue.

 

C# Console Application to Read or Consume Messages from RabbitMQ

 

After creating an application, now add the “RabbitMQ.Client” NuGet package reference to your application as we did in publishing the application to communicate with the rabbitmq server.

C# Consume Messages from RabbitMQ

After installing RabbitMQ.Client, next add a class with the name “MessageReceiver.cs” in your application as shown below to read or get messages from queues in rabbitmq.

 

C# Console Application Add New Class File to Read Messages from RabbitMQ

 

Now, open MessageReceiver.cs class file and write the code as shown below.

MessageReceiver.cs

using System;
using System.Text;
using RabbitMQ.Client;

namespace RabbitMQConsumer
{
  public class MessageReceiver : DefaultBasicConsumer
  {
    private readonly IModel _channel;
    public MessageReceiver(IModel channel)
    {
      _channel = channel;
    }
    public override void HandleBasicDeliver(string consumerTag, ulong deliveryTag, bool redelivered, string exchange, string routingKey, IBasicProperties properties, byte[] body)
    {
       Console.WriteLine($"Consuming Message");
       Console.WriteLine(string.Concat("Message received from the exchange ", exchange));
       Console.WriteLine(string.Concat("Consumer tag: ", consumerTag));
       Console.WriteLine(string.Concat("Delivery tag: ", deliveryTag));
       Console.WriteLine(string.Concat("Routing tag: ", routingKey));
       Console.WriteLine(string.Concat("Message: ", Encoding.UTF8.GetString(body)));
       _channel.BasicAck(deliveryTag, false);
    }
  }
}

If you observe the above code, we created a MessageReceiver class and it’s inheriting from DefaultBasicConsumer class of RabbitMQ.Client service and we implemented a HandleBasicDeliver method by overriding it to receive a message body.

 

Now open Program.cs class file and write a code in the Main method to call MessageReceiver.cs class to get messages from rabbitmq.

Program.cs

Following is the code which we need to write in Program.cs class file Main method to receive data from rabbitmq server.

 

using System;
using RabbitMQ.Client;

namespace RabbitMQConsumer
{
  class Program
  {
    private const string UName = "guest";
    private const string Pwd = "guest";
    private const string HName = "localhost";

    static void Main(string[] args)
    {
      ConnectionFactory connectionFactory = new ConnectionFactory
      {
        HostName = HName,
        UserName = UName,
        Password = Pwd,
      };
      var connection = connectionFactory.CreateConnection();
      var channel = connection.CreateModel();
      // accept only one unack-ed message at a time
      // uint prefetchSize, ushort prefetchCount, bool global
      channel.BasicQos(0, 1, false);
      MessageReceiver messageReceiver = new MessageReceiver(channel);
      channel.BasicConsume("request.queue", false, messageReceiver);
      Console.ReadLine();
    }
  }
}

If you observe the above example, to establish a connection with rabbitmq server we are passing the required credentials along with the HostName to ConnectionFactory() method. After that, we created a connection and channel by calling the “CreateConnection” and “CreateModel” methods and we set a prefetchCount to 1 so that it tells RabbitMQ not to give more than one message at a time to the worker.

 

Next, we created an instance of MessageReceiver class and passed IModel (channel) to it, in the final step we called the “BasicConsume” method and passed the queue name to it “request.queue” along with we have set autoAck to false and passed the messageReceiver instance to it. 

 

Here, prefetchCount is used to tell RabbitMQ not to give more than one message at a time to the worker. Or, in other words, don't dispatch a new message to a worker until it has been processed and acknowledged the previous one. Instead, it will dispatch to the next worker that is not still busy. 

 

When we execute our application, we will get messages from the queue (request.queue) as shown below.

 

C# RabbitMQ Direct Exchange Consuming Data from Queue Example Result

 

This is how we can use rabbitmq direct exchanges to consume or read messages from queues in c# using RabbitMQ.Client service based on our requirements.