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.

sl786982

Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. Miami Bus Charter

sl786982

sl786982

Great info! I recently came across your blog and have been reading along. I thought I would leave my first comment. I don’t know what to say except that I have. Distributor Hijab Alila

sl786982

sl786982

I’ve found your blog post. Very interesting and useful. Thanks for such valuable information hcg diet

sl786982

sl786982

Proxy Sites
This is what separates the average pest control service from the best that you can find. A quality exterminator will take care of your pest problem by looking for the reason that your pest problem exists.

sl786982

sl786982

Thanks for being so nice and shared your knowledge to us. I love your blog very much and I would like to visit here again for more… mariellas master mover article

sl786982

sl786982

We believe that everyone deserves a chance at moving ahead with their lives. balloon singapore

sl786982

sl786982

This substance is made fundamentally well. Your usage of designing while deciding your centers makes your target feelings clear and easy to understand. dubai directory companies

sl786982

sl786982

Very Efficiently written information. It will be beneficial to anybody it Utilizes WHO, treats including me. Keep up the good work. For sure i will check out more posts. This site Seems to get a good amount of visitors. ezbatteryreconditioningreview.net

sl786982

sl786982

Wow, What a Excellent post. I really found this to much informatics. It is what i was searching for.I would like to suggest you that please keep sharing such type of info.Thanks Zamartar Insider Millionaire Remedy

sl786982

sl786982

I am found which I actually want. I check your blog everyday and try to learn something from your blog. best denver charity

sl786982

I encourage you to read this

I encourage you to read this text it is fun described ... equipo seguridad

asidyah

You made some good points there. I checked on the net to find out more about the issue and found most people will go along with your views on this site. this post which recommends the best skylake motherboards

sl786982

sl786982

Thank you so much for this very usefull information. It's just a very effectively written article. It will likely be useful to anyone who makes use of it, together with me. what starts with the letter a

sl786982

sl786982

I thought it was going to be some exhausting old post, however it truly made up for my time. I will present a connection on this page on my web journal. I am certain my guests will find that extremely helpful. barneys back aid results

sl786982

sl786982

I definitely really liked every part of it and i also have you saved to fav to look at new information in your site Fitness tracker deals

sl786982

sl786982

Our range of ceiling fans include under light fans, energy saving fans, decorative fans, fans with special finish, metallic fans, high speed fans etc. HERRAJES PARA MUEBLES

sl786982

sl786982

A good blog always comes-up with new and exciting information and while reading I have feel that this blog is really have all those quality that qualify a blog to be a one.I wanted to leave a little comment to support you and wish you a good continuation. Wishing you the best of luck for all your blogging efforts. Seattle Web Design Company Services Designer

sl786982

sl786982

Easily, the article is actually the best topic on this registry related issue. I fit in with your conclusions and will eagerly look forward to your next updates. Just saying thanks will not just be sufficient, for the fantasti c lucidity in your writing. I will instantly grab your rss feed to stay informed of any updates. Locksmith

sl786982

sl786982

Wonderful blog post. This is absolute magic from you! I have never seen a more wonderful post than this one. You’ve really made my day today with this. I hope you keep this up. HERRAJES PARA MUEBLES

sl786982

sl786982

This conent is simply exciting and creative. I have been deciding on a institutional move and this has helped me with one aspect. Cheers! subway surfers

sl786982

sl786982

Great tips and very easy to understand. This will definitely be very useful for me when I get a chance to start my blog. antivirus

sl786982

sl786982

Well, I have got the best information from here the site is fully stuffed with the knowledgeable information. how to lose 20 pounds fast and keep it off

sl786982

sl786982

Very informative post. I was looking for information about this topic and this post really helped me a lot. Thanks for sharing. free tour stockholm

sl786982

sl786982

This is very educational content and written well for a change. It's nice to see that some people still understand how to write a quality post! 中国 vpn

sl786982

sl786982

Very informative post! There is a lot of information here that can help any business get started with a successful social networking campaign! Inagamo Abogados Murcia

sl786982

sl786982

Very good written article. It will be supportive to anyone who utilizes it, including me. Keep doing what you are doing – can’t wait to read more posts. Cerrajeria Vigo

sl786982

sl786982

Thanks for another wonderful post. Where else could anybody get that type of info in such an ideal way of writing? cerrajero Vigo

sl786982

sl786982

Your website offered we all registered together with very helpful details so as to support. Every & any concepts in this particular unique write-up are exceptional. Take care very much suited to featuring. AromaSuperStore reviews

sl786982

sl786982

If you're looking for a high-quality human-powered translation, Translation Agency is the right place for you. We offer high accuracy of translation and instant rates on your order. m27500

sl786982

sl786982

I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post. chat room for website

sl786982

sl786982

In this case you will begin it is important, it again produces a web site a strong significant internet site: Recording Studio Design

sl786982

sl786982

Many of these websites is actually very important along with exciting to view associated with couple of days event. mxf converter mac

sl786982

sl786982

Really I enjoy your site with effective and useful information. It is included very nice post with a lot of our resources.thanks for share. i enjoy this post. maintenance plans

sl786982

sl786982

This was a truly awesome challenge and ideally I can go to the following one. It was alot of fun and I truly had a ball.. Legal Moneylender in Singapore. Moneylender in Choa Chu Kang

sl786982

sl786982

This article gives the light in which we can observe the reality. This is very nice one and gives indepth information. Thanks for this nice article. Photographie débutant

sl786982

sl786982

The information you have posted is very useful. The sites you have referred is good. Thanks for sharing... m27500

sl786982

sl786982

You possess lifted an essential offspring..Blesss for using..I would want to study better latest transactions from this blog..preserve posting.. business gift

sl786982

sl786982

Simply superb article! Its amazing to see someone put so much passion into a subject. Keep blogging the good info stuff..! Please visit my web too.. :) Licensed Moneylender

sl786982

sl786982

I'll put a connection to this website on my web journal. This posting is heavenly and what an incredible research that you have done. Click Here

sl786982

sl786982

Thanks for writing such a good article, I stumbled onto your blog and read a few post. I like your style of writing... Web Design in Belfast

sl786982

sl786982

Very nice blog and articles. I am realy very happy to visit your blog. Now I am found which I actually want. I check your blog everyday and try to learn something from your blog. Thank you and waiting for your new post. chillicothe bail bondsman

sl786982

sl786982

That’s really amazing and extraordinary blogs & can help those who get issues in searching this type of information Home Care Jobs

sl786982

sl786982

Nice to be visiting your blog again, it has been months for me. Well this article that i’ve been waited for so long. I need this article to complete my assignment in the college, and it has same topic with your article. Thanks, great share. esurance ins

sl786982

This is what distinguishes

This is what distinguishes the common insect management service from the best that you can find a replacement. A quality pest control will take care of your condition with pests by looking for the reason that your condition with pests prevails.

sl786982

Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info. Fezervin Smart Cellulite Coach

sl786982

sl786982

This is really good information. Must agree that you are one of the coolest blogger I ever saw. sharpdownloads.com

sl786982

Why do only so much written

Why do only so much written on this subject? Here you see more. Love Traction Lines Review

sl786982

I was searching for something like that for quite a long time and at last I have found it here. city gate

sl786982

sl786982

This content is written very well. Your use of formatting when making your points makes your observations very clear and easy to understand. Thank you. kbox

sl786982

Post new comment

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