Junior — Middle
How is message passing implemented in RabbitMQ system?
sobes.tech AI
Answer from AI
In RabbitMQ, message transmission occurs through exchanges and queues. The process looks like this:
- Producer sends a message to an exchange.
- Exchange routes the message to one or more queues according to rules (binding).
- Consumer subscribes to the queue and receives messages from it.
Thus, messages are not sent directly from producer to consumer but pass through an exchange and a queue, which provides flexibility and reliability.
Example of sending a message in RabbitMQ using C# with the RabbitMQ.Client library:
var factory = new ConnectionFactory() { HostName = "localhost" };
using(var connection = factory.CreateConnection())
using(var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null);
string message = "Hello RabbitMQ!";
var body = System.Text.Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange: "", routingKey: "hello", basicProperties: null, body: body);
Console.WriteLine(" [x] Sent {0}", message);
}