TomcatExpert

Integrating ActiveMQ With Apache Tomcat Using Local JNDI

posted by bsnyder on December 16, 2010 08:03 AM

This article is excerpted from the forthcoming book ActiveMQ In Action (http://bit.ly/2je6cQ) by Bruce Snyder, Rob Davies and Dejan Bosanac (Manning Publications, ISBN: 1933988940)

In the first article in this series, I introduced ActiveMQ at a high level and briefly discussed why and when it might be used. In the next two articles, I will introduce two styles of integrating ActiveMQ with Tomcat. In this article I will discuss the first style of integrating ActiveMQ with Tomcat.

Tomcat supports the ability to configure Java objects as JNDI resources. This is ideal for ActiveMQ because a JMS connection factory is required to access the message broker. ActiveMQ is highly configurable and very flexible. As part of this flexibility, ActiveMQ can be embedded inside an existing JVM via a connection factory or started up as a stand alone server in its own JVM. Both of these styles will be touched upon in this article.

Integrating ActiveMQ With Tomcat

ActiveMQ provides a unique feature that allows a broker to be created via the ActiveMQ JMS connection factory. By creating an ActiveMQ connection factory using a URI for a broker that does not yet exist, the JMS connection will create an embedded instance of the broker. So this means that the creation of the broker is dependent upon the ability to create the ActiveMQ connection. JMS connections are created from a connection factory that is registered with the application server. For this purpose, Java application servers provide a JNDI (Java Naming and Directory Interface) implementation that can be used to expose objects to be used by applications deployed to the container. Objects such as JDBC drivers, JMS resources, transaction managers and so forth can be configured to be accessed using the JNDI API. This is the approach that will be used with the web containers.

Tomcat offers two styles of configuration for JNDI resources, local JNDI context and global JNDI context. Configuring a local JNDI resource means that the resource is only available to a particular web application deployed to Tomcat. Whereas configuring a resource in the global JNDI context means that the resource is available to any web application deployed to Tomcat. The configuration for each type of JNDI style is different, so I will review one style in this article and second style in the next article.

Using an Embedded ActiveMQ Broker

The local JNDI configuration restricts the availability of resources to the application where they are defined. With this style of configuration for Tomcat, the JNDI resources are defined in a file named META-INF/context.xml. Example 1 shows the file:

Example 1. The Tomcat context.xml file for an embedded ActiveMQ broker

	<Resource auth="Container"
          name="jms/ConnectionFactory"
          type="org.apache.activemq.ActiveMQConnectionFactory"
          description="JMS Connection Factory"
          factory="org.apache.activemq.jndi.JNDIReferenceFactory"
          brokerURL="vm://localhost?brokerConfig=xbean:activemq.xml"
          brokerName="MyActiveMQBroker"/>
 
<Resource auth="Container"
          name="jms/FooQueue"
          type="org.apache.activemq.command.ActiveMQQueue"
          description="JMS queue"
          factory="org.apache.activemq.jndi.JNDIReferenceFactory"
          physicalName="FOO.QUEUE"/>

The first element shown in Example 1, “The Tomcat context.xml file for an embedded ActiveMQ broker” is the resource named jms/ConnectionFactory defines an ActiveMQ connection factory and takes advantage of the ability to be started up in an existing JVM via the connection factory. The second element named jms/FooQueue defines a JMS queue in ActiveMQ. This configuration is packaged with the web application and is automatically picked up by Tomcat to configure the three resources. Tomcat makes them available via a standard JNDI lookup to the sample web application.

Note:

The $TOMCAT_HOME variable is being used to generically reference the Tomcat installation directory. This is not something that you must set in your environment.

To test the local JNDI resources, use the following steps:

  1. Download the local jms-webapp.war (http://bit.ly/gwKqay) file and put it in the $TOMCAT_HOME/webapps directory
     
  2. Start up Tomcat:
    			$ cd $TOMCAT_HOME
    $ ./bin/catalina.sh run 
    Using CATALINA_BASE:   /opt/apache-tomcat-6.0.26
    Using CATALINA_HOME:   /opt/apache-tomcat-6.0.26
    Using CATALINA_TMPDIR: /opt/apache-tomcat-6.0.26/temp
    Using JRE_HOME:        
    /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
    ...
    INFO  - BrokerService                  - Using Persistence Adapter: 
    org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter@3351c1
    INFO  - BrokerService                  - ActiveMQ 5.4.1 JMS Message 
    Broker (FooBroker) is starting
    INFO  - BrokerService                  - For help or more information 
    please see: http://activemq.apache.org/
    ...
    Apr 8, 2010 9:03:03 PM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 3542 ms

    You can see in the output that ActiveMQ is actually using the activemq.xml configuration file because the brokerName FooBroker is being used. Passing the run argument to the catalina.sh script will cause Tomcat to start up so that its output will appear in the terminal. The ability to see the output is helpful as noted earlier, and will also help you to verify the message receipt in a few steps.

    As noted at the beginning of the chapter, this configuration takes advantage of a unique feature in ActiveMQ. This feature allows an ActiveMQ broker to be started simply by creating a connection factory and passing it a broker URI. The connection factory attempts to connect to a broker at the URI, and if one does not exist, it will start one up. As you can see, this is a handy feature in ActiveMQ.

  3. Visit http://localhost:8080/jms-webapp and use the web page to send a message. See Figure 1 for an example of what you should see.

    Figure 1: Upon sending a JMS message using the web application, a message appears in the web application and then fades away just to let you know that the message was sent successfully."

    Message that appears in the web application indicatingJMS message was sent successfully
     

  4. To verify the message send, check the terminal to see that the consumer received the message. See the output below:
    			...
    INFO: Server startup in 3306 ms
    INFO  - SingleConnectionFactory        - Established shared JMS Connection: 
    ActiveMQConnection {id=ID:mongoose.local-55759-1270249165283-2:1,clientId=null,
    started=false}
    INFO  - JmsMessageDelegate     - Consumed message with payload: This is a 
    test message

    Notice the output above from the terminal, specifically, the final line that is a log message from the JmsMessageDelegate bean. This line indicates that the message has been consumed and you see the message payload is being output.

The local configuration of the ActiveMQ resources is a great approach because these resources are contained with the web application.

When should an embedded broker be used?

There are a number of situations where an embedded broker can be used. One scenario is to use an embedded broker as a persistent work queue whereby an application is sending and receiving jobs or workloads as JMS messages via ActiveMQ. One benefit is that ActiveMQ can be used in this manner without the overhead of the networking stack (remember the VM transport?). Another benefit is that JMS messages can be marked as persistent so that they get stored on disk by ActiveMQ. This is beneficial because you won't lose any messages when your application is shut down. The next time the application is started up, ActiveMQ will recover all the messages from the disk store and pick up where it left off.

Another use case where an embedded ActiveMQ message broker is useful is with an application that needs to continue working in a disconnected state. Consider an application that sends JMS messages that lives on a sales laptop that is frequently disconnected from the corporate network. When the sales person visits customers, the application needs to continue functioning. Such a situation won't work with a stand alone broker that lives on the corporate network, but an embedded broker will certainly suit this situation. By embedding an ActiveMQ broker in the application, messages can still be sent and received without being connected to the home office network. By using an ActiveMQ network of brokers (http://activemq.apache.org/networks-of-brokers.html), when the laptop is plugged back into the office network, the embedded broker will automatically connect to the stand alone broker and messages can flow.

But what if the broker I need to use is not embedded but instead is remote and stand alone?

Using a Stand Alone ActiveMQ Broker

In many cases, ActiveMQ is started in its own JVM instance so that it acts as a stand alone server. This is very straightforward using the startup script that is packaged with ActiveMQ. If you run ActiveMQ as a stand alone server, then you need to change the configuration shown in Example 1, “The Tomcat context.xml file for an embedded ActiveMQ broker” needs to be altered, but only slightly.

The only change that needs to be made is to the brokerURL attribute for the jms/ConnectionFactory object. See Example 2 below that demonstrates this change.

Example 2. The Tomcat context.xml file for a stand alone broker

	<Resource auth="Container"
          name="jms/ConnectionFactory"
          type="org.apache.activemq.ActiveMQConnectionFactory"
          description="JMS Connection Factory"
          factory="org.apache.activemq.jndi.JNDIReferenceFactory"
          brokerURL="tcp://192.168.0.23:61616"
          brokerName="MyActiveMQBroker"/>
 
<Resource auth="Container"
          name="jms/FooQueue"
          type="org.apache.activemq.command.ActiveMQQueue"
          description="JMS queue"
          factory="org.apache.activemq.jndi.JNDIReferenceFactory"
          physicalName="FOO.QUEUE"/>

Notice the brokerURL attribute in Example 2 is different than the brokerURL in Example 1. Instead of using the ActiveMQ VM transport (http://activemq.apache.org/vm-transport-reference.html), the ActiveMQ TCP transport (http://activemq.apache.org/tcp-transport-reference.html) was used. The VM transport causes an embedded broker to be started whereas the TCP transport simply points at a remote broker that is running in a separate JVM (and possibly on another machine). This slight change does not alter the way that the sample application works. Although this change is minor, this ability is quite powerful because it allows you the flexibility to choose between using an embedded broker or a stand alone broker.

Summary

Integrating ActiveMQ with Tomcat's local JNDI configuration is quite easy and remains contained in the web application. This style of configuration is useful if you don't want the JMS resources exposed beyond the web application where it is packaged. But if you do want to expose the JMS resources to more than one web application that is deployed in a single Tomcat instance, then you will want to read the third article.

In the next article, you will learn how to integrate ActiveMQ with Tomcat using the global JNDI configuration.

Bruce Snyder is a veteran of enterprise software development and a recognized leader in open source software. With nearly 15 years of experience, Bruce has worked with a wide range of technologies including Java EE, enterprise messaging and service oriented integration.

In addition to his role as a senior software engineer at SpringSource working on the vFabric Cloud Application Platform, Bruce is also an Apache Member, a co-founder of Apache Geronimo and a developer for Apache ActiveMQ, Apache Camel and Apache ServiceMix. He is a published author, currently co-authoring ActiveMQ In Action for Manning Publications.

Bruce also serves as a member of various JCP expert groups and is a recognized international speaker at industry conferences. Bruce lives in beautiful Boulder, Colorado with his family.

Comments

nice writeup, incomplete example

This looked like a really thorough example but the example WAR file is incomplete. It appears I need to use Maven to be able to obtain the dependent files? Further explaination would be beneficial.

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.