Exchanges, bindings and queues: how a message finds a queue

RabbitMQ Course · lesson 2 of 15 · 5 min read

Publishers address exchanges, never queues, and bindings decide where a message lands.

Open this lesson in the learning hub

Key points

  • A publisher never writes to a queue - it publishes to an exchange with a routing key.
  • A binding joins an exchange to a queue and carries the pattern the routing key is tested against.
  • The exchange copies the message into every queue whose binding matches; no match means no copy.
  • The default exchange has the empty name and binds every queue to its own name automatically.
  • Consumers read from queues only, so one publish can feed one queue or twenty with no code change.
  • Declarations are idempotent, but redeclaring with different arguments fails with 406 PRECONDITION_FAILED.

Example

// 1. the exchange: durable so it survives a restart
ch.exchangeDeclare("orders", BuiltinExchangeType.TOPIC, true);

// 2. the queue: durable, not exclusive, not auto-delete
ch.queueDeclare("invoicing", true, false, false, null);

// 3. the binding: this is what does the routing
ch.queueBind("invoicing", "orders", "order.created");

// 4. publish - note the exchange name, never the queue name
ch.basicPublish("orders", "order.created",
                MessageProperties.PERSISTENT_TEXT_PLAIN, body);

// the default exchange is the one exception: routing key = queue name
ch.basicPublish("", "invoicing", null, body);

Publishers address exchanges, consumers read queues, and bindings are the only thing that joins them.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the RabbitMQ Course course, and every lesson in it is listed on the RabbitMQ Course contents page.