<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>CodeDependents &#187; activemq</title>
	<atom:link href="http://codedependents.com/tag/activemq/feed/" rel="self" type="application/rss+xml" />
	<link>http://codedependents.com</link>
	<description>Two Geeks Walk Into A Blog</description>
	<lastBuildDate>Mon, 30 Apr 2012 15:53:40 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='codedependents.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>CodeDependents &#187; activemq</title>
		<link>http://codedependents.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://codedependents.com/osd.xml" title="CodeDependents" />
	<atom:link rel='hub' href='http://codedependents.com/?pushpress=hub'/>
		<item>
		<title>Synchronous Request Response with ActiveMQ and Spring</title>
		<link>http://codedependents.com/2010/03/04/synchronous-request-response-with-activemq-and-spring/</link>
		<comments>http://codedependents.com/2010/03/04/synchronous-request-response-with-activemq-and-spring/#comments</comments>
		<pubDate>Thu, 04 Mar 2010 17:32:58 +0000</pubDate>
		<dc:creator>Benjamin Darfler</dc:creator>
				<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[activemq]]></category>
		<category><![CDATA[jms]]></category>
		<category><![CDATA[lingo]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://codedependents.com/?p=326</guid>
		<description><![CDATA[A few months ago I did a deep dive into Efficient Lightweight JMS with Spring and ActiveMQ where I focused on the details for asynchronous sending and receiving of messages. In an ideal world all messaging would be asynchronous. If you need a response then you should set up an asynchronous listener and either have enough state stored in [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codedependents.com&#038;blog=7973493&#038;post=326&#038;subd=codedependents&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><img class="size-full wp-image-335 alignleft" src="http://codedependents.files.wordpress.com/2010/03/activemq-5-x-box-reflection.png?w=630" alt="activemq-5-x-box-reflection"   />A few months ago I did a deep dive into <a href="http://codedependents.com/2009/10/16/efficient-lightweight-jms-with-spring-and-activemq/">Efficient Lightweight JMS with Spring and ActiveMQ</a> where I focused on the details for asynchronous sending and receiving of messages. In an ideal world all messaging would be asynchronous. If you need a response then you should set up an asynchronous listener and either have enough state stored in the service or in the message that you can continue processing once the response has been received. However, when ideals lead to complexity, we have to make the decision of how much complexity can we tolerate for the performance we need. Sometimes it just makes more sense to use a synchronous request/response.</p>
<h2>Request Response with JMS</h2>
<p>ActiveMQ documentation actually has a pretty good overview of <a href="http://activemq.apache.org/how-should-i-implement-request-response-with-jms.html">how request-response semantics work in JMS</a>.</p>
<blockquote><p>You might think at first that to implement request-response type operations in JMS that you should create a new consumer with a selector per request; or maybe create a new temporary queue per request.</p>
<p>Creating temporary destinations, consumers, producers and connections are all synchronous request-response operations with the broker and so should be avoided for processing each request as it results in lots of chat with the JMS broker.</p>
<p>The best way to implement request-response over JMS is to create a temporary queue and consumer per client on startup, set JMSReplyTo property on each message to the temporary queue and then use a correlationID on each message to correlate request messages to response messages. This avoids the overhead of creating and closing a consumer for each request (which is expensive). It also means you can share the same producer &amp; consumer across many threads if you want (or pool them maybe).</p></blockquote>
<p>This is a pretty good start but it requires some tweaking to work best in Spring. It also should be noted that <a href="http://lingo.codehaus.org/home">Lingo</a> and <a href="http://camel.apache.org/">Camel</a> are also suggested as options when using ActiveMQ. In my <a href="http://activemq.apache.org/how-should-i-implement-request-response-with-jms.html">previous post</a> I addressed why I don&#8217;t use either of these options. In short Camel is more power than is needed for basic messaging and Lingo is built on <a href="http://jencks.codehaus.org/Home">Jencks</a>, neither of which have been updated in years.</p>
<h2>Request Response in Spring</h2>
<p>The first thing to notice is that its infeasible to create a consumer and temporary queue per client in Spring since pooling resources is required overcome the <a href="http://activemq.apache.org/jmstemplate-gotchas.html">JmsTemplate gotchas</a>. To get around this, I suggest using predefined request and response queues, removing the overhead of creating a temporary queue for each request/response. To allow for multiple consumers and producers on the same queue the JMSCorrelationId is used to correlated the request with its response message.</p>
<p>At this point I implemented the following naive solution:</p>
<p><pre class="brush: java;">
@Component
public class Requestor {

    private static final class CorrelationIdPostProcessor implements MessagePostProcessor {

        private final String correlationId;

        public CorrelationIdPostProcessor( final String correlationId ) {
            this.correlationId = correlationId;
        }

        @Override
        public Message postProcessMessage( final Message msg ) throws JMSException {
            msg.setJMSCorrelationID( correlationId );
            return msg;
        }
    }

    private final JmsTemplate jmsTemplate;

    @Autowired
    public RequestGateway( JmsTemplate jmsTemplate ) {
        this.jmsTemplate = jmsTemplate;
    }

    public String request( final String request, String queue ) throws IOException {
        final String correlationId = UUID.randomUUID().toString();
        jmsTemplate.convertAndSend( queue+&quot;.request&quot;, request, new CorrelationIdPostProcessor( correlationId ) );
        return (String) jmsTemplate.receiveSelectedAndConvert( queue+&quot;.response&quot;, &quot;JMSCorrelationID='&quot; + correlationId + &quot;'&quot; );
    }
}
</pre></p>
<p>This worked for a while until the system started occasionally timing out when making a request against a particularly fast responding service. After some debugging it became apparent that the service was responding so quickly that the receive() call was not fully initialized, causing it to miss the message. Once it finished initializing, it would wait until the timeout and fail. Unfortunately, there is very little in the way of documentation for this and <a href="http://forum.springsource.org/showpost.php?p=141588&amp;postcount=7">the best suggestion</a> I could find still seemed to leave open the possibility for the race condition by creating the consumer after sending the message. Luckily, according to the <a href="http://technology-related.com/j2ee/1.4/docs/tutorial/doc/JMS4.html#wp79145">JMS spec</a>, a consumer becomes active as soon as it is created and, assuming the connection has been started, it will start consuming messages. This allows for the reordering of the method calls leading to the slightly more verbose but also more correct solution. (<strong>NOTE</strong>: Thanks to Aaron Korver for pointing out that ProducerConsumer needs to implement SessionCallback and that true needs to be passed to the JmsTemplate.execute() for the connection to be started.)</p>
<p><pre class="brush: java;">
@Component
public class Requestor {

    private static final class ProducerConsumer implements SessionCallback&lt;Message&gt; {

        private static final int TIMEOUT = 5000;

        private final String msg;

        private final DestinationResolver destinationResolver;

        private final String queue;

        public ProducerConsumer( final String msg, String queue, final DestinationResolver destinationResolver ) {
            this.msg = msg;
            this.queue = queue;
            this.destinationResolver = destinationResolver;
        }

        public Message doInJms( final Session session ) throws JMSException {
            MessageConsumer consumer = null;
            MessageProducer producer = null;
            try {
                final String correlationId = UUID.randomUUID().toString();
                final Destination requestQueue =
                        destinationResolver.resolveDestinationName( session, queue+&quot;.request&quot;, false );
                final Destination replyQueue =
                        destinationResolver.resolveDestinationName( session, queue+&quot;.response&quot;, false );
                // Create the consumer first!
                consumer = session.createConsumer( replyQueue, &quot;JMSCorrelationID = '&quot; + correlationId + &quot;'&quot; );
                final TextMessage textMessage = session.createTextMessage( msg );
                textMessage.setJMSCorrelationID( correlationId );
                textMessage.setJMSReplyTo( replyQueue );
                // Send the request second!
                producer = session.createProducer( requestQueue );
                producer.send( requestQueue, textMessage );
                // Block on receiving the response with a timeout
                return consumer.receive( TIMEOUT );
            }
            finally {
                // Don't forget to close your resources
                JmsUtils.closeMessageConsumer( consumer );
                JmsUtils.closeMessageProducer( producer );
            }
        }
    }

    private final JmsTemplate jmsTemplate;

    @Autowired
    public Requestor( final JmsTemplate jmsTemplate ) {
        this.jmsTemplate = jmsTemplate;
     }

    public String request( final String request, String queue ) {
        // Must pass true as the second param to start the connection
        return (String) jmsTemplate.execute( new ProducerConsumer( msg, queue, jmsTemplate.getDestinationResolver() ), true );
    }
}
</pre></p>
<h2>About Pooling</h2>
<p>Once the request/response logic was correct it was time to load test. Almost instantly, memory usage exploded and the garbage collector started thrashing. Inspecting ActiveMQ with the <a href="http://activemq.apache.org/web-console.html">Web Console</a> showed that MessageConsumers were hanging around even though they were being explicitly closed using Spring&#8217;s own JmsUtils. Turns out, the <a href="http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/jms/connection/CachingConnectionFactory.html">CachingConnectionFactory</a>&#8216;s JavaDoc held the key to what was going on: &#8220;Note also that MessageConsumers obtained from a cached Session won&#8217;t get closed until the Session will eventually be removed from the pool.&#8221; However, if the MessageConsumers could be reused this wouldn&#8217;t be an issue. Unfortunately, CachingConnectionFactory caches MessageConsumers based on a hash key which contains the selector among other values. Obviously each request/response call, with its necessarily unique selector, was creating a new consumer that could never be reused. Luckily ActiveMQ provides a <a href="http://activemq.apache.org/maven/activemq-core/apidocs/org/apache/activemq/pool/PooledConnectionFactory.html">PooledConnectionFactory</a> which does not cache MessageConsumers and switching to it fixed the problem instantly. However, this means that each request/response requires a new MessageConsumer to be created. This is adds overhead but its the price that must be payed to do synchronous request/response.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codedependents.wordpress.com/326/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codedependents.wordpress.com/326/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codedependents.wordpress.com/326/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codedependents.wordpress.com/326/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codedependents.wordpress.com/326/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codedependents.wordpress.com/326/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codedependents.wordpress.com/326/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codedependents.wordpress.com/326/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codedependents.wordpress.com/326/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codedependents.wordpress.com/326/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codedependents.wordpress.com/326/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codedependents.wordpress.com/326/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codedependents.wordpress.com/326/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codedependents.wordpress.com/326/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codedependents.com&#038;blog=7973493&#038;post=326&#038;subd=codedependents&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codedependents.com/2010/03/04/synchronous-request-response-with-activemq-and-spring/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e0132e931569bbd7d6ad6ef56a6f11db?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">bdarfler</media:title>
		</media:content>

		<media:content url="http://codedependents.files.wordpress.com/2010/03/activemq-5-x-box-reflection.png" medium="image">
			<media:title type="html">activemq-5-x-box-reflection</media:title>
		</media:content>
	</item>
		<item>
		<title>Efficient Lightweight JMS with Spring and ActiveMQ</title>
		<link>http://codedependents.com/2009/10/16/efficient-lightweight-jms-with-spring-and-activemq/</link>
		<comments>http://codedependents.com/2009/10/16/efficient-lightweight-jms-with-spring-and-activemq/#comments</comments>
		<pubDate>Fri, 16 Oct 2009 16:14:49 +0000</pubDate>
		<dc:creator>Benjamin Darfler</dc:creator>
				<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[activemq]]></category>
		<category><![CDATA[jencks]]></category>
		<category><![CDATA[jms]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://codedependents.com/?p=240</guid>
		<description><![CDATA[Asynchronicity, its the number one design principal for highly scalable systems, and for Java that means JMS, which in turn means ActiveMQ. But how do I use JMS efficiently? One can quickly  become overwhelmed with talk of containers, frameworks, and a plethora of options, most of which are outdated. So lets pick it apart. Frameworks [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codedependents.com&#038;blog=7973493&#038;post=240&#038;subd=codedependents&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div id="attachment_252" class="wp-caption alignleft" style="width: 156px"><a href="http://www.flickr.com/photos/darwinbell/2798503989/"><img class="size-medium wp-image-252     " style="margin:5px;" title="Spring" src="http://codedependents.files.wordpress.com/2009/10/2798503989_278ecc0a31_b1.jpg?w=146&h=194" alt="Spring" width="146" height="194" /></a><p class="wp-caption-text">© Darwin Bell</p></div>
<p>Asynchronicity, its the <a href="http://highscalability.com/blog/2009/10/7/how-to-avoid-the-top-5-scale-out-pitfalls.html">number one</a> <a href="http://highscalability.com/blog/2009/8/11/13-scalability-best-practices.html">design</a> <a href="http://highscalability.com/blog/2009/5/8/eight-best-practices-for-building-scalable-systems.html">principal</a> for highly scalable systems, and for Java that means <a href="http://java.sun.com/products/jms/">JMS</a>, which in turn means <a href="http://activemq.apache.org/">ActiveMQ</a>. But <a href="http://activemq.apache.org/how-do-i-use-jms-efficiently.html">how do I use JMS efficiently</a>? One can quickly  become overwhelmed with talk of containers, frameworks, and a plethora of options, most of which are outdated. So lets pick it apart.</p>
<h2>Frameworks</h2>
<p>The ActiveMQ documentation makes mention of two frameworks; <a href="http://camel.apache.org/">Camel</a> and <a href="http://www.springsource.org/about">Spring</a>. The decision here comes down to simplicity vs functionality. Camel supports an immense amount of <a href="http://en.wikipedia.org/wiki/Enterprise_Integration_Patterns">Enterprise Integration Patterns</a> that can greatly simplify integrating a variety of services and orchestrating complicated message flows between components. Its certainly a best of breed if your system requires such functionality. However, if you are looking for simplicity and support for the basic best practices then Spring has the upper hand. For me, simplicity wins out any day of the week.</p>
<h2>JCA (Use It Or Loose It)</h2>
<p>Reading through ActiveMQ&#8217;s <a href="http://activemq.apache.org/spring-support.html">spring support</a> one is instantly introduced to the idea of a <a href="http://java.sun.com/j2ee/connector/">JCA</a> container and ActiveMQ&#8217;s various proxies and <a href="http://activemq.apache.org/resource-adapter.html">adaptors</a> for working inside of one. However, this is all a red herring. JCA is part of the <a href="http://java.sun.com/products/ejb/">EJB</a> specification and as with most of the EJB specification, Spring doesn&#8217;t support it. Then there is a mention of <a href="http://docs.codehaus.org/display/JCA/Home">Jencks</a>, a &#8220;lightweight JCA container for Spring&#8221;, which was spun off of ActiveMQ&#8217;s <a href="http://activemq.apache.org/jca-container.html">JCA container</a>. At first this seems like the ideal solution, but let me stop you there.  Jencks was last updated on January 3rd 2007. At that time ActiveMQ was at version 4.1.x and Spring was at version 2.0.x and things have come a long way, a very long way. Even trying to get Jencks from the maven repository fails due to dependencies on ActiveMQ 4.1.x jars that no longer exist. The simple fact is there are better and simpler ways to ensure resource caching.</p>
<h2>Sending Messages</h2>
<p>The core of Spring&#8217;s message sending architecture is the <a href="http://static.springsource.org/spring/docs/2.5.6/api/org/springframework/jms/core/JmsTemplate.html">JmsTemplate</a>. In typical Spring template fashion, the JmsTemplate abstracts away all the cruft of opening and closing sessions and producers so all the application developer needs to worry about is the actual business logic. However, ActiveMQ is quick to point out the <a href="http://activemq.apache.org/jmstemplate-gotchas.html">JmsTemplate gotchas</a>, mostly that JmsTemplate is designed to open and close the session and producer on each call. To prevent this from absolutely destroying the messaging performance the documentation recommends using ActiveMQ&#8217;s <a href="http://activemq.apache.org/maven/activemq-pool/apidocs/org/apache/activemq/pool/PooledConnectionFactory.html">PooledConnectionFactory</a> which caches the sessions and message producers. However this too is outdated. Starting with version 2.5.3, Spring started shipping its own <a href="http://static.springsource.org/spring/docs/2.5.6/api/org/springframework/jms/connection/CachingConnectionFactory.html">CachingConnectionFactory</a> which I believe to be the preferred caching method. (UPDATE: In <a href="http://codedependents.com/2010/03/04/synchronous-request-response-with-activemq-and-spring/">my more recent post</a>, I talk about when you might want to use PooledConnectionFactory.) However, there is one catch to point out. By default the CachingConnectionFactory only caches one session which the javadoc claims to be<a href="http://static.springsource.org/spring/docs/2.5.6/api/org/springframework/jms/connection/CachingConnectionFactory.html#setSessionCacheSize(int)"> sufficient for low concurrency situations</a>. By contrast, the PooledConnectionFactory <a href="http://www.docjar.com/html/api/org/apache/activemq/pool/PooledConnectionFactory.java.html">defaults to 500</a>. As with most settings of this type, some amount of experimentation is probably in order. I&#8217;ve started with 100 which seems like a good compromise.</p>
<h2>Receiving Messages</h2>
<p>As you may have noticed, the <a href="http://activemq.apache.org/jmstemplate-gotchas.html">JmsTemplate gotchas</a> strongly discourages using the recieve() call on the JmsTemplate, again, since there is no pooling of sessions and consumers.  Moreover, all calls on the JmsTemplate are synchronous which means the calling thread will block until the method returns. This is fine when using JmsTemplate to send messages since the method returns almost instantly. However, when using the recieve() call, the thread will block until a message is received, which has a huge impact on performance. Unfortunately, neither the <a href="http://activemq.apache.org/jmstemplate-gotchas.html">JmsTemplate gotchas</a> nor the <a href="http://activemq.apache.org/spring-support.html">spring support</a> documentation mentions the simple Spring solution for these problems. In fact they both recommend using <a href="http://docs.codehaus.org/display/JCA/Home">Jencks</a>, which we already debunked. The actual solution, using the <a href="http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/jms/listener/DefaultMessageListenerContainer.html">DefaultMessageListenerContainer</a>, is buried in the <a href="http://activemq.apache.org/how-do-i-use-jms-efficiently.html">how do I use JMS efficiently</a> documentation. The DefaultMessageListenerContainer allows for the asynchronous receipt of messages as well as caching sessions and message consumers. Even more interesting, the DefaultMessageListenerContainer can dynamically grow and shrink the number of listeners based on message volume. In short, this is why we can completely ignore JCA.</p>
<h2>Putting It All Together</h2>
<h4>Spring Context XML</h4>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
xmlns:amq=&quot;http://activemq.apache.org/schema/core&quot;
xmlns:jms=&quot;http://www.springframework.org/schema/jms&quot;
xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-2.5.xsd&quot;&gt;

&lt;!-- enables annotation based configuration --&gt;
&lt;context:annotation-config /&gt;
&lt;!-- scans for annotated classes in the com.company package --&gt;
&lt;context:component-scan base-package=&quot;com.company&quot;/&gt;
&lt;!-- allows for ${} replacement in the spring xml configuration from the system.properties file on the classpath --&gt;
&lt;context:property-placeholder location=&quot;classpath:system.properties&quot;/&gt;
&lt;!-- creates an activemq connection factory using the amq namespace --&gt;
&lt;amq:connectionFactory id=&quot;amqConnectionFactory&quot; brokerURL=&quot;${jms.url}&quot; userName=&quot;${jms.username}&quot; password=&quot;${jms.password}&quot; /&gt;
&lt;!-- CachingConnectionFactory Definition, sessionCacheSize property is the number of sessions to cache --&gt;
&lt;bean id=&quot;connectionFactory&quot; class=&quot;org.springframework.jms.connection.CachingConnectionFactory&quot;&gt;
    &lt;constructor-arg ref=&quot;amqConnectionFactory&quot; /&gt;
    &lt;property name=&quot;exceptionListener&quot; ref=&quot;jmsExceptionListener&quot; /&gt;
    &lt;property name=&quot;sessionCacheSize&quot; value=&quot;100&quot; /&gt;
&lt;/bean&gt;
&lt;!-- JmsTemplate Definition --&gt;
&lt;bean id=&quot;jmsTemplate&quot; class=&quot;org.springframework.jms.core.JmsTemplate&quot;&gt;
   &lt;constructor-arg ref=&quot;connectionFactory&quot;/&gt;
&lt;/bean&gt;
&lt;!-- listener container definition using the jms namespace, concurrency is the max number of concurrent listeners that can be started --&gt;
&lt;jms:listener-container concurrency=&quot;10&quot; &gt;
    &lt;jms:listener id=&quot;QueueListener&quot; destination=&quot;Queue.Name&quot; ref=&quot;queueListener&quot; /&gt;
&lt;/jms:listener-container&gt;
&lt;/beans&gt;
</pre></p>
<p>There are two things to notice here. First, I&#8217;ve added the amq and jms namespaces to the opening beans tag. Second, I&#8217;m using the Spring 2.5 <a href="http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-annotation-config">annotation based configuration</a>. By using the annotation based configuration I can simply add <a href="http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/stereotype/Component.html">@Component</a> annotation to my Java classes instead of having to specify them in the spring context xml explicitly. Additionally, I can add <a href="http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/beans/factory/annotation/Autowired.html">@Autowired</a> on my constructors to have objects such as JmsTemplate automatically wired into my objects.</p>
<h4>QueueSender</h4>
<p><pre class="brush: java;">
package com.company;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;

@Component
public class QueueSender
{
    private final JmsTemplate jmsTemplate;

    @Autowired
    public QueueSender( final JmsTemplate jmsTemplate )
    {
        this.jmsTemplate = jmsTemplate;
    }

    public void send( final String message )
    {
        jmsTemplate.convertAndSend( &quot;Queue.Name&quot;, message );
    }
}
</pre></p>
<h4>Queue Listener</h4>
<p><pre class="brush: java;">

package com.company;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.springframework.stereotype.Component;

@Component
public class QueueListener implements MessageListener
{
    public void onMessage( final Message message )
    {
        if ( message instanceof TextMessage )
        {
            final TextMessage textMessage = (TextMessage) message;
            try
            {
                System.out.println( textMessage.getText() );
            }
            catch (final JMSException e)
            {
                e.printStackTrace();
            }
        }
    }
}
</pre></p>
<h4>JmsExceptionListener</h4>
<p><pre class="brush: java;">
package com.company;

import javax.jms.ExceptionListener;
import javax.jms.JMSException;

import org.springframework.stereotype.Component;

@Component
public class JmsExceptionListener implements ExceptionListener
{
    public void onException( final JMSException e )
    {
        e.printStackTrace();
    }
}
</pre></p>
<h2>Update</h2>
<div>I have finally updated the wiki at activemq.apache.org. The following pages now recommend using MessageListenerContainers and JmsTemplate with a Pooling ConnectionFactory instead of JCA and Jencks.</div>
<div>
<ul>
<li><a href="http://activemq.apache.org/spring-support.html">http://activemq.apache.org/spring-support.html</a></li>
<li><a href="http://activemq.apache.org/how-do-i-use-jms-efficiently.html">http://activemq.apache.org/how-do-i-use-jms-efficiently.html</a></li>
<li><a href="http://activemq.apache.org/jmstemplate-gotchas.html">http://activemq.apache.org/jmstemplate-gotchas.html</a></li>
</ul>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codedependents.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codedependents.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codedependents.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codedependents.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codedependents.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codedependents.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codedependents.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codedependents.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codedependents.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codedependents.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codedependents.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codedependents.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codedependents.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codedependents.wordpress.com/240/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codedependents.com&#038;blog=7973493&#038;post=240&#038;subd=codedependents&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codedependents.com/2009/10/16/efficient-lightweight-jms-with-spring-and-activemq/feed/</wfw:commentRss>
		<slash:comments>43</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e0132e931569bbd7d6ad6ef56a6f11db?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">bdarfler</media:title>
		</media:content>

		<media:content url="http://codedependents.files.wordpress.com/2009/10/2798503989_278ecc0a31_b1.jpg?w=225" medium="image">
			<media:title type="html">Spring</media:title>
		</media:content>
	</item>
		<item>
		<title>Monitoring ActiveMQ Using JMX Over SSH</title>
		<link>http://codedependents.com/2009/05/23/monitoring-activemq-using-jmx-over-ssh/</link>
		<comments>http://codedependents.com/2009/05/23/monitoring-activemq-using-jmx-over-ssh/#comments</comments>
		<pubDate>Sat, 23 May 2009 00:20:43 +0000</pubDate>
		<dc:creator>Benjamin Darfler</dc:creator>
				<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[activemq]]></category>
		<category><![CDATA[jmx]]></category>
		<category><![CDATA[rmi]]></category>
		<category><![CDATA[ssh]]></category>

		<guid isPermaLink="false">http://blog.bdarfler.com/?p=183</guid>
		<description><![CDATA[For those who use ActiveMQ, the JMX monitoring is some pretty impressive stuff.  You can dive into connections, queues, topics, subscriptions, etc and get stats about the current state of the system.  However, this nirvana of information is practically unreachable when AMQ is in a data center.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codedependents.com&#038;blog=7973493&#038;post=183&#038;subd=codedependents&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-136" style="margin-right:5px;" title="Frustration" src="http://bdarfler.files.wordpress.com/2009/01/rsz_frustration.jpg?w=630" alt="Frustration"   /> If you want to know true confusion and frustration I suggest you attempt to monitor <a href="http://activemq.apache.org/">ActiveMQ</a> using JMX over SSH port forwarding.</p>
<p>For those who use ActiveMQ, the JMX monitoring is some pretty impressive stuff.  You can dive into connections, queues, topics, subscriptions, etc and get stats about the current state of the system.  However, this nirvana of information is practically unreachable when AMQ is in a data center.  For the first six months or so working on AMQ I was able to get around this using the <a href="http://activemq.apache.org/web-console.html">web console</a> which gives some level of detail on topics and queues but once we moved into trying to debug bigger and bigger problems the console wasn&#8217;t cutting it any longer.</p>
<p><strong>The Investigation Begins</strong></p>
<p>As with anything AMQ, I started looking into the <a href="http://activemq.apache.org/jmx.html">JMX documentaion</a>.  Step one was to enable JMX in the activemq.xml file.</p>
<p><pre class="brush: xml;">
&lt;broker useJmx=&quot;true&quot; brokerName=&quot;BROKER1&quot;&gt;
</pre></p>
<p>Fire it up, forward port 1099 (the default JMX port), give it a try, and, no go.  Come to find out, JMX uses two ports, one which is defaults to 1099 and one which is negotiated at runtime.  No worries, there is an &#8220;Advanced JMX Configuration&#8221; seciton in the documentation which lead me to this xml configuration.</p>
<p><pre class="brush: xml;">
&lt;managementContext&gt;
    &lt;managementContext connectorPort=&quot;2011&quot; jmxDomainName=&quot;test.domain&quot;/&gt;
&lt;/managementContext&gt;
</pre></p>
<p>Awesome, I can change the default 1099 port but nothing else.  The AMQ documentation was failing me, as usual.  Google, here I come.  After some searching around I was able to dig up <a href="https://issues.apache.org/activemq/browse/AMQ-892">AMQ-892</a>.  (Power user tip, search AMQ&#8217;s Jira site once the documentation has inevitably failed.)  It turns out you can configure the RMI server port and have been able to do so since version 4.1.</p>
<p><pre class="brush: xml;">
&lt;managementContext connectorPort=&quot;11099&quot; rmiServerPort=&quot;11119&quot; jmxDomainName=&quot;org.apache.activemq&quot;/&gt;
</pre></p>
<p>I particularly liked the &#8220;This necessitates a documentation update in the wiki.&#8221; comment from 2007.  Way to jump on that.  Confident that this is bound to work I forward port 11099 and 11109, give it a whirl, and, failure.  It was at this point that I started to despair.</p>
<p><strong>Deeper Down The Rabbit Hole</strong></p>
<p>Quickly running out of options I decided to try running the same configuration on a dev box in the office, and of course I could connect to it flawlessly.  To add insult to injury I tried another dev box and this one failed.  The only difference I could easily see was one was running a VM image and the other was native but this didn&#8217;t point at any easily understandable target.  I was done.  I conceded defeat.  I would soldier on without JMX.</p>
<p>Meanwhile, my co-worker had been pressuring me to start packet sniffing with wireshark.  I had resisted, mostly because I dislike getting that low level, but also because RMI is a binary protocol and I didn&#8217;t think I could learn much.  However, I was bloody and beaten at this point and gave in. I downloaded the package, fired it up and started sniffing away.  Sure enough the binary was a bunch of gibberish, but tucked away in there was one string, the hostname of the amq server I was trying to connect to.  What the hell is this?!?  That question is left to the reader but at least the issue was clear, the hostname was inside the data center and not something I could connect to from my machine.  It also jived with the test on the local dev boxes.  The box with the VM image had an internal hostname that was not in the office dns, where as the native machine had an addressable hostname.</p>
<p>I attacked the problem with renewed vigor.  I found a <a href="http://activemq.apache.org/i-cannot-connect-to-activemq-from-jconsole.html">JConsole FAQ</a> on the AMQ website that I had previously dismissed for its cryptic message.  However, this time it made sense.  I quickly added</p>
<pre>-Djava.rmi.server.hostname=127.0.0.1</pre>
<p>to the Java Service Wrapper configuration for AMQ so communication would be forced back through the SSH tunnel, rebooted AMQ, and, wait for it, VICTORY.</p>
<p><strong>The Morale of the Story</strong></p>
<p>So the short answer is add the broker configuration, the management context (the second on up there), and the rmi hostname configuration, port forward 11099 and 11109, and fire up jconsole</p>
<pre>jconsole service:jmx:rmi://127.0.0.1:11119/jndi/rmi://127.0.0.1:11099/jmxrmi</pre>
<p>As with most of these posts, so easy once you know, but so hard to get there.</p>
<a class="DiggThisButton DiggMedium" href="http://digg.com/submit?url=http%3A%2F%2Fcodedependents.com%2F2009%2F05%2F23%2Fmonitoring-activemq-using-jmx-over-ssh%2F&amp;title=Monitoring+ActiveMQ+Using+JMX+Over%26nbsp%3BSSH"></a>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/codedependents.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/codedependents.wordpress.com/183/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/codedependents.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/codedependents.wordpress.com/183/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/codedependents.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/codedependents.wordpress.com/183/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/codedependents.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/codedependents.wordpress.com/183/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/codedependents.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/codedependents.wordpress.com/183/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/codedependents.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/codedependents.wordpress.com/183/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/codedependents.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/codedependents.wordpress.com/183/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=codedependents.com&#038;blog=7973493&#038;post=183&#038;subd=codedependents&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://codedependents.com/2009/05/23/monitoring-activemq-using-jmx-over-ssh/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e0132e931569bbd7d6ad6ef56a6f11db?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">bdarfler</media:title>
		</media:content>

		<media:content url="http://bdarfler.files.wordpress.com/2009/01/rsz_frustration.jpg" medium="image">
			<media:title type="html">Frustration</media:title>
		</media:content>
	</item>
	</channel>
</rss>
