Topic Exchange and Headers Exchange in RabbitMQ

Topic Exchange

In Topic exchange the producer publishes the message along with group of words and those words are separated with dot (.) and when topic exchange gets the key it matches the key with the binding key of the queue if the pattern matches and the message gets routed to that queue.

So basically the Topic exchange doesn't match the key, it matches the pattern of the key.

Example:

producer sends a message with key "html.xml.excel" .

we have three queue which are bind to the topic exchange

  1. "*.xml.*" --> it means that any message with key having "xml" in the middle and only one word before that and one word after that will be routed to this queue.

  2. "*.html.#" --> it means that any message with key having "html" in the middle and only one word before that and any number word after that will be routed to this queue.

  3. "#.excel" --> it means that any message with key having "excel" in the end and any number of word before that will be routed to this queue.

    Create an topic exchange:

    Login to RabbitMQ Management web page and go to "Exchanges" tab and click on "Add a new exchange" and fill details as below.

    Once topic exchange is created, bind the queues as below by clicking on your exchange.

    Once done it will look like below:

now lets publish a message with key "html.xml.excel" and lets see how it works.

Now that we have published the messages, lets check the queue.

We can see there is message in excel and xml queue but no message in html queue.

The reason is html is bound with key "*.html.#" that means there must be one word before html and the message is published with key "html.xml.excel" and here there is no word before html, hence the message is not routed to this queue.

Header Exchange

In Headers Exchange we don't use routing key. it matches key-value pairs as headers and routes the messages to appropriate queue.

When the header has "x-match" : "any", if any one of the header matches then it will route to the Queue.

When the header has "x-match" : "all", then all the key-value pair should match to route it to the Queue.

Create an Headers Exchange:

Login to RabbitMQ Management web page and go to "Exchanges" tab and click on "Add a new exchange" and fill details as below.

Bind queues using arguments.

Now after running below code we got one message in xml as we have a pair "key2":"xml_msg". But there are no message in html queue because it has "x-match":"all" and all key value pair should match but we didn't send "key2":"true".

Now we have covered all the exchange in this series. Hoping all the concept of RabbitMQ is clear to all of you.

Series: https://codeinjava.hashnode.dev/series/rabbitmq

Did you find this article valuable?

Support Java Blogs By Hemant by becoming a sponsor. Any amount is appreciated!