How to implement activeMQ JMS Producer in Spring-boot application?

Let’s consider a scenario where your application is deployed in clustering environment and application handles thousands of email request to handle it. To solve this problem, You could simple trigger an API endpoints and post the message to the process which sends email. This could solve the problem however when an application received 100’s message per seconds, You have to handle concurrency. You got to have a queue to handle these messages and that’s where you need JMS & ActiveMQ. ActiveMQ is implementation of JMS like any other JMS implementation (RabbitMQ, AmazonMQ etc).

As you know, Spring boot controllers do not provide concurrency.

In this post, I would like to put details how you can implement producer job to sent JMS messages. If you wish to know how to implement JMS Listener.. Read my previous post Follow below each step to implement ActiveMQ Producer JOB in your Spring boot application.

NOTES: In below code, There are a lots of ActiveMQ policies which are configured in the code listed below. These configurations are varies based on your requirement. And, Recommendation is to read actual document to understand more on these configurations.

Sample Configurations: Session.CLIENT_ACKNOWLEDGE and DeliveryMode.PERSISTENT

Maven POM.XML Dependencies

#Add dependencies if you have producer too in same environment.

ActiveMQ Configuration:

activemq.packages.trusted=<Optional but for security you can configure package name where the listener is>
producer.queues=<Queue Name>

ActiveMQ Java Configuration File mapped with file.

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;

public class AMQConfig {

    private String trustedPackages;

    private String noOfConnections;

    private String brokerUrl;

    private String consumerUser;

    private String consumerPassword;

    private String queues;

    private int prefetchLimit=50;

Springboot Java JMS Listener Service

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.pool.PooledConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Session;

public class ProducerJob {

    AMQConfig amqConfig;

    private final Logger LOGGER = LoggerFactory.getLogger(ProducerJob.class);
  // replace with your own producer cron
    @Scheduled(cron = "${PRODUCER_JOB_CRON}")
    public void run(){
            Session producerSession = null;
            try {
                Connection producerConnection = AMQProducer.getActiveMQProducerConnection(amqConfig);
                if (producerConnection != null) {
                    producerSession = producerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
          " Producer Job Starts. sending sample message ");
                    for (int index = 0; index < 10; index++) {
                        AMQProducer.sendMessage(producerSession, amqConfig, "{'orderno': index*100, 'type':'order', 'amount':'202'}");
          " Job ran and queue size is: {} ",  count * 50);
            } catch (Exception e) {
            } finally {
                if (producerSession != null) {
                    try {
                    } catch (JMSException e) {
} This file contains the code which sends message in activeMQ.

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.pool.PooledConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jms.*;

public final class AMQProducer {
    private AMQProducer(){ }

    private static final Logger LOGGER = LoggerFactory.getLogger(AMQProducer.class);

    static PooledConnectionFactory pooledConnectionFactory = null;
    static Connection producerConnection = null;

    private static PooledConnectionFactory getPooledConnectionFactory(final String brokenUrl, String userName, String password, String noOfConnections){
        final ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokenUrl);
        // Pass the username and password.
        // Create a pooled connection factory.
        final PooledConnectionFactory pooledConnectionFactory = new PooledConnectionFactory();
        pooledConnectionFactory.setConnectionFactory(connectionFactory);      pooledConnectionFactory.setMaxConnections(Integer.parseInt(noOfConnections));
        return pooledConnectionFactory;
    public static Connection  getActiveMQProducerConnection(AMQConfig amqConfig) {
        if (pooledConnectionFactory == null) {
  " pooledConnectionFactory is null ");
            pooledConnectionFactory = getPooledConnectionFactory(amqConfig.getBrokerUrl(), amqConfig.getProducerUser(),
                    amqConfig.getProducerPassword(), amqConfig.getNoOfPooledConnections());
        if (producerConnection == null){
            try {
      " producerConnection is null ");
                producerConnection = pooledConnectionFactory.createConnection();
            } catch (JMSException e) {
        return producerConnection;

    public static void sendMessage(Session producerSession, AMQConfig amqConfig, final String message) throws Exception{
        if (producerSession != null) {
            final Destination producerDestination = producerSession.createTopic(amqConfig.getTopics());
            final MessageProducer producer = producerSession.createProducer(producerDestination);
            try {
                TextMessage producerMessage = producerSession.createTextMessage(message);
      " ******************* message sent  ******************* ");
            } catch (Exception e) {

Note: This is a working solution however there is a chance that code could throw error due to typing mistake. Reach out to me, will do my best to help you out.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.