Reputation: 725
I am new to rabbitMQ and have requirement to publish the message one or more than one queue based on message type.
Lets say, I am getting messages of type M1, M2, M3 and have two queues Q1, Q2. If message type is M1 or M2, then it need to be published to queue Q1 only . If message type is M3, then need to be published to Q1 and Q2 both.
Please suggest how could I achieve this? Thanks.
Upvotes: 0
Views: 901
Reputation: 72888
This is what exchanges, bindings and routing keys allow you to do.
In your case, the type of exchange should either be "direct" or "topic". I don't think it makes much difference for you in this simple scenario. Given that, I'll go with "direct" for now.
First you need to create your exchange
Next, create your queues.
The important part is what happens after this: the bindings between the exchange and the queues.
Based on your description, I see the following requirements for message flow:
These are basically the bindings that you need to create from your exchange to the queues, where the message type is the routing key.
It would look something like this, if you wanted to document it more completely.
| Exchange | Routing Key | Queue | | -------- | ----------- | ----- | | ex1 | M1 | Q1 | | ex1 | M2 | Q1 | | ex1 | M3 | Q1 | | ex1 | M3 | Q2 |
Now, when publishing a message to this exchange, you would set the message type as the routing key. This will ensure the message flows to the correct queue.
The main difference between a direct and topic exchange - which are the two real options you have here - is that a direct exchange does a literal string match on the routing key, while a topic exchange allows pattern matching.
If you have complex routing requirements with a highly structures routing key (highly structured, as in "this.that.whatever.something" type of formatting) then a topic exchange is a better choice. topics allow you to match portions of the routing key to specific routes and queues.
The question of which type of exchange to use is not always obvious. I tend to default to direct exchanges... but i don't have a good reason for this. many people will tell you that you should default to topic exchanges. i don't think it matters. the more important issue is understanding when you need a topic and pattern matching. i wrote a short ebook on rabbitmq layout that uses stories based on real world experiences to explain some of the differences of when to use which one, if you're interested.
Upvotes: 1
Reputation: 854
Producer will produce all messages to one exchange (type: topic) with message type as routing key. And the exchange should be bound to different queues with routing key. In your case "Q1" should be bound to exchange with 2 bindings : One "#.M2.#" and another "#.M2.#". It implies any message to the exchange with routing key M1 or M2 should go to Q1.
Upvotes: 1