rabbitmq consumer example in csharp

Here is an example code for a RabbitMQ consumer in C# using the RabbitMQ.Client package:

main.cs
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        var factory = new ConnectionFactory() { HostName = "localhost" };
        using (var connection = factory.CreateConnection())
        using (var channel = connection.CreateModel())
        {
            channel.QueueDeclare(queue: "my_queue",
                                 durable: false,
                                 exclusive: false,
                                 autoDelete: false,
                                 arguments: null);

            var consumer = new EventingBasicConsumer(channel);
            consumer.Received += (model, ea) =>
            {
                var body = ea.Body.ToArray();
                var message = Encoding.UTF8.GetString(body);
                Console.WriteLine("Received message: {0}", message);
            };
            channel.BasicConsume(queue: "my_queue",
                                 autoAck: true,
                                 consumer: consumer);

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
}
1176 chars
36 lines

In this example, the ConnectionFactory class is used to create a connection to the RabbitMQ server running on localhost. A channel is then created using this connection.

The QueueDeclare method is called to create a queue named my_queue if it does not already exist. This method is idempotent, meaning that it will only create the queue if it does not exist yet.

A consumer object of type EventingBasicConsumer is created and attached to the channel. The Received event is subscribed to so that incoming messages are handled by the Received handler delegate.

The BasicConsume method is called to start consuming messages from the my_queue queue. The autoAck parameter is set to true, meaning that the message is automatically acknowledged when it has been received. This parameter controls whether or not the server waits for an acknowledgement from the consumer before deleting the message from the queue.

Finally, the program waits for a key to be pressed before exiting.

related categories

gistlibby LogSnag