Understanding Queue, Publisher, Consumer in RabbitMQ with practical
How to Create a Queue?
Login to RabbitMQ
in my case URL: http://127.0.0.1:15672/ and credential: guest/guest
go to Queues tab
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.
-
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 ?
Create a quickstart Maven project.
-
add below dependency in pom.xml file
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.20.0</version>
</dependency>
Create a java class which will publish the message. in my case java class name is "Publisher".
-
Now run the program and if you see something like below in the console means it ran successfully.
-
Now you can check the message in RabbitMQ web UI.
How can a consumer consume these published message ?
create a consumer class. In my case class name is "Consumer".
add below code and provide queueName.
-
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.
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.
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.
-
Now lets run the publisher code again and see if it consumes the message or not.
-
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