Thursday, April 27, 2023

Sample C# Program to Send and Receive Messages using RabbitMQ

Here is a simple C# example that demonstrates how to send and receive messages using RabbitMQ.

You need to install the RabbitMQ client library for your programming. You can typically install this using a package manager for your language (such as NuGet for C#) or by downloading the library directly from the official RabbitMQ website.
using System;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
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())
        {
            // Declare the queue
            channel.QueueDeclare(queue: "hello",
                                 durable: false,
                                 exclusive: false,
                                 autoDelete: false,
                                 arguments: null);

            // Publish a message to the queue
            string message = "Hello World!";
            var body = Encoding.UTF8.GetBytes(message);
            channel.BasicPublish(exchange: "",
                                 routingKey: "hello",
                                 basicProperties: null,
                                 body: body);
            Console.WriteLine(" [x] Sent {0}", message);

            // Create a consumer and receive messages from the queue
            var consumer = new EventingBasicConsumer(channel);
            consumer.Received += (model, ea) =>
            {
                var body = ea.Body;
                var message = Encoding.UTF8.GetString(body);
                Console.WriteLine(" [x] Received {0}", message);
            };
            channel.BasicConsume(queue: "hello",
                                 autoAck: true,
                                 consumer: consumer);

            Console.WriteLine(" Press [enter] to exit.");
            Console.ReadLine();
        }
    }
}
In this example, we declare a queue named "hello", publish a message to the queue, and create a consumer to receive messages from the queue. When the program is run, it sends a message to the queue and waits for a response. When a message is received, it is printed to the console. Note that this example assumes that RabbitMQ is running on the same machine with the default settings.

The response of the above code should be the following:
 [x] Sent Hello World!
 Press [enter] to exit.
This indicates that a message containing "Hello World!" was successfully sent to the "hello" queue.

When you press enter to exit the program, you should see the following message printed to the console:
 [x] Received Hello World!
This indicates that the consumer received the message from the queue and printed it to the console.

No comments:

Post a Comment