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

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

sl786982

Thanks for your post. I’ve been thinking about writing a very comparable post over the last couple of weeks, I’ll probably keep it short and sweet and link to this instead if thats cool. http://bit.do/b66RR

sl786982

sl786982

absolutely no knowledge of the product and that may have ulterior motives to try and trick you into visiting their sites. fishing trips Dubai

sl786982

sl786982

Sometimes you never know the true value of a moment until it becomes a memory, that you wish you could experience again dhow cruise Dubai

sl786982

sl786982

Which could perform short-term, yet it’s not just a feasible long-term remedy regarding fellas who would like to become your a single specific lady they will can’t quit contemplating. fishing trips Dubai

sl786982

sl786982

It's a great pleasure reading your post.It's full of information I am looking for and I love to post a comment that "The content of your post is awesome" Great work. dhow cruise Dubai

sl786982

sl786982

His is so good that I had to comment. I’m in most cases just a lurker, taking in know-how and nodding my head in quiet approval in the beneficial stuff Συνθετικός Χλοοτάπητας

sl786982

Tomcat provides two designs

Tomcat provides two designs of settings for JNDI sources, regional JNDI perspective and international JNDI perspective. Establishing a regional JNDI source indicates that the source is only available to a particular download clash royale for pc, web program implemented to Tomcat. Whereas configuring an origin in the international JNDI perspective indicates that the source is available to any web program implemented to Tomcat. The settings for each kind of JNDI design is different, so I will evaluation one design in this post and second design in the next content.

sl786982

You have a real ability for writing unique content. I like how you think and the way you represent your views in this article. I agree with your way of thinking. Thank you for sharing. mikes brain waves results

sl786982

sl786982

Thank you for the information and clarification acerca the identical houses. While I was reading the post I thought They Might Be haunted, but nothing of That sort ITS, thanks to your explanation. status of ration card

sl786982

sl786982

Your method in authoring ones own blogging is certainly important. Used to do not even comprehend you can nothing on at most of the most beneficial varieties as a result readily. This was an amazing guideline. how to teach 2 year olds to read

sl786982

sl786982

I’ve been surfing online more than three hours today, yet I never found any interesting article like yours. It’s pretty worth enough for me. In my opinion, if all webmasters and bloggers made good content as you did, the web will be a lot more useful than ever before. pregnancy miracle review

sl786982

sl786982

It is a great website.. The Design looks very good.. Keep working like that!. Post UTME

sl786982

sl786982

I am very enjoyed for this blog. Its an informative topic. It help me very much to solve some problems. Its opportunity are so fantastic and working style so speedy. Best Paid VPN

sl786982

sl786982

At this point you'll find out what is important, it all gives a url to the appealing page: - See more at: http://www.sancb.org.za/article/challenges-vi-learners#comment-25058 visit site

sl786982

sl786982

Excellent Article, i like this post and your feedback Because Its very need full post for me. Thanks for share this post click here

sl786982

sl786982

Excellent Article, i like this post and your feedback Because Its very need full post for me. Thanks for share this post! nie mehr akne buch

sl786982

sl786982

Excellent read, Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work. Affiliate Marketing

sl786982

sl786982

That is the excellent mindset, nonetheless is just not help to make every sence whatsoever preaching about that mather. Wardrobe Hardware from China

sl786982

This seemed like a really

This seemed like a really thorough example but the example WAR computer file is imperfect Click This Link. This indicates I need to use Expert to be able to acquire the reliant files? Further explaination would benefit you.

GAME HACK

pou dinheiro infinito During this website, you will see this shape, i highly recommend you learn this review. clash of clans hack download

sl786982

The best smart pet feeder available. Put up to 8 pets on individual diets, keepout the dog or any other undesired pets. toa payoh lor 4 condo

sl786982

sl786982

In our Mitigation services we strive to provide the Court with your history For our other court appointed services, our goal is to help provide the most up to date and relevant irventions. Parenting

sl786982

Post new comment

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