Junior — Middle
How is message delivery to multiple subscribers performed in RabbitMQ?
sobes.tech AI
Answer from AI
In RabbitMQ, message delivery to multiple subscribers is implemented through "fanout" exchange types. Such an exchange broadcasts each received message to all queues bound to it. Thus, each subscriber listening to its own queue will receive a copy of the message.
Example in C# using the RabbitMQ.Client library:
var factory = new ConnectionFactory() { HostName = "localhost" };
using var connection = factory.CreateConnection();
using var channel = connection.CreateModel();
channel.ExchangeDeclare(exchange: "logs", type: ExchangeType.Fanout);
var queueName = channel.QueueDeclare().QueueName;
channel.QueueBind(queue: queueName, exchange: "logs", routingKey: "");
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) => {
var body = ea.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
Console.WriteLine("Received: " + message);
};
channel.BasicConsume(queue: queueName, autoAck: true, consumer: consumer);
Here, each subscriber creates its own queue and binds it to the fanout exchange, receiving all messages.