Sobes.tech
Junior — Middle

How are messages routed within RabbitMQ?

sobes.tech AI

Answer from AI

In RabbitMQ, message routing is done through exchanges and queues. The process looks like this:

  1. Producer sends a message to an exchange.
  2. Exchange receives the message and, according to its routing policy, directs it to one or more queues.
  3. Queues store messages until consumers retrieve them.

Exchange types determine routing logic:

  • Direct — routes messages to queues with an exact routing key match.
  • Fanout — sends messages to all bound queues.
  • Topic — routes based on pattern matching of routing keys.
  • Headers — routes based on message headers.

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);

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);

Here, the message is sent to a fanout exchange, which will distribute it to all bound queues.