I have a queue with name QUEUE
in exchange of type topic
. it has 2 messages. one with routing key A
the other B
. payload is of no interest atm.
I need to run 2 different apps (consumers). I want app1 to receive only messages with routing key A and the other only with key B.
I cant find the solution - even if I bing to A only I still receive 2 messages. Whats the point of the routing key if I cant bind a consumer to it?
How do I do it?
I ran into the same question / confusion when i first started working with RabbitMQ. It seemed really odd to me.
Eventually I realized I was thinking about the relationship between exchanges, queues and bindings, backward.
Consumers don't consume from an exchange or a routing key. Consumers consume from a queue.
That is the only thing a consumer should know about: the queue from which they consume.
The message publisher, on the other hand, is concerned with publishing to the right exchange with the right routing key, so that the messages end up in the right queue.
To solve your situation, you need to look at what it will take to make App 1 consume from a queue that only receives messages from Queue 1. Similarly, App 2 should only receive messages from Queue 2.
The work of the routing key, then, is to ensure the message gets sent to the right queue.
For example, you could have a topology defined like this:
| exchange | queue | routing key (binding) | |------------|----------|------------------------| | some.ex | queue-1 | key.a | | some.ex | queue-2 | key.b |
App 1 would only consume messages from queue-1
and App 2 would only consume messages from queue-2
. When you publish a message through some.ex
exchange, you provide the routing key and the bindings for the exchange say "key.a goes to queue-1" and "key.b goes to queue-2".
this is a very simple example of the configuration that you could use to get the right messages to the right consumer. there are a lot of potential configurations for what you want.
the primary point, though, is that your consumer must be able to handle any message sent to the queue from which it reads. therefore, you must only send messages that the consumer can handle to the queue from which the consumer reads.