How to Implement JMS with Tomcat – Durable Subscription Example

Posted on Updated on

java-logoIn this A Durable Subscription Example, we will see how to implement JMS with Tomcat.  read What is JMS in previous article.

Tomcat doesn’t supports JMS itself but using some external library ( ActiveMQ ) we can accomplish it. here we use JMS vendor – ActiveMQ

so, before getting started, download couple of libraries and put it into Tocat/lib directory and Project classpath.

or Copy and paste below Maven Dependencies in your pom.xml file:-

 <dependency>
 <groupId>commons-logging</groupId>
 <artifactId>commons-logging</artifactId>
 <version>1.2</version>
 </dependency>
 <dependency>
 <groupId>org.apache.activemq</groupId>
 <artifactId>activemq-all</artifactId>
 <version>5.11.1</version>
 </dependency>

Next, add the resource below to conf/server.xml:

<GlobalNamingResources>
 <Resource name="ConnectionFactory" auth="Container"
 type="org.apache.activemq.ActiveMQConnectionFactory" description="JMS
 Connection Factory " factory="org.apache.activemq.jndi.JNDIReferenceFactory"
 brokerurl="tcp://localhost:61617"
 brokerName="ActiveMQBroker"
 useEmbeddedBroker="false"/>

 <Resource name="jms/topic/ITExpertsTopic" auth="Container"
 type="org.apache.activemq.command.ActiveMQTopic" factory="org.apache.activemq.jndi.JNDIReferenceFactory"
 physicalName="APP.JMS.TOPIC" />

 <Resource name="jms/queue/ITExpertsQueue" auth="Container"
 type="org.apache.activemq.command.ActiveMQQueue" factory="org.apache.activemq.jndi.JNDIReferenceFactory"
 physicalName=" APP.JMS.QUEUE" />

 </GlobalNamingResources>

Next, add this code to context.xml:

<ResourceLink global="jms/ConnectionFactory" name="jms/ConnectionFactory" type="javax.jms.ConnectionFactory"/>
<ResourceLink global="jms/topic/ITExpertsTopic" name="jms/topic/ITExpertsTopic" type="javax.jms.Topic"/>
<ResourceLink global="jms/queue/ITExpertsQueue" name="jms/queue/ITExpertsQueue" type="javax.jms.Queue"/>

Next, We need to add ActiveMQ props into tomcat class path:

set JAVA_OPTS=-Dwebconsole.type=properties -Dwebconsole.jms.url=”tcp://localhost:61617″ -Dwebconsole.jmx.url=”service:jmx:rmi:///jndi/rmi://localhost:1099/ jmxrmi”

Below are code snippet of A Durable Subscription Example :-

MessageProducerClient.Java

package com.itexperts.jms;
/**
 * 
 * @author #Ajay
 *
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

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 javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.activemq.broker.BrokerService;

public class MessageProducerClient {

 public static Properties getProp() {
 Properties props = new Properties();
 props.setProperty(Context.INITIAL_CONTEXT_FACTORY,
 "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
 props.setProperty(Context.PROVIDER_URL, "tcp://localhost:61617");
 return props;
 }

 public static void initBroker() throws Exception {
 BrokerService broker = new BrokerService();
 // configure the broker
 broker.addConnector("tcp://localhost:61617");
 broker.start();
 }

 public static void main(String args[]) {

 Connection connection = null;
 try {
 initBroker();
 InitialContext jndiContext = new InitialContext(getProp());
 ConnectionFactory connectionFactory = (ConnectionFactory) jndiContext
 .lookup("ConnectionFactory");
 connection = connectionFactory.createConnection();
 connection.setClientID("durable");
 Session session = connection.createSession(false,
 Session.AUTO_ACKNOWLEDGE);
 Destination destination = session
 .createTopic("jms/topic/ITExpertsTopic");
 MessageProducer producer = session.createProducer(destination);
 TextMessage msg = session.createTextMessage();
 msg.setText("Hello, This is JMS example !!");
 BufferedReader reader = new BufferedReader(new InputStreamReader(
 System.in));
 while (true) {
 System.out
 .println("Enter Message to Topic or Press 'Q' for Close this Session");
 String input = reader.readLine();
 if ("Q".equalsIgnoreCase(input.trim())) {
 break;
 }
 msg.setText(input);
 producer.send(msg);
 }
 } catch (JMSException e) {
 e.printStackTrace();
 } catch (IOException e) {
 e.printStackTrace();
 } catch (NamingException e) {
 e.printStackTrace();
 } catch (Exception e) {
 e.printStackTrace();
 } finally {
 try {
 if (connection != null) {
 connection.close();
 }
 } catch (JMSException e) {
 e.printStackTrace();
 }
 }

 }
}

MessageReceiverClient.Java


package com.itexperts.jms;

import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;

import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 
 * @author #Ajay
 *
 */
public class MessageReceiverClient {
 protected static final String url = "tcp://localhost:61617";

 public static void main(String args[]) {

 TopicConnection connection = null;
 try {
 ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
 url);
 connection = factory.createTopicConnection();
 connection.setClientID("durable");
 connection.start();
 MessageConsumer consumer = null;
 Session session = connection.createTopicSession(false,
 Session.AUTO_ACKNOWLEDGE);
 Topic topic = session.createTopic("jms/topic/ITExpertsTopic");
 consumer = session.createDurableSubscriber(topic, "mySub");
 // consumer.setMessageListener(new ReceiverListener());

 // System.out.println(" Waiting for Message ...");
 // while(true){
 // Thread.sleep(1000);
 // }
 while (true) {
 TextMessage message = (TextMessage) consumer.receive();
 System.out.println(message.getText());
 }
 } catch (Exception e) {
 e.printStackTrace();
 } finally {
 try {
 if (connection != null) {
 connection.close();
 }
 } catch (JMSException e) {
 e.printStackTrace();
 }
 }

 }

}

Compile and run these two Java files separately in two command prompt.

Here you will see how durable topics works when a Sender/Producer send a bunch of messages while  Subscriber/ Receiver is not yet active.

Step 1: Compile and run MessageProducerClient.Java file. Send some message to durable using command prompt.

Step 2: Compile and run MessageReceiverClient.Java file. When you run this file then all messages that are retain on Destination Durable Topic get started consuming and print on console.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s