Jms Java Activemq Example Usage

ApacheMQ

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 loosly coupled.

Maven Dependency

We will require the following maven dependency to ActiveMQ.

<dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>activemq-all</artifactId>
    <version>5.6.0</version>
</dependency>

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");
//factory.setUserName(username);
//factory.setPassword(password);

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");
messageProducer.send(textMessage);

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

if (message != null){ 
    String text = ((TextMessage) message).getText();
    System.out.println(text);
}

//...

JMS vs Sockets

Advantages of JMS

On the other hand sockets provide a direct connection.


Share Tweet Share