TomcatExpert

Integrating ActiveMQ With Apache Tomcat using Global JNDI

posted by bsnyder on December 20, 2010 07:45 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)

The first article in this series began by introducing ActiveMQ at a high level. This provided you a picture into where to use ActiveMQ with your applications. The second article dove a bit deeper to demonstrate how to integrate ActiveMQ with Tomcat using local JNDI. This is useful for situations where ActiveMQ should only be accessed by a single application. But what about a situation where more than one application deployed to a single instance of Tomcat needs to access ActiveMQ? This is where Tomcat's global JNDI enters the picture. In this article, I show how to integrate ActiveMQ with Tomcat using a global JNDI configuration.

Integrating ActiveMQ With Tomcat

As mentioned in the previous article, 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.

Using an Embedded ActiveMQ Broker

The global JNDI configuration in Tomcat is also quite easy to use, it just requires a bit of additional configuration. The advantage of global JNDI is that the resources are available to any web applications that are deployed to Tomcat. In this style of configuration, the JNDI resources are defined in configuration files that live with the Tomcat application server named conf/server.xml and the conf/context.xml. Listing Example 1, “The Tomcat server.xml file” shows the relevant portion of the server.xml file.

Example 1. The Tomcat server.xml file

<GlobalNamingResources>
...
  <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:conf/activemq.xml" 
    brokerName="MyActiveMQBroker"/> 
 
  <Resource auth="Container" 
    name="jms/FooQueue" 
    type="org.apache.activemq.command.ActiveMQQueue" 
    description="A sample queue" 
    factory="org.apache.activemq.jndi.JNDIReferenceFactory" 
    physicalName="FOO.QUEUE"/>
...
</GlobalNamingResources>

The <Resource> elements from the server.xml file shown in Example 1, “The Tomcat server.xml file” registers the JNDIReferenceFactory object with Tomcat for creating the noted object types - the ActiveMQConnectionFactory and the ActiveMQQueue. Again, ActiveMQ is unique in the fact that a full broker instance can be created via a ConnectionFactory. The brokerURL attribute is used to pass the broker URI which allows any of the supported transports (e.g., TCP, VM, etc.). It also supports the optional brokerConfig parameter used to point to a configuration file for the ActiveMQ instance that is being started.

The next file to be changed is the context.xml file; the relevant additions are shown in listing Example 2, “The Tomcat context.xml file”.

Example 2. The Tomcat context.xml file

<Context>
...
  <ResourceLink global="jms/ConnectionFactory" 
    name="jms/ConnectionFactory" /> 
 
  <ResourceLink global="jms/FooQueue" 
    name="jms/FooQueue" />
 
...
</Context>

The <ResourceLink> elements define a link to the resources that are defined in the global JNDI context and exposes these resources to all web applications deployed in this instance of Tomcat.

To test the global JNDI resource configurations, use the following steps:

  1. Download the dependencies.zip (http://bit.ly/hgz2fR) file and expand the JARs in it into the $TOMCAT_HOME/lib directory.

  2. Download the global activemq.xml (http://bit.ly/gTZA6t) file and place it in $TOMCAT_HOME/conf/ directory. This makes the ActiveMQ configuration file available on the classpath.

  3. Download the global jms-webapp.war (http://bit.ly/hpcfHJ) and place it in the $TOMCAT_HOME/webapps directory.

  4. Start up Tomcat using the following command:

     

    			$ 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
    Using CLASSPATH:       
    /opt/apache-tomcat-6.0.26/bin/bootstrap.jar
    ...
    INFO  - BrokerService                  - ActiveMQ 5.4.1 JMS Message 
    Broker (FooBroker) is starting
    ...
    Apr 9, 2010 8:54:59 PM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 3365 ms

    You can see that ActiveMQ is using the activemq.xml configuration file based on the output stating that the FooBroker is starting.

  5. Visit http://localhost:8080/jms-webapp and send a message.

  6. To confirm a successful message send, check the terminal for the following output:

    		...
    INFO: Server startup in 3365 ms
    INFO  - SingleConnectionFactory        - Established shared JMS Connection: 
    ActiveMQConnection {id=ID:mongoose.local-49429-1270868098091-2:1,
    clientId=null,started=false}
    INFO  - JmsMessageDelegate             - Consumed message with payload: 
    This is a test message

    In the output above shown above, notice the last line of output from the JmsMessageDelegate bean shows the message payload that was consumed by the JmsMessageDelegate bean.

For some projects, configuring ActiveMQ to use the Tomcat global JNDI context is appropriate because there may be multiple projects that need access to those resources. In some situations, it makes sense to control ActiveMQ from within the Tomcat process. The disadvantage is that Tomcat and ActiveMQ are now contending for the same resources inside of the same JVM. For some projects, this is not a problem and is, therefore, an acceptable trade-off.

But how would this work if the ActiveMQ broker is not embedded? What if the broker 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 server.xml file” 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 3 below that demonstrates this change.

Example 3. The Tomcat server.xml file for a stand alone broker

<GlobalNamingResources>
...
<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"/>
...
</GlobalNamingResources>

Notice the brokerURL attribute in Example 3 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

This concludes this series of articles on integrating ActiveMQ with Tomcat. The first article introduced you to ActiveMQ while articles two and three demonstrated the steps for each style of integration. Although the sample application used in these articles was extremely simple, there are many more possibilities for building applications that utilize JMS. For more information, check out ActiveMQ In Action (http://bit.ly/2je6cQ) by Bruce Snyder, Rob Davies and Dejan Bosanac.

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

tomcat ERROR

Hi ,

I followed ur steps Example 2 : 4 th step running tomcat .i am getting the below ..
can u help me to resolve the issue?

Apr 14, 2011 2:20:58 PM org.apache.catalina.core.StandardContext start
SEVERE: Error listenerStart
Apr 14, 2011 2:20:58 PM org.apache.catalina.core.StandardContext start
SEVERE: Context [/jms-webapp] startup failed due to previous errors

Still not working

1. The Article "Integrating ActiveMQ With Apache Tomcat using Local JNDI" lacks a link to "dependency.zip".
2. Following installing "jms-webapp.war" still leads to "java.lang.NoClassDefFoundError: org/springframework/asm/ClassVisitor".
Adding "springframework-asm"-jar leads to missing "springframework-expression".
3. When all springframework-thingys were added, the application will still not start: "org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'connectionFactory': Invocation of init method failed; nested exception is javax.naming.NamingException: Cannot create resource instance"

Have you ever tested this with a vanilla tomcat?

Which lib/jar is required and would you please provide it in dependency.zip?

Tomcat 7 with ActiveMQ Global JNDI

Thanks for showing us a great solution for sharing an embedded ActiveMQ instance, and your "In Action" book on this general topic. We have decided to go with this global jndi embedded solution, however, once we attempted to upgrade Tomcat to version 7, we ran into a classpath issue when loading the activemq.xml file:

Caused by: java.io.FileNotFoundException: class path resource [conf/activemq.xml] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:158)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328)

In the context.xml, the Loader element has the attribute useSystemClassLoaderAsParent set to false, however, this attribute no longer exists in Tomcat 7. (or 6, according to the docs, but 6 worked properly.)

Have you attempted to use Tomcat 7 with your globally-referencable embedded ActiveMQ solution? If so, how did you get the activemq.xml to load?

Thanks for your help.

Tom Harris

Found a solution to the above issue

If I use:

brokerURL="vm://localhost?brokerConfig=xbean:file:./activemq.xml"

now things work in Tomcat 7 again. It seems that the classloaders in 7 no longer allow the use of xbean:conf/activemq.xml as the brokerConfig value.

Pls help

SEVERE: Servlet.service() for servlet jms-webapp in context with path [/jms-webapp] threw exception [Request processing failed; nested exception is org.springframework.jms.UncategorizedJmsException: Uncategorized exception occured during JMS processing; nested exception is javax.jms.JMSException: Could not create Transport. Reason: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource http://conf/activemq.xml; nested exception is java.io.FileNotFoundException: class path resource http://conf/activemq.xml] cannot be opened because it does not exist with root cause
java.io.FileNotFoundException: class path resource http://conf/activemq.xml cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:158)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
at org.apache.xbean.spring.context.ResourceXmlApplicationContext.loadBeanDefinitions(ResourceXmlApplicationContext.java:111)

tomcat error

I followed the above directions & when I start up tomcat I get the following error:
SEVERE: Error deploying configuration descriptor activemq.xml

any suggestions on other configurations that have to get done?

Post new comment

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