RabbitMQ Tutorial with Publish/Subscribe Example


In the previous article, we have discussed RabbitMQ Java HelloWorld Example. In this tutorial, we will look at an overview of RabbitMQ and then we will develop step by step a Publish/Subscribe example.

Overview

RabbitMQ is a message-queueing software called a message broker or queue manager. It is a software where queues can be defined, applications may connect to the queues and transfer a message onto them. The basic architecture of a message queue is simple: there are client applications called producers that create messages and deliver them to the broker (the message queue). Other applications, called consumers, connect to the queue and subscribes to the messages to be processed.
RabbitMQ implements Advanced Message Queuing Protocol (AMQP). It provides client libraries for major programming languages. In this tutorial we will use RabbitMQ Java client to demonstrates usage of RabbitMQ using Java programming language.

How RabbitMQ Works and RabbitMQ Core Concepts

For simplicity, I have covered these topics in my separate article, you should learn these topics at How RabbitMQ Works and RabbitMQ Core Concepts.

Publish/Subscribe Example

In this tutorial, we will use a Publish/Subscribe pattern means we'll deliver a message to multiple consumers.  If you are new to publish/subscribe pattern then check out here.
To illustrate the pattern, we're going to build a simple logging system. It will consist of two programs -- the first will emit log messages and the second will receive and print them. 

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 EmitLog(Publisher)
  5. Create ReceiveLogs(Subscriber)
  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

Let's add RabbitMQ Java client dependency to your pom.xml file.

<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-publisher-subscriber-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 an EmitLog Program

In this example, the Publisher program, which emits log messages. Note that we are using "pub-sub-queue" as the queue name. Here goes the code for EmitLog.java program:
package net.javaguides.rabbitmq.pubsub;

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

public class EmitLog {
    private static final String EXCHANGE_NAME = "pub-sub-queue";

    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.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);

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

5. Create ReceiveLogs

This program receives logs consumes logs from the queue. Here is the complete code:
package net.javaguides.rabbitmq.pubsub;

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

/**
 * Recieve logs program 
 * @author Ramesh Fadatare
 *
 */
public class ReceiveLogs {
    private static final String EXCHANGE_NAME = "pub-sub-queue";

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

        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);
        String queueName = channel.queueDeclare().getQueue();
        channel.queueBind(queueName, EXCHANGE_NAME, "");

        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(queueName, true, deliverCallback, consumerTag - > {});
    }
}

6. Running Programs

First, run ReceiveLogs program and which waits for messages from a queue. 
Next, run the EmitLog program which sends 10 hello world log messages over the queue. Below diagram shows messages that's get printed on the console:

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.

You should check out below RabbiMQ related articles:
RabbitMQ Java HelloWorld Example
How RabbitMQ Works and RabbitMQ Core Concepts

Comments

  1. Hi thank you for your clip, I have a question that didn't found solution on gg, this is when rabbitmq server Down, then the spring boot application is going to loop retry connect to rabbitmq and all other services don't work properly. What I want is the spring boot just show a message (maybe console) that inform if rabbitmq server down, and other services (not related rabbitmq) work normally and when it re-connect rabbitmq success it show a message to inform rabbitmq server Up. Could you give a brief way to do that? Thank you!

    ReplyDelete

Post a Comment