In the previous article, we discussed RabbitMQ Java HelloWorld Example. In this tutorial, we will look at an overview of RabbitMQ, and then we will develop a step-by-step Publish/Subscribe example.
Overview
RabbitMQ is a message-queueing software called a message broker or queue manager. It is software where queues can be defined, applications may connect to the queues and transfer a message onto them.
RabbitMQ implements Advanced Message Queuing Protocol (AMQP). It provides client libraries for major programming languages.
In this tutorial, we will use the RabbitMQ Java client to demonstrate the usage of RabbitMQ using the 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.
Prerequisite
Install and Setup RabbitMQ on your machine. Check out RabbitMQ installation official documentation.
Java RabbitMQ Publish/Subscribe Example
In this tutorial, we will use a Publish/Subscribe pattern - Publisher will publish message to the RabbitMQ broker and the Subscriber will subscribe to RabbitMQ broker to recieve the message. 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.Tools and technologies used
- RabbitMQ Java client- 5.5.1
- IDE - Eclipse Noen
- Maven 3.5.3
- JavaSE - 1.8
Development Steps
- Create a Simple Maven Project
- Project Directory Structure
- Add jar Dependencies to pom.xml
- Create EmitLog(Publisher)
- Create ReceiveLogs(Subscriber)
- Run an Application
1. Create a Simple Maven Project
Use the How to Create a Simple Maven Project in Eclipse article to create a simple Maven project in Eclipse IDE.
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
The Publisher program 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
Let's create a Reciever or Consumer to consume the 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 the 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.
The below diagram shows messages that 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 is available on my GitHub Repository.
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