Direct Exchange in RabbitMQ

As we all know exchange basically routes the message to appropriate queue. it is helpful when we have multiple Queues for multiple consumer.

In Previous example we used to send messages directly to the queue, but here we will learn how to send message to the exchange.

There are many type of exchange, One of them is "Direct Exchange".

In Direct Exchange the messaged are sent to the direct exchange with a routing-key and the routing key is mapped to a queue. And based on that mapping the message is sent to appropriate Queue.

Lets take an example of sending emails with attachments, so there are various consumers and some of them sends attachment/data as excel sheet, some send as xml and some as html.

All the consumers are tagged to respective queue as per the above diagram.

To achieve this we will create an exchange, in that exchange we will bind our queues with a routing key and while publishing the message we will send the routing key.

Lets Implement above scenario.

  1. lets create a direct exchange.

    Login to RabbitMQ webpage, go to "Exchanges" tab, then click on "add new exchange", then provide any exchange name and click "add exchange" button to save it.

    In my case I gave name "direct-exchange".

    1. Now lets create 3 queues

      I have created 3 queues "excel", "xml" and "html"

    2. Lets bind these queues with the Direct Exchange

      go to "Exchanges" tab, click on your exchange, then click on "Bindings", then provide your queue name and provide any routing key and click "Bind".

      Once done you can see all the binding details like below.

    3. Now lets publish the messages with exchange name and routing key.

      After running the above program we can see all the queue with the respective routing queue has a message in ready state.

    4. Now lets create consumers for the queues.

      Consumers doesn't deal with exchange so we don't have to mention exchange here.

      I ran the "xml" queue consumer and the xml message got consumed.

      I ran the "excel" queue consumer and the excel message got consumed.

      I ran the "html" queue consumer and the html message got consumed.

      Now all the queue has zero messages.

This is all about Direct Exchange. In next blog we will learn more about RabbitMQ

Did you find this article valuable?

Support Hemant Besra by becoming a sponsor. Any amount is appreciated!