Junior — Middle
Can you explain the concept of Exchange in RabbitMQ and how it functions in message transfer?
sobes.tech AI
Answer from AI
In RabbitMQ, an Exchange is a component that receives messages from producers and routes them to queues based on certain rules called routing.
Main types of Exchanges:
- Direct — routes the message to a queue if the routing key matches the queue's key.
- Fanout — sends the message to all queues bound to this Exchange.
- Topic — routes messages based on key pattern matching.
- Headers — routes based on message headers.
Example of operation:
- Producer sends a message to an Exchange with a specific routing key.
- The Exchange checks its rules and binds the message to one or more queues.
- The message is placed in a queue from which the consumer retrieves it.
This allows flexible message routing and system scaling.
Example in C# using RabbitMQ.Client:
var factory = new ConnectionFactory() { HostName = "localhost" };
using var connection = factory.CreateConnection();
using var channel = connection.CreateModel();
channel.ExchangeDeclare(exchange: "logs", type: ExchangeType.Fanout);
string message = "Hello RabbitMQ!";
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange: "logs", routingKey: "", basicProperties: null, body: body);
Console.WriteLine(" [x] Sent {0}", message);