Mini Project RabbitMQ and Java – part 2

Marcin Łącki

In the previous article, I presented RabbitMQ installation and environment preparation in the second part I will show how to send and consume messages from queues.

Sender Class

In this class we will create a connection with RabbitMQ and a channel to which the message will be sent.

Create Class Sender

package com.marcin;  

import com.rabbitmq.client.Channel;  
import com.rabbitmq.client.Connection;  
import com.rabbitmq.client.ConnectionFactory;  
import java.io.IOException;  
import java.util.concurrent.TimeoutException;  

public class Sender {  
    public static void main(String[] args) throws IOException, TimeoutException {  
        ConnectionFactory factory = new ConnectionFactory();  

 try (Connection connection = factory.newConnection()) {  

            Channel channel = connection.createChannel();  
  channel.queueDeclare("Rabbit in Jlabs", false, false, false, null);  

  String message = "Send something";  

  channel.basicPublish("", "Rabbit in Jlabs", false,null, message.getBytes());  

  System.out.println("Done");  

  }  
    }  
}

At the beginning we created factory which gives connection to RabbitMQ:

ConnectionFactory factory = new ConnectionFactory();

If you want to send or consume message you need a channel:

Channel channel = connection.createChannel();  

Next we create queue on the RabbitMQ server:

Our queue has name Rabbit in Jlabs

channel.queueDeclare("Rabbit in Jlabs", false, false, false, null); 

Time to create a message:

String message = "Creepy Message"; 

And we want to publish message to the queue:

channel.basicPublish("", "Rabbit in Jlabs", false,null, message.getBytes());

Run code and check it is finished without errors.

Find your message in queue

Go to your RabbitMQ path e.g.:

c:\Program Files\RabbitMQ Server\rabbitmq_server-3.8.2\sbin

And in cmd run:

>rabbitmqctl list_queues

As response you can see your queue name and number of messages:

Timeout: 60.0 seconds ...
Listing queues for vhost / ...
name    messages
Rabbit in Jlabs 1

You can run again Sender.java and check rabbitmqctl list_queues:

Timeout: 60.0 seconds ...
Listing queues for vhost / ...
name    messages
Rabbit in Jlabs 2

Now your queue contains two messages. How to check the message body?
Unfortunately you can’t check this with cmd, but you can go to RabbitMQ Management Plugin (installed in first part). Go to Queues tab scroll down to Get messages and click button Get Message(s). You can see your Payload:

Consume message from queue

We want read our message from the queue. In this part we will create a consumer who can do it.

package com.marcin;  

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

import java.io.IOException;  
import java.util.concurrent.TimeoutException;  
public class Consumer {  
    public static void main(String[] args) throws IOException, TimeoutException {  
        ConnectionFactory factory = new ConnectionFactory();  

  Connection connection = factory.newConnection();  

  Channel channel = connection.createChannel();  
  channel.queueDeclare("Rabbit in Jlabs", false, false, false, null);  

  channel.basicConsume("Rabbit in Jlabs",true, (consumerTag, message) -> {  
                String receivedMessage = new String(message.getBody(), "UTF-8");  
  System.out.println("Received message: " + receivedMessage);  
  }, consumerTag -> {});  
  }  
    }

Same as for Sender you need a channel:

Channel channel = connection.createChannel();  

And queue:

channel.queueDeclare("Rabbit in Jlabs", false, false, false, null); 

We need to convert the bytes array to a string and set encoding to UTF-8.

channel.basicConsume("Rabbit in Jlabs",true, (consumerTag, message) -> {  
                String receivedMessage = new String(message.getBody(), "UTF-8");  
  System.out.println("Received message: " + receivedMessage);

Consumer Tag is a tag you get from the server when you connect and identifies you as a consumer:

}, consumerTag -> {}); 

Summary

Message broker is really helps in scaling your application. You can delegate work to background processes and get easier managing communication between services or applications. Message brokers gives your applications platform to send and receive messages. Provide the ability to connect with other systems and helps to create it scalable.

https://www.rabbitmq.com/ http://maven.apache.org/download.cgi http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html https://mvnrepository.com/ https://www.erlang.org/

Poznaj mageek of j‑labs i daj się zadziwić, jak może wyglądać praca z j‑People!

Skontaktuj się z nami