RabbitMQ Java HelloWorld Example

In this article, we will look into what is RabbitMQ, how it works and then we will demonstrate how to use RabbitMQ with HelloWorld example.
RabbitMQ is an open source message broker software. It accepts messages from producers and delivers them to consumers. It acts like a middleman which can be used to reduce loads and delivery times taken by web application servers.
  You should check out - How RabbitMQ Works and RabbitMQ Core Concepts 
You should check out - RabbitMQ Tutorial with Publish/Subscribe Example

How RabbitMQ works?

Let’s briefly have a look at how RabbitMQ works.
Let's first familiar with a few important concepts of RabbitMQ:
  • Producer: Application that sends the messages.
  • Consumer: Application that receives the messages.
  • Queue: Buffer that stores messages.
  • Message: Information that is sent from the producer to a consumer through RabbitMQ.
  • Connection: A connection is a TCP connection between your application and the RabbitMQ broker.
  • Channel: A channel is a virtual connection inside a connection. When you are publishing or consuming messages from a queue - it's all done over a channel.
  • Exchange: Receives messages from producers and pushes them to queues depending on rules defined by the exchange type. To receive messages, a queue needs to be bound to at least one exchange.
  • Binding: A binding is a link between a queue and an exchange.
  • Routing key: The routing key is a key that the exchange looks at to decide how to route the message to queues. The routing key is like an address for the message.
Producers send/publish the messages to the broker -> Consumers receive the messages from the broker. RabbitMQ acts a communication middleware between both producers and consumers even if they run on different machines.
The exchanges agents that are responsible for routing the messages to different queues. So that the message can be received from the producer to the exchange and then again forwarded to the queue. This is known as the ‘Publishing’ method.
The message will be picked up and consumed from the queue; this is called ‘Consuming’.

Send Message to Multiple Queues

By having a more complex application we would have multiple queues. So the messages will send it in the multiple queues.

Sending messages to multiple queues exchange is connected to the queues by the binding and the routing key. A Binding is a “link” that you set up to connect a queue to an exchange. The Routing key is a message attribute. The exchange might look at this key when deciding how to route the message to queues (depending on exchange type).
Learn more in detail about RabbitMQ at How RabbitMQ Works and RabbitMQ Core Concepts

RabbitMQ Java HelloWorld Example

In this simple HelloWorld example, We will create a Sender program which sends messages to a queue and we will create a Reciever program which picks the messages from a queue and consumes it.
Let's first set up the RabbitMQ and make sure that you have installed RabbitMQ based on your OS machine. Please refer official guide here.

Tools and technologies used

  • RabbitMQ Java client- 5.5.1
  • IDE - Eclipse Noen
  • Maven 3.5.3
  • JavaSE - 1.8

Development Steps

  1. Create a Simple Maven Project
  2. Project Directory Structure
  3. Add jar Dependencies to pom.xml
  4. Create a Sender
  5. Create a Reciever
  6. Run an Application

1. Create a Simple Maven Project

Use How to Create a Simple Maven Project in Eclipse article to create simple Maven project in Eclipse IDE.

2. Project Directory Structure

The project directory structure for your reference - 

3. Add jar Dependencies to pom.xml

<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>net.javaguides.rabbitmq</groupId>
    <artifactId>rabbitmq-helloworld-example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/com.rabbitmq/amqp-client -->
        <dependency>
            <groupId>com.rabbitmq</groupId>
            <artifactId>amqp-client</artifactId>
            <version>5.5.1</version>
        </dependency>
    </dependencies>
</project>

4. Create a Sender

Here is a complete Sender program:
package com.rabbitmq.helloworld;

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

public class Sender {
    private final static String QUEUE_NAME = "hello";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel()) {
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);

            for (int i = 0; i < 10; i++) {
                String message = "Hello World! " + i;
                channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
                System.out.println(" [x] Sent '" + message + "'");
            }
        }
    }
}

5. Create a Receiver

Let's create a Receiver program which receives messages. Here is the complete code:
package com.rabbitmq.helloworld;

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

public class Reciever {
    private final static String QUEUE_NAME = "hello";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        DeliverCallback deliverCallback = (consumerTag, delivery) - > {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received '" + message + "'");
        };
        channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag - > {});
    }
}

6. Running Programs

First, run Reciever program which waits for messages from a queue. 
Next, run the Sender program which sends 10 hello world log messages over the queue.
Now, you can see the logs on the console of ReceiveLogs class which receives messages from a queue and print them to the console. Here is the diagram:

The source code of this article available on my GitHub Repository.

Reference

Comments