Understanding Queue, Publisher, Consumer in RabbitMQ with practical

Photo by Europeana on Unsplash

Understanding Queue, Publisher, Consumer in RabbitMQ with practical

How to Create a Queue?

  1. Login to RabbitMQ

    in my case URL: http://127.0.0.1:15672/ and credential: guest/guest

  2. go to Queues tab

  1. Then click on "Add a new queue" and provide a queue name click on "Add Queue". In my case I gave name "queue-name1" so my que got created.

  2. Now you can see all the details of the queue by clicking on the Queue name under "Queues and Streams" tab. Right now there are no consumers thats why consumer count is coming as zero.

How to route a message to a Queue ?

  1. Create a quickstart Maven project.

  2. add below dependency in pom.xml file

        <dependency>
            <groupId>com.rabbitmq</groupId>
            <artifactId>amqp-client</artifactId>
            <version>5.20.0</version>
        </dependency>
  1. Create a java class which will publish the message. in my case java class name is "Publisher".

  2. Now run the program and if you see something like below in the console means it ran successfully.

  3. Now you can check the message in RabbitMQ web UI.

How can a consumer consume these published message ?

  1. create a consumer class. In my case class name is "Consumer".

  2. add below code and provide queueName.

  3. In above consumer code you can see we are not closing the channel and connection. The reason is consumer is like a listener and when ever there is a message is in ready state in Queue, it should consume it so it should be running in background all the time.

  4. now lets run the code and in console you can see that the message is received and the application is not terminated and still running.

  5. now in RabbitMQ UI you can see there are zero message in Ready state as the message is consumed. Also the consumer count is 1.

  6. Now lets run the publisher code again and see if it consumes the message or not.

  7. Now the 2nd message should have consumed, lets check the Consumer console.

How the messages will be consumed when there are multiple consumers ?

When there are multiple consumers the messages will be consumed in round robbin fashion or in easy terms we can say it will be consumed evenly.

Lets create multiple consumers for a single Queue.

create multiple copy of same jar. In my case I have created two copies.

now lets run both the jars.

lets check in RabbitMQ UI if the consumers are running or not, we should have two consumers.

Perfect, Now that all the consumers are ready lets publish multiple messages.

Now Lets check the consumers console

You can see that how evenly both the consumers consumed the messages.

This is it for this blog, we will continue to learn about RabbitMQ in the next blog.

Click Here : RabbitMQ Series

Did you find this article valuable?

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