Mark As Completed Discussion

Publishing and Consuming Messages

Once RabbitMQ is set up, you can start publishing and consuming messages using RabbitMQ. This allows different components of a distributed system to communicate with each other.

Publishing Messages

To publish a message, you need to create a Publisher class. First, create a connection to the RabbitMQ server using the connection factory. Then, create a channel using the connection object. Declare a queue to which the message will be published using channel.QueueDeclare(). Finally, use channel.BasicPublish() to publish the message to the queue. Here's an example:

TEXT/X-CSHARP
1const message = "Hello, world!";
2
3using (var connection = factory.CreateConnection())
4{
5    using (var channel = connection.CreateModel())
6    {
7        channel.QueueDeclare(queue: "my_queue",
8                             durable: false,
9                             exclusive: false,
10                             autoDelete: false,
11                             arguments: null);
12
13        var body = Encoding.UTF8.GetBytes(message);
14
15        channel.BasicPublish(exchange: "",
16                             routingKey: "my_queue",
17                             basicProperties: null,
18                             body: body);
19    }
20}

Consuming Messages

To consume a message, you need to create a Consumer class. Similar to publishing, create a connection to the RabbitMQ server using the connection factory and create a channel. Declare the same queue as in the publisher. Then, create a EventingBasicConsumer and attach a callback function to the Received event. In the callback function, you can process the received message. Finally, start consuming the messages using channel.BasicConsume(). Here's an example:

TEXT/X-CSHARP
1using (var connection = factory.CreateConnection())
2{
3    using (var channel = connection.CreateModel())
4    {
5        channel.QueueDeclare(queue: "my_queue",
6                             durable: false,
7                             exclusive: false,
8                             autoDelete: false,
9                             arguments: null);
10
11        var consumer = new EventingBasicConsumer(channel);
12        consumer.Received += (model, ea) =>
13        {
14            var body = ea.Body;
15            var message = Encoding.UTF8.GetString(body);
16            Console.WriteLine("Received message: " + message);
17        };
18
19        channel.BasicConsume(queue: "my_queue",
20                             autoAck: true,
21                             consumer: consumer);
22    }
23}
C#
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment