ActiveMQ Queue JNDI Publisher Consumer

In last tutorial you saw how to print Hello World using ActiveMQ. Today we will extend ActiveMQ Hello World to use JNDI to lookup javax.jms.ConnectionFactory rather than creating ActiveMQConnectionFactory directly. All steps of installation, start and stop process are same.

  • To use JNDI first you will have to create jndi.properties file and keep in project classpath. To show how to do this we will create simple maven project. Below is final project structure:

ActiveMQ Queue JNDI Publisher Consumer

  • pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.javahonk</groupId>
	<artifactId>ActiveMQHelloWorld</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>ActiveMQHelloWorld</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<repositories>
		<repository>
			<id>repository.jboss.org-public</id>
			<name>JBoss.org Maven repository</name>
			<url>https://repository.jboss.org/nexus/content/groups/public</url>
		</repository>
	</repositories>
	
	<dependencies>
		<dependency>
			<groupId>javax.jms</groupId>
			<artifactId>jms</artifactId>
			<version>1.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.activemq</groupId>
			<artifactId>activemq-client</artifactId>
			<version>5.11.1</version>
		</dependency>
	</dependencies>
</project>
  • jndi.properties file:
java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory
 
# use the following property to configure the default connector
java.naming.provider.url = tcp://JavaHonk:61616
 
# use the following property to specify the JNDI name the connection factory
# should appear as. 
#connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactry
 
# register some queues in JNDI using the form
# queue.[jndiName] = [physicalName]
queue.MyQueue = JavaHonk
 
 
# register some topics in JNDI using the form
# topic.[jndiName] = [physicalName]
topic.MyTopic = JavaHonktopic
  • ActiveMQTopicExampleUsingJNDI.java
package com.javahonk;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

public class ActiveMQTopicExampleUsingJNDI {
    
	public static void main(String[] args) throws Exception {
		
		(new Thread(new ActiveMQHelloWorldProducer())).start();
		(new Thread(new ActiveMQHelloWorldProducer())).start();
		(new Thread(new ActiveMQHelloWorldProducer())).start();
		(new Thread(new ActiveMQHelloWorldProducer())).start();
				
		Thread.sleep(1000);
		(new Thread(new HelloWorldConsumer())).start();
		(new Thread(new HelloWorldConsumer())).start();
		(new Thread(new HelloWorldConsumer())).start();
		 
	}

	public static class ActiveMQHelloWorldProducer implements Runnable {
		
		public void run() {
			try {
				
				// Create ConnectionFactory
				javax.naming.Context ctx = new javax.naming.InitialContext();
				javax.jms.TopicConnectionFactory activeMQConnectionFactory = (javax.jms.TopicConnectionFactory)ctx.lookup("ConnectionFactory");
				
				// Create Connection
				Connection connection = activeMQConnectionFactory.createConnection();
				connection.start();

				// Create Session
				Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
				
				// Create the destination (Topic or Queue)
				Destination destination = session.createQueue("JavaHonk");

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

				// Create messages
				String text = "Java Honk ActiveMQ Hello world! From: "+ Thread.currentThread().getName() + " : "+ this.hashCode();
				TextMessage message = session.createTextMessage(text);

				// Tell the producer to send the message
				System.out.println("Sent message: " + message.hashCode()+ " : " + Thread.currentThread().getName());
				producer.send(message);

				// Clean up
				session.close();
				connection.close();
			} catch (Exception e) {
				System.out.println("Caught Exception: " + e);
				e.printStackTrace();
			}
		}
	}

	public static class HelloWorldConsumer implements Runnable,
			ExceptionListener {
		public void run() {
			try {

				// Create ConnectionFactory
				javax.naming.Context ctx = new javax.naming.InitialContext();
				javax.jms.TopicConnectionFactory activeMQConnectionFactory = (javax.jms.TopicConnectionFactory)ctx.lookup("ConnectionFactory");

				// Create a Connection
				Connection connection = activeMQConnectionFactory.createConnection();
				connection.start();

				connection.setExceptionListener(this);

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

				// Create the destination (Topic or Queue)
				Destination destination = session.createQueue("JavaHonk");

				// Create a MessageConsumer from the Session to the Topic or
				// Queue
				MessageConsumer consumer = session.createConsumer(destination);

				// Wait for a message
				Message message = consumer.receive(1000);

				if (message instanceof TextMessage) {
					TextMessage textMessage = (TextMessage) message;
					String text = textMessage.getText();
					System.out.println("Received: " + text);
				} else {
					System.out.println("Received: " + message);
				}

				consumer.close();
				session.close();
				connection.close();
			} catch (Exception e) {
				System.out.println("Caught exception: " + e);
				e.printStackTrace();
			}
		}

		public synchronized void onException(JMSException ex) {
			System.out.println("ActiveMQ JMS Exception occured.  Shutting down client.");
		}
	}
}
  • Output:

ActiveMQ Queue JNDI Publisher Consumer

  • For more information please read ActiveMQ getting started tutorial here

Leave a Reply

Your email address will not be published. Required fields are marked *