Home » Enterprise Java » jms » Apache ActiveMQ “Hello World” Example

About Neha Goel

Neha Goel
Neha holds a Bachelors degree in Computer Science and Engineering. Currently she is working as a Sr. Programmer Analyst for a client in USA and has a total of 9+ years of Java/J2EE experience.Her expertise includes participation in all stages of SDLC. She has experience with multiple web based and enterprise based applications. She has a very impressive understanding in Object oriented architecture, analysis, design and software development using latest technologies like Java, J2EE , Restful Services, Spring, Hibernate, JDBC, JSP, Servlets, GWT, ATG etc.

Apache ActiveMQ “Hello World” Example

In this example, we shall show you how to make use of ActiveMQ as a message broker for exchanging messages between applications connected via a network. Before starting with our example, it is expected that we have a basic understanding of JMS concepts and Java/J2EE. JMS stands for Java Messaging Service, which is a JAVA API that helps communication between two applications connected via a network or two components within an application that communicate by exchanging messages. The messages are exchanged in an asynchronous and reliable manner.

There are several JMS providers like TIBCO EMS, JBOSSMQ etc., which act as Message Oriented Middleware (MOM) and ActiveMQ (Apache) is one of them. The software versions that we will be using to build this example is Java v8 and ActiveMQ v 5.14.5.

1. Introduction

ActiveMQ is an open source, message broker (MOM-Message Oriented Middleware) that implements the JMS API.  It is lightweight and open source. In this example, we will see how to use ActiveMQ as a JMS provider.

2. How to setup ActiveMQ

  1.  Download ActiveMQ from Download ActiveMQ
  2.  Extract the ActiveMQ downloaded zip file to any location in your computer.
  3.  Open command prompt and go to the bin directory of extracted activemq folder.
  4.  Type activemq.bat start, to start activemq.
  5.  The command prompt will state that activemq has been started by this statement- INFO | Apache ActiveMQ 5.14.5 (localhost, ID:xxxx) started (please refer screenshot). Please refer the activeMQ image below.

Fig:1 Running ActiveMQ bat

6. You can also try to open ActiveMQ console using the link “http://localhost:8161/admin/” with ‘admin’/’admin’ as username and password. It should open as below.

Fig:2 ActiveMQ Console

7. The ActiveMQ console gives us information about the queue and the topic which we can monitor when we exchange messages.

3. Using ActiveMQ in a Java project (example using eclipse)

  1. Let us now create a dynamic web project in eclipse and create our MessageSender and MessageReceiver classes to see how a message is exchanged using ActiveMQ.
  2. Copy the jar files from extracted ActiveMQ/lib folder in your system to the lib folder of dynamic web project just created in eclipse.
  3. Create two classes one for sending the message (MessageSender.java) and another for receiving the message (MessageReceiver.java). Please refer code snippets below.

This class is used to send a text message to the queue. The JMS class MessageProducer.java has a method send(), which will be used here to send the message.

MessageSender.java

package com.activemq.sender;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class MessageSender {
	
	//URL of the JMS server. DEFAULT_BROKER_URL will just mean that JMS server is on localhost
	private static String url = ActiveMQConnection.DEFAULT_BROKER_URL;
	
	// default broker URL is : tcp://localhost:61616"
	private static String subject = "JCG_QUEUE"; // Queue Name.You can create any/many queue names as per your requirement.	
	
	public static void main(String[] args) throws JMSException {		
		// Getting JMS connection from the server and starting it
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
		Connection connection = connectionFactory.createConnection();
		connection.start();
		
		//Creating a non transactional session to send/receive JMS message.
		Session session = connection.createSession(false,
				Session.AUTO_ACKNOWLEDGE);	
		
		//Destination represents here our queue 'JCG_QUEUE' on the JMS server. 
		//The queue will be created automatically on the server.
		Destination destination = session.createQueue(subject);	
		
		// MessageProducer is used for sending messages to the queue.
		MessageProducer producer = session.createProducer(destination);
		
		// We will send a small text message saying 'Hello World!!!' 
		TextMessage message = session
				.createTextMessage("Hello !!! Welcome to the world of ActiveMQ.");
		
		// Here we are sending our message!
		producer.send(message);
		
		System.out.println("JCG printing@@ '" + message.getText() + "'");
		connection.close();
	}
}

This class is used to receive the text message from the queue. The JMS class MessageConsumer.java has a method receive(), which will be used here to receive the message.

MessageReceiver.java

package com.activemq.receiver;

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.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class MessageReceiver {

	// URL of the JMS server
	private static String url = ActiveMQConnection.DEFAULT_BROKER_URL;
	// default broker URL is : tcp://localhost:61616"

	// Name of the queue we will receive messages from
	private static String subject = "JCG_QUEUE";

	public static void main(String[] args) throws JMSException {
		// Getting JMS connection from the server
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
		Connection connection = connectionFactory.createConnection();
		connection.start();

		// Creating session for seding messages
		Session session = connection.createSession(false,
				Session.AUTO_ACKNOWLEDGE);

		// Getting the queue 'JCG_QUEUE'
		Destination destination = session.createQueue(subject);

		// MessageConsumer is used for receiving (consuming) messages
		MessageConsumer consumer = session.createConsumer(destination);

		// Here we receive the message.
		Message message = consumer.receive();

		// We will be using TestMessage in our example. MessageProducer sent us a TextMessage
		// so we must cast to it to get access to its .getText() method.
		if (message instanceof TextMessage) {
			TextMessage textMessage = (TextMessage) message;
			System.out.println("Received message '" + textMessage.getText() + "'");
		}
		connection.close();
	}
}

So now we have the following things:

  1. A JMS provider is running (Running ActiveMQ as shown in image above.)
  2. We have our MessageSender and MessageReceiver classes.
  3. Next we will see how a message is exchanged using Active MQ but before that here is a brief about the classes that we have used in our code.

Connection -> It represents the connection with the JMS provider – ActiveMQ. It is not a database connection.

Destination -> It represents a destination on our message provider ActiveMQ i.e. it represents a queue where we will be sending our messages. In our case we are sending it to queue “JCG_QUEUE” which will be automatically created once the MessageSender class is executed.

MessageProducer -> It represents a producer to send a message to the queue.

MessageConsumer -> It represents a receiver to receive a message from the queue.

4. Output

We will be running our java classes written above to check how the message is exchanged.

Please follow the steps below:

  1. In the eclipse Right Click on MessageSender.java -> Run As->Java Application to see if our message is sent to the queue. The Hello message after being successfully sent to the queue gets printed in eclipse output console.

Fig:3 MessageSender.java

2. We can also check our ActiveMQ console->Queues tab, to see the number of pending messages in our queue after running the MessageSender.java

Fig:4 ActiveMQ console with pending message

The producer task is done. It will just create a queue and send a message to it. Now who is going to read that message, it will not be mentioned in the producer.

Next comes our MessageReceiver class which has a connection and a destination same as explained earlier. Here we also mention the same queue name that we have used in the MessageSender class to know that we are going to pick the message from the same queue. The consumer.receive() is used to receive the message. Once the class is run, the message is received from the queue and gets printed in eclipse output console when we will execute the class.

3. In the eclipse Right Click on MessageReceiver.java -> Run As->Java Application to see if our message is received from the queue. The hello message after being successfully received gets printed in eclipse output console.

Fig:5 MessageReceiver.java

4. We can also check our ActiveMQ console->Queues tab, to see the number of dequeued messages from our queue after running the MessageReceiver.java

Fig:6 ActiveMQ console with received message

5. Conclusion

Through this example, we have learned how to configure ActiveMQ and use it to exchange any text message in an asynchronous manner. Both the sender and receiver classes are independent and we just have to configure the queue name that we want to send message to and receive message from.

(0 rating, 4 votes)
6 Comments Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

6
Leave a Reply

avatar
6 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
6 Comment authors
RaushandobauAshish GuptaTad AriqKishor Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Shiv Trivedi
Guest
Shiv Trivedi

very helpful and very nice explanation….
thanks a lot.
could you please explain something about MQ message channel.

Kishor
Guest
Kishor

Thanks very useful.

Tad Ariq
Guest
Tad Ariq

Assalamu’alaikum!

Thank you for sharing this code and explanation. It is pretty useful.

It works!

Ashish Gupta
Guest
Ashish Gupta

Very Nice Explanation..
could you please explain more about the console..

dobau
Guest
dobau

It was a good “Hello Word” in JMS.
Thank You.

Raushan
Guest
Raushan

Hello Neha
It was exactly what I was looking for, very much needed steps