principlejavascriptModerate
RabbitMQ Exchanges and Queue Bindings
Viewed 0 times
rabbitmqexchangerouting keyamqpfanouttopic exchangedirect exchangequeue binding
Problem
Messages sent to RabbitMQ are not reaching the intended consumers, or all consumers receive every message when only specific ones should.
Solution
Publish messages to an exchange (not directly to a queue). Choose the exchange type: direct (exact routing key match), fanout (broadcast to all bound queues), topic (wildcard routing key patterns), headers (header-based routing). Bind queues to the exchange with the appropriate routing key.
Why
Exchanges decouple producers from consumers. The producer does not need to know which queues exist — it just publishes to an exchange with a routing key.
Gotchas
- Publishing to a non-existent exchange or queue silently drops the message unless you use mandatory: true and a return listener.
- Durable exchanges and durable queues survive broker restarts. Transient ones do not. Ensure both match — you cannot bind a durable queue to a transient exchange.
- The default exchange (empty string '') routes directly by queue name — this is a direct exchange and is not explicitly declared.
Code Snippets
RabbitMQ topic exchange publish/consume
// Publisher
await channel.assertExchange('events', 'topic', { durable: true });
await channel.publish('events', 'order.created', Buffer.from(JSON.stringify(order)));
// Consumer (receives order.* events)
await channel.assertQueue('order-processor', { durable: true });
await channel.bindQueue('order-processor', 'events', 'order.*');
await channel.consume('order-processor', async (msg) => {
const data = JSON.parse(msg.content.toString());
await processOrder(data);
channel.ack(msg);
});Revisions (0)
No revisions yet.