Jms Java Activemq Example Usage


ActiveMQ is a popular implementation of Java Messaging Service (JMS).

Why JMS?

JMS works on pub-sub model. Now the publisher and subscriber need a broker in between to communicate. JMS is that broker. The advantage of this scheme is that you can have multiple subscribers listening to the topic (event) and its configurable and loosely coupled.

Maven Dependency

We will require the following maven dependency to ActiveMQ.


JMS Producer and Consumer

JMS producer will connect to a running broker and write its messages to a particular DESTINATION. e.g. Hello.q JMS Consumer will connect to the same broker and read messages from the same DESTINATION.

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;


String DESTINATION_NAME = "Hello.q";
int TIMEOUT = 1;
ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");

Connection connection = factory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

// create the Destination from which messages will be received
Destination destination = session.createQueue(DESTINATION_NAME);
MessageProducer messageProducer = session.createProducer(destination);
TextMessage textMessage = session.createTextMessage("Hello World");

// start the connection in order to receive messages
MessageConsumer messageConsumer = session.createConsumer(destination);
Message message = messageConsumer.receive(TIMEOUT);

if (message != null){
    String text = ((TextMessage) message).getText();


JMS vs Sockets

Advantages of JMS

On the other hand sockets provide a direct connection.

Share Tweet Share