Spring Boot + ActiveMQ 5 - Producer and Consumer Example

In this section, we will learn how to do asynchronous communication using ActiveMQ broker in Spring Boot application.

We will develop two Spring Boot applications, one producer and one consumer application, then we will learn how to use ActiveMQ broker in the Spring boot application to send and receive messages between the Producer and the Consumer

In the digital world, different systems are constantly sending or receiving messages. This must be carried out in a controlled manner so that messages do not block each other, end up creating a jam and processes cannot function optimally. In order for applications to be able to communicate with each other easily, it makes sense to create an intermediary, that is, a service that is responsible for managing the distribution of messages: this is what is known as a messaging brokerActiveMQ broker, one of the best known.


1. What we will build?

We will develop two Spring Boot applications, one producer and one consumer application, then we will learn how to use ActiveMQ broker in the Spring boot application to send and receive messages between the Producer and the Consumer.

The following diagram is an overview of the components in our messaging system.

Queues & Topics

Queues provide a direct channel between a producer and a consumer. The producer creates messages, while the consumer reads one after another. After a message was read, it’s gone. If multiple consumers are registered for a queue, only one of them will get the message.

On the other hand, Topics implement a one-to-many channel between a producer and multiple consumers. Unlike a queue, every consumer will receive a message send by the producer.


2. Install and Setup Apache ActiveMQ 5

Download ActiveMQ 5 from the official website at https://activemq.apache.org/components/classic/download/


Extract ActiveMQ 5 zip in the local file system. 

Open command prompt window and use "activemq start" command from the bin folder folder.


Enter the http://localhost:8161/ URL into web browser to access admin console. 
Default credentials => username="admin" and password="admin". 


3. Creating spring boot consumer application

First, open the Spring initializr https://start.spring.io

Then, Provide the Group and Artifact name. We have provided Group name com.knf.dev.demo and Artifact consumer. Here I selected the Maven project - language Java 17 - Spring Boot 3.1.5 , and Spring for Apache ActiveMQ 5.


Then, click on the Generate button. When we click on the Generate button, it starts packing the project in a .zip(consumer) file and downloads the project. Then, Extract the Zip file. 

Then, import the project on your favourite IDE.

Final Project directory:


Complete pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.knf.dev.demo</groupId>
<artifactId>consumer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>consumer</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

application.yaml

You can then configure activemq properties according to the Documentation 

spring.activemq.broker-urlURL of the ActiveMQ broker. Auto-generated by default. By default, 8161 is http port while for tcp port is 61616. Check the logs of active mq for correct port.

spring.activemq.user: Login user of the broker. By default 'admin'

spring.activemq.password: Login password of the broker. By default 'admin'

spring.jms.pub-sub-domainSwitching the default destination type of a @JmsListener from Queue to Topic can be done by setting spring.jms.pub-sub-domain=true

Our topic name = knowledgeFactory_Topic
spring:
activemq:
broker-url: tcp://localhost:61616
password: admin
user: admin
jms:
pub-sub-domain: true

activemq:
topic:
name: knowledgeFactory_Topic

Create Consumer

Consumer is  the service that will be responsible for reading messages and processing them according to the needs of your own business logic. The @JmsListener annotation is used to define a listener endpoint for JMS messages in a Spring Boot application.
package com.knf.dev.demo.consumer.service;

import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Service;

@Service
public class Consumer {

@JmsListener(destination = "${activemq.topic.name}")
public void listenToTopic(String message)
{
System.out.println("Message arrived! Message: " + message);
}
}

ConsumerApplication.java

package com.knf.dev.demo.consumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ConsumerApplication {

public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}

}


4. Creating spring boot producer application

First, open the Spring initializr https://start.spring.io

Then, Provide the Group and Artifact name. We have provided Group name com.knf.dev.demo and Artifact producer. Here I selected the Maven project - language Java 17 - Spring Boot 3.1.5 and add Spring Web, and Spring for Apache ActiveMQ 5.


Then, click on the Generate button. When we click on the Generate button, it starts packing the project in a .zip(producer) file and downloads the project. Then, Extract the Zip file. 

Then, import the project on your favourite IDE.

Final Project directory:


Complete pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.knf.dev.demo</groupId>
<artifactId>producer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>producer</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

application.yaml

spring:
activemq:
broker-url: tcp://localhost:61616
password: admin
user: admin
jms:
pub-sub-domain: true

activemq:
topic:
name: knowledgeFactory_Topic

Create Producer

Creating a producer will write our messages on the topic. JmsTemplate is a class that is part of the Spring to produce messages into the ActiveMQ Topics.
package com.knf.dev.demo.producer.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;

@Service
public class Producer {

JmsTemplate jmsTemplate;

@Value("${activemq.topic.name}")
private String topic;

public Producer(JmsTemplate jmsTemplate) {
this.jmsTemplate = jmsTemplate;
}

public void sendMessageToTopic(String message)
{
jmsTemplate.convertAndSend(topic,message);
}
}

Create MessageController

package com.knf.dev.demo.producer.controller;

import com.knf.dev.demo.producer.service.Producer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1")
public class MessageController {

Producer producer;

public MessageController(Producer producer) {
this.producer = producer;
}

@GetMapping("/sendMessage")
public String publishMessage(@RequestParam("message") String message) {

producer.sendMessageToTopic(message);
return "Message was sent successfully";
}
}

ProducerApplication.java

package com.knf.dev.demo.producer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ProducerApplication {

public static void main(String[] args) {
SpringApplication.run(ProducerApplication.class, args);
}

}


5. Verify our system is working as expected

First start the producer application, then start the consumer application:

Run the Spring Boot application - mvn spring-boot:run


OR 


Run this Spring boot application from 

  • IntelliJ IDEA IDE by right click - Run 'Application.main()' 
  • Eclipse/STS - You can right click the project or the Application.java file and run as java application or Spring boot application.

Open a Postman or any other tool and send a message to the producer:

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Spring Boot + Mockito simple application with 100% code coverage

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete