jms

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.

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.
Subscribe
Notify of
guest

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

10 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Shiv Trivedi
Shiv Trivedi
6 years ago

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

Kishor
Kishor
5 years ago

Thanks very useful.

Tad Ariq
Tad Ariq
5 years ago

Assalamu’alaikum!

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

It works!

Ashish Gupta
Ashish Gupta
5 years ago

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

dobau
dobau
5 years ago

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

Raushan
Raushan
4 years ago

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

Dhruv Soni
Dhruv Soni
3 years ago

Error occurred during initialization of boot layer
java.lang.module.ResolutionException: Module activemq.all contains package javax.transaction.xa, module java.transaction.xa exports package javax.transaction.xa to activemq.all

I am getting the above error while connecting to activemq.
What could be a probable solution for this?

JTW
JTW
2 years ago
Reply to  Dhruv Soni

You’re using Java 11 or later most likely, and those things are now no longer part of the standard library. You’ll need to add implementations to your classpath at startup.

Yogesh Gandhi
Yogesh Gandhi
3 years ago

Wonderful article. Thanks for adding it here.
Its pretty clear, and it tells that default port is 61616 which is not the same as the port number of admin console of active MQ.

Also if will be great if you can add, what can be done if this port is not available on some machine or being used by some other process. How can we change this default port.

JTW
JTW
2 years ago
Reply to  Yogesh Gandhi

The ports used can all be configured in the ActiveMQ configuration files.
Which file and setting depends on the exact version of ActiveMQ you’re using but they should be in the etc or conf subdirectory.
Just go through the config files, look for the port number you want to change, and change it.
Do restart ActiveMQ for the changes to take effect.

Back to top button