
Working with message routing using direct exchanges
In this recipe we are going to see how to select a subset of messages to be consumed, routing them only to the AMQP queues of interest and ignoring all the others.
A typical use case is implementing a chat, where each queue represents a user.
We can find the relative example in the book examples directory at:
Chapter01/Recipe07/Java_7/src/rmqexample/direct
Getting ready
To use this recipe we need to set up the Java development environment as indicated in the Introduction section.
How to do it…
We are going to show how to implement both the producer and the consumer, and see them in action. To implement the producer, perform the following steps:
- Declare a direct exchange:
channel.exchangeDeclare(exchangeName, "direct", false, false, null);
- Send some messages to the exchange, using arbitrary
routingKey
values:channel.basicPublish(exchangeName, routingKey, null, jsonBook.getBytes());
To implement the consumer, perform the following steps:
- Declare the same exchange, identical to what was done in step 1.
- Create a temporary queue:
String myQueue = channel.queueDeclare().getQueue();
- Bind the queue to the exchange using the
bindingKey
. Perform this operation as many times as needed, in case you want to use more than one binding key:channel.queueBind(myQueue,exchangeName,bindingKey);
- After having created a suitable consumer object, start consuming messages as already seen in the Consuming messages recipe.
How it works…
In this recipe we have published messages (step 2) tagged with an arbitrary string (the so called routing key), to a direct exchange.
As with fanout
exchanges, messages are not stored if there are no queues bound; however, in this case the consumers can choose the messages to be forwarded to these queues, depending on the binding key specified when they are bound (step 5).
Only messages with a routing key equal to the one specified in the binding will be delivered to such queues.
However, it's possible to have more queues bound with the same binding key; in this case, the broker will place a copy of the matching messages in all of them.
It is also possible to bind many different binding keys to the same queue/exchange pair, letting all the corresponding messages be delivered.
There's more…
In case we deliver a message with a given routing key to an exchange, and there are no queues bound with that specific key, the message is silently dropped.
However, the producer can detect and behave consequently when this happens, as shown in detail in the Handling unroutable messages recipe.