Tuesday, August 26, 2014

ActiveMQ Introduction

ActiveMQ is a messaging bus and helps in building Event based systems.It supports JMS which is a JavaEE based feature. In this tutorial, we will look into how to install and start a ActiveMQ server and a small program to create topic and consume topic over the message bus. We will also look into the ActiveMQ web front end where we can see what is happening in the message bus. This tutorial is based on windows but pretty much similar steps can be followed for Linux.

Installation of ActiveMQ
  • Download the latest version from http://activemq.apache.org/download-archives.html . This post is done with version 5.9.1
  • Download the zip file and extract it to some location.
  • In the extracted folder you would see a bin directory. Inside that will be batch file activemq
  • Run the activemq batch script
  • A cmd window would appear and if everything is fine you should be able to access the ActiveMQ management console at http://localhost:8161/ 
ActiveMQ is a messaging bus so it works on the notion of consumer and producer. A producer produces the message and consumer consumes it. Producers can produce message both on Queues and Topics. Let's write a TopicProducer and TopicConsumer to see how we can interact with ActiveMQ.

Maven dependencies

To connect to activeMQ server you will need client libraries. The corresponding dependency for that is as follows. In your case, you can look into maven repository and take the latest one.

<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-core</artifactId>
<version>5.7.0</version>
</dependency>

Writing a Producer

A producer is responsible for producing the message. A representative producer looks as follows


public class TopicProducer implements Runnable {

//Connection Factory which will help in connecting to ActiveMQ serer
ActiveMQConnectionFactory connectionFactory = null;

public TopicProducer(ActiveMQConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}

@Override
public void run() {
try {
// First create a connection
Connection connection = 
connectionFactory.createConnection();
connection.start();

// Now create a Session
Session session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);

// Let's create a topic. If the topic exist, 
//it will return that
Destination destination = session.createTopic("CLIMATE");

// Create a MessageProducer from 
//the Session to the Topic or Queue
MessageProducer producer = 
session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.PERSISTENT);

// Create a messages for the current climate
String text = "Today is Hot";
TextMessage message = session.createTextMessage(text);

// Send the message to topic
producer.send(message);

// Do the cleanup
session.close();
connection.close();
} catch (JMSException jmse) {
         System.out.println("Exception: " + jmse.getMessage());
}
}

}

Writing a Consumer

public class TopicConsumer implements Runnable {

ActiveMQConnectionFactory connectionFactory = null;

public TopicConsumer(ActiveMQConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}

@Override
public void run() {
try {
// First create a connection
Connection connection = 
connectionFactory.createConnection();
connection.start();

// Now create a Session
Session session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);

// Let's create a topic. If the topic exist, 
//it will return that
Destination topicDestination = 
session.createTopic("CLIMATE");

// Create a MessageProducer from the Session 
//to the Topic or Queue
MessageConsumer messageConsumer =
session.createConsumer(topicDestination);
//Get the message
Message message = messageConsumer.receive();

TextMessage textMessage = (TextMessage)message;

System.out.println(textMessage.getText());

// Do the cleanup
session.close();
connection.close();
} catch (JMSException jmse) {
System.out.println("Exception: " + jmse.getMessage());
}
}
}

Writing the main program

//Create the connection factory
ActiveMQConnectionFactory connectionFactory = 
new ActiveMQConnectionFactory("tcp://localhost:61616");

//Create the consumer. It will wait to listen to the Topic
Thread topicConsumerThread = 
new Thread(new TopicConsumer(connectionFactory));
topicConsumerThread.start();

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

//Create a message. As soon as the message is published on the Topic,
//it will be consumed by the consumer
Thread topicProducerThread = 
new Thread(new TopicProducer(connectionFactory));
topicProducerThread.start();

Run the main program and you will see the consumer consuming the message and printing it on console.

Code at GitHub

22 comments:

  1. Hi I downloaded the code from Github. How are you running the application from eclipse? Is it a standalone app or it is a Web app? I could not run the appplication from eclipse after I imported the zip file from Eclispe

    ReplyDelete
  2. You will have to run activeMQ as a separate program and connect it with the Producer/Consumer code which is in github. It's a standalone program. Refer to the code inside activeMQ folder.

    ReplyDelete
  3. Thank you very much Lalit. This helped me a lot

    ReplyDelete
  4. How to start the active-mq service in Ubuntu/MAC ?

    ReplyDelete
    Replies
    1. Can you check if there is a shell script in the same location? With that you can start it in *nix environment

      Delete
  5. Thanks Lalit, this gives good start for JMS

    ReplyDelete
  6. Hello this is nice. i have a query how to integrate activemq in java. any solution.

    ReplyDelete
  7. Hi sir, Can you please explain the aspects, which are affect the performance of ActiveMQ queues.

    ReplyDelete
    Replies
    1. What is the thoroughput that you want to do with Queues. is one important thing you might want to evaluate in terms of your use case.

      Delete
    2. Hi sir,
      thank you for your quick reply, Presently We are using ActiveMQ as queuing server , which collect queues from Tomcat web application ( Java servlets ) and those are collecting by core java application . I want to know the parameters which are effecting the ActiveMQ performance, as well as I want to tune my server performance. so Please give suggestions.we are not using topics.

      Delete
    3. You can look at this http://activemq.apache.org/performance-tuning.html
      Apart from that the server configuration that you are using also will determine the performance.

      Delete
    4. Ok Thank you sir.

      Delete
  8. Hi Sir, we want to active MQ to listen message from weblogic jms queue and receive them in websphere. please let us know how to configure that using active mq.

    ReplyDelete
    Replies
    1. Check this http://activemq.apache.org/weblogic-integration.html This might help. For websphere see this https://www.ibm.com/developerworks/websphere/library/techarticles/1211_eswarachary/1211_eswarachary.html

      These might help

      Delete
  9. Hi Lalit,

    Newbee to MQ-ing, and just playing around with the possibilities. I installed and created some queues and messages in the queues. Did that via a browser (so on the "console") and tried issueing the commandline "activemq producer --message "My message" --messageCount 1"

    So far so good. I can backtrack messages on the console. Then I tried consuming a message using "activemq consumer --transacted true"

    I get the message allright (the last I put in), but I expected that if a message is consumed, it would be deleted. It isn't. So I tried "activemq purge --msgsel [msgidhere]" and that didn't work either... It just says the broker is not avialable at service:jmx:rmi///jndi/rmi://localhost:61616

    I am missing something..?

    ReplyDelete
    Replies
    1. I was hoping you might comment..

      Delete
    2. @Lucky It's a while that I have worked in ActiveMQ. I did looked into your query but I don't have any insight on that now. I would suggest you to try ActiveMQ forum at http://activemq.2283324.n4.nabble.com/ActiveMQ-User-f2341805.html

      Delete
  10. Hi Lalit,
    Thanks for this informative article. I want to know if it is possible to create same program using node.js, websocket and active mq ? Awaiting for your reply.
    Regards,
    Deepti

    ReplyDelete
    Replies
    1. Deepti,

      What you are trying to do? ActiveMQ is just a message middleware. It supports multiple protocol like MQTT. See at http://activemq.apache.org/ . On the right hand side on the page is a connectivity section. That will help in doing the integration.

      Hope this helps.

      PS: Also I have used ActiveMQ last time almost three years before so not very conversant with the latest developments there.

      Delete
  11. The tutorial is clean and to the point. Thanks Lalit.

    ReplyDelete
  12. Thanks for information .. Lalit Bhatt

    ReplyDelete