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

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.

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

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

sl786982

Really great post, Thank you for sharing This knowledge.Excellently written article, if only all bloggers offered the same level of content as you, the internet would be a much better place. Please keep it up! dog trainer

sl786982

sl786982

I’m excited to uncover this page. I need to to thank you for ones time for this particularly fantastic read!!make clubflyers

sl786982

sl786982

This article so powerful. I wanna say Thank you. Once more this blog is so greatful for me. That make me better to work much. Love this blog the best… stretch wrapping machine

sl786982

sl786982

Thank you for this massive informative post. I’m going to bookmark this post for later use! Thanks for the share! Have an excellent day! doggy dan login

sl786982

You have shared an

You have shared an informative post and I think this is the best way to integrate ActiveMQ with Apache Tomcat using local JNDI. Following this method it will be very easy to do this procedure. I tried this method. sell rewards points

Deskgram

Checking any blog may make others just want to come up with a greater number of. I did a fabulous which i was first lovely content by means of. The software most likely conducted for the tier still it’s exceptional. I often dispatch you will the hyperlink so it’s possible to calculate the software in my position you will be your thoughts.
upload images to instagram

david

Thanks for your time in the insightful blogging. Used to do not even know there has been plenty of responsible authoring expertise web based. In cases where you’re revealing them all then simply it means now we have not a thing to help you be worried about.
Pro DJ

Jual Laptop Notebook PC HP Lenovo Printer Tinta Toner Harga Revi

On this page you can read Jual tinta Printer my interests, write something special.

Confirming any blog site may

Confirming any blog site may make others just want to come up with more. I did a amazing which i was first wonderful content by way of
Check This Out. The applying most likely conducted for the stage still it’s amazing. I often distribution you will the text so it’s possible to find the program in my position you will be your thoughts.

I would like to thank you for

I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own Blog Engine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it. Clipping Path India

For example, a software runs

For example, a software runs on the link share of fifty connections, and if film cameras, your repository enables 50 connections, theoretically everything must work.

Took me time to read all the

Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained! the respect principle reviews

amir

I've got not long ago started off some sort of blog site, the internet people produce here possesses served everyone enormously. Appreciate it intended for all of your current time period & do the job. Cappadocia hotels

Zulander Hack

For many people this is important, so check out my profile:
Zulander Hack

Push Money App

The most interesting text on this interesting topic that can be found on the net ...
Push Money App

This appeared as if really a

This appeared as if really a comprehensive example-but the instance CONFLICT file is imperfect learn more. It seems I have to use Expert in order to acquire the dependent documents? Further explaination could be helpful.

bookmarked!!, I love your web

bookmarked!!, I love your web site!
Mortgage Broker Calgary

Quickly, the content is

Quickly, the content is clearly the very best subject with this registry problem that is relevant. I certainly will desperately anticipate the next improvements and participate in your findings. Simply expressing cheers will insufficient check this out, for the c lucidity inside your writing. I'll immediately get your feed to remain informed of any improvements.

This can be a excellent ideas

This can be a excellent ideas particularly in order to individuals a new comer to blogosphere, short as well as precise information… Many thanks with regard to discussing that one. Essential study post.
Cheap ClubFlyer

This can be a amazing ideas

This can be a amazing ideas particularly to be able to those not used to seluruh seluruh seluruh dunia ngeblog this contact form, brief as well as precise information… Many thanks associated with referring to to that one. Essential analysis post.

This is the approach that

This is the approach that will be used with the web containers.cccam server

Seo

Very interesting blog. A lot of blogs I see these days don't really provide anything that I'm interested in, but I'm most definitely interested in this one. Just thought that I would post and let you know...bus from miami to key west

SeoBlogger

I blog often and I truly

I blog often and I truly thank you for your content. The article has really peaked my interest. I'm going to bookmark your site and keep checking for new details about once a week. I subscribed to your RSS feed as well.
Edmonton Mortgage Broker
Life Insurance Vancouver
Life Insurance Calgary

I have got recently started

I have got recently started out some kind of blog, the web people create below offers offered everybody significantly kids bedroom sets. Relish it meant for all your present period of time & get the job done.

I blog frequently and that I

I blog frequently and that I certainly thanks for the information. My curiosity has been truly peaked by the content Source. Maintain checking for brand new factual statements about once per week and I am likely to save your website. I bought for your feed aswell.

I weblog regularly and that I

I weblog regularly and that I certainly thanks for the information. My fascination has been truly actually peaked by the information Resource why not try here . Sustain looking at product new actual claims about once per 7 days and I am likely to preserve your valuable website. I got myself for your nourish aswell.

Post new comment

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