C# Read (Consume) Messages from RabbitMQ Queue

In c#, we can read or consume a messages from rabbitmq by using RabbitMQ.Client nuget package. Here, we will learn how to consume or get a messages from rabbitmq using RabbitMQ.Client service in c# or .net application with examples.

C# Create RabbitMQConsumer Application

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

 

C# RabbitMQ Consumer Console Application

 

After creating an application, now we will add “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 need to add “RabbitMQ.Client” nuget package in our application to communicate with RabbitMQ server to publish or consume messages for that, right click on your application and select Manage NuGet Packages like as shown below.

 

C# Add RabbitMQ.Client Nuget Package Reference to Application

 

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

 

C# Add RabbitMQ.Client Nuget Package Reference to Application

 

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

 

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

 

Package Manager Console to Add RabbitMQ.Client Service in C#

 

After installing RabbitMQ.Client, next add a class with name “MessageReceiver.cs” in your application like as shown below.

 

C# Add MessageReceiver Class File to Handle RabbitMQ

 

Now, open MessageReceiver.cs class file and write the code like 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 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 Main method to call MessageReceiver.cs class to get a messages from rabbitmq.

Program.cs

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

 

using System;

using RabbitMQ.Client;

 

namespace RabbitMQConsumer

{

    class Program

    {

        private const string UserName = "guest";

        private const string Password = "guest";

        private const string HostName = "localhost";

 

        static void Main(string[] args)

        {

            ConnectionFactory connectionFactory = new ConnectionFactory

            {

                HostName = HostName,

                UserName = UserName,

                Password = Password,

            };

            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("demoqueue", false, messageReceiver);

            Console.ReadLine();

        }

    }

}

If you observe above example, to establish a connection with rabbitmq server we are passing a required credentials along with HostName to ConnectionFactory() method. After that, we created a connection and channel by calling “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 worker.

 

Next, we have created an instance of MessageReceiver class and passed IModel (channel) to it, in final step we have called “BasicConsume” method and passed queue name to it “demoqueue” 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 worker. Or, in other words, don't dispatch a new message to a worker until it has processed and acknowledged the previous one. Instead, it will dispatch to the next worker that is not still busy.

 

Now we are done with the creation of rabbitmq consumer application. Before we start reading the data from rabbitmq server, first we need to publish the message to rabbitmq queue (demoqueue) for that check C# Publish Messages to RabbitMQ Queue article.

 

After we publish data to rabbitmq queue (demoqueue) that will be like as shown below.

 

C# Publish Messages to RabbitMQ Queue Example Result

 C# Read Messages from RabbitMQ Queue Example Result

After publishing the messages to queue run your c# consumer application to read messages from rabbitmq and that will return the result like as shown below.

 

C# Read (Consume) Messages from RabbitMQ Queue Example Result

 

This is how we can consume or rea a messages from rabbitmq queues in c# using RabbitMQ.Client service based on our requirements.