RabitMQ 2.Work Queue

Paul issack minoltan
3 min readJul 23, 2020

Here RabbitMQ 2 is used to create a messaging application also known as a message broker or queue manager. Simply says, it is software where queues are defined, to which applications connect in order to transfer a message or messages.

This message can be any kind of information. Such as text message, information about a process or task. The queue-manager software stores the messages until a receiving application connects and takes a message off the queue. The receiving application then processes the message.

Let’s follow the example to understanding the concepts.

Step 1: Create a Java Class with named NewTask.Java

Import the following

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

Then create a name for the queue and the name should be same for publisher and consumers.

Then create the connection with the server. I used local server of my machine(localhost) . Next we need to create a channel, where most of the API for getting things done resides.

Step 2: Create a Java Class with named Worker.Java

Import the same used in NewTask.java

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

After that we create a fake task inside the Worker class.

Step 3: Compile classes and run RabbitMQ

1. Compile the classes using command prompt.
use this to compile :
javac -cp amqp-client-5.7.1.jar NewTask.java Worker.java.

client jar and the dependencies should be in the class path

Step 4: Create multiple consumers

Lets see, how the work queue deals with the paralleled work. we cana create an environment variable for our class path.

At command prompt type set CP=.;amqp-client-5.7.1.jar;slf4j-api-1.7.26.jar;slf4j-simple-1.7.26.jar.

after doing this we can use the word CP and can get our works done.

1. Create two consumers, So that open two consoles which represents two consumers and type java -cp %CP% Worker in each of the consoles.

2. Consumers are ready and wait for the messages. The consumers will print the messages when they get from the publisher via RabbitMQ.

Step 5: Publish Tasks

  1. Create a new console which represents our publisher and publish a task using the command java -cp %CP% NewTask First message.
  2. Then, only the first consumer got the message.

3. Publish the next task: java -cp %CP% NewTask Second message.. Now only the second consumer received the message.

4. Finally publish several tasks one by one and see what happens next.

The End..!

--

--