<?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/"
	>

<channel>
	<title>JMS &#8211; Pauls Blog</title>
	<atom:link href="https://sterl.org/tag/jms/feed/" rel="self" type="application/rss+xml" />
	<link>https://sterl.org</link>
	<description></description>
	<lastBuildDate>Sat, 04 Apr 2020 14:30:33 +0000</lastBuildDate>
	<language>de</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>
	<item>
		<title>Reconnecting JMS listener</title>
		<link>https://sterl.org/2020/04/reconnecting-jms-listener/</link>
					<comments>https://sterl.org/2020/04/reconnecting-jms-listener/#respond</comments>
		
		<dc:creator><![CDATA[Paul Sterl]]></dc:creator>
		<pubDate>Sat, 04 Apr 2020 13:34:15 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[Spring Boot]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[JMS]]></category>
		<category><![CDATA[Reconnect]]></category>
		<guid isPermaLink="false">http://sterl.org/?p=558</guid>

					<description><![CDATA[Problem In some projects we still may need to manually to reconnect to our JMS provider. For what ever reason the framework or the container cannot do the job for us. As so we have to ensure that an once registered JMS listener re-register itself if something bad happens. Note: Check first if your container&#8230;]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Problem</h2>



<p>In some projects we still may need to manually to reconnect to our JMS provider. For what ever reason the framework or the container cannot do the job for us. As so we have to ensure that an once registered JMS listener re-register itself if something bad happens.</p>



<div class="bs-callout bs-callout-info"><strong>Note:</strong>
Check first if your container can handle this for you.
</div>



<h2 class="wp-block-heading">Solution</h2>



<p>Well some <code>JmsConnectionFactory</code> already support a re-connection but they are not always very reliable. For instance, the <a rel="noreferrer noopener" href="https://www.ibm.com/support/knowledgecenter/en/SSFKSJ_7.5.0/com.ibm.mq.ref.dev.doc/q111980_.htm" target="_blank">IBM driver supports</a> in theory a reconnect, but it is just a bit buggy.</p>



<p>Well, what is the straight forward solution? The most easiest way is just to register an exception listener with the connection and rebuild the connection from here:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}"> connection.setExceptionListener((e) -&gt; {
   connection = cf.createConnection();
   session = connection.createSession();
   consumer = session.createConsumer(session.createQueue(&quot;FANCY.QUEUE.NAME&quot;));
   consumer.setMessageListener((m) -&gt; {
     System.out.println(&quot;onMessage: &quot; + m);
   }
   connection.start();
 });
</pre></div>



<p>Not clean but in theory, this is all that we have to do. Of course, we have to handle the state, the old connection and even worse think about a retry if the connection cannot be created immediately again. The last part considering that we have of course also the requirement to stop the connection and avoid race conditions is the hard part.</p>



<h3 class="wp-block-heading">ReconnectinListener</h3>



<p>Let us build a <code>ReconnectingListener</code> step by step. What we have seen above is that we need a way to determine the desired connection state and we have to provide separate methods for <code>connect </code>and <code>disconnect </code>as we will do this more often, in case we have to retry to re-connect again.</p>



<h4 class="wp-block-heading">Connecting and Disconnecting</h4>



<p>Lets us first solve the connect and disconnect problem. The user should be able to:</p>



<ol class="wp-block-list"><li>Have a separate connect method</li><li>Store the user desire if we should be connected or not</li><li>Have a separate disconnect method</li><li>Have a way to clear the resources without to reset the user desire</li><li>Have a way to check if the connection is up and running</li></ol>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">@RequiredArgsConstructor
static class ReconnectingListener implements MessageListener,  ExceptionListener {
    final JmsConnectionFactory cf;
    final String destinationQueue;
    
    private Connection connection;
    private Session session;
    private MessageConsumer consumer;
    // 1. Have a separate connect method
    public synchronized void connect() throws JMSException {
        // 2. Store the user desire if we should be connected or not
        shouldRun.set(true);
        if (!isConnected()) {
            connection = cf.createConnection();
            session = connection.createSession();
            consumer = session.createConsumer(session.createQueue(destinationQueue));
            consumer.setMessageListener(this); // register us
            connection.setExceptionListener(this); // react on errors
            connection.start();
        }
    }
    // 3. Have a separate disconnect method 
    public synchronized void disconnect() {
        // 2. Store the user desire if we should be connected or not
        shouldRun.set(false);
        clearConnection();
    }
    // 4. Have a way to clear the resources without to reset the user desire
    private synchronized void clearConnection() {
        JmsUtil.close(consumer);
        JmsUtil.close(session);
        JmsUtil.close(connection);
        consumer = null;
        session = null;
        connection = null;
        LOG.debug(&quot;Connection cleared and stoped&quot;);
   }
   // 5. Have a way to check if the connection is up and running
   public boolean isConnected() {
       return connection != null &amp;&amp; consumer != null &amp;&amp; session != null;
   }</pre></div>



<h4 class="wp-block-heading">Reconnect &#8222;onException&#8220;</h4>



<p>Having solved this we have to re-connect back to the JMS Broker if we lose the connection. For this have to implement the <code>ExceptionListener </code>interface as shown above and now to implement <code>onException</code>.  The goal here is now:</p>



<ol class="wp-block-list"><li>Clear the old connection to avoid a double registration</li><li>Schedule a delayed retry to connect again</li><li>Check if we still should be connected</li><li>Retry again, if we fail in our retry to connect to the broker</li></ol>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">// we need a executer to delay a retry attempt
private final ScheduledExecutorService reconnectScheduler = Executors.newScheduledThreadPool(1);
@Override
public void onException(JMSException exception) {
    // 1. Clear the old connection to avoid a double registration
    clearConnection();
    // 2. Schedule a delayed retry to connect again
    reconnect(5);
}
private void reconnect(final int delay) {            
    reconnectScheduler.schedule(() -&gt; {
        // 3. Check if we still should be connected
        if (shouldRun.get()) {
            try {
                // here we use our connect method from above
                connect();
            } catch (Exception e) {
                // 4. Retry again, if we fail in our retry to connect to the broker
                LOG.info(&quot;Reconnect failed, will retry in {}s. {}&quot;, delay, e.getMessage());
                clearConnection(); // just for savety
                reconnect(delay);
            }
        }
    }, delay, TimeUnit.SECONDS);
}</pre></div>



<p>That&#8217;s it. Basically we solved all basic requirements </p>



<h3 class="wp-block-heading">Going further</h3>



<p>We should of course provide the ability to set a subscription filter and maybe we should just implement the <code>Closeable </code>interface to provide a more modern API. Not to forget that we have now hardcoded that we subscribe always to a queue, means a way to tell the code if it is a topic or not would be too bad.  Maybe we should also consider using the JMS 2.x API like:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:&quot;language&quot;,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Java&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;java&quot;}">public synchronized void connectJms2() throws JMSException {
    shouldRun.set(true);
    if (!isConnected()) {
        context = cf.createContext();
        context.setExceptionListener(this);
        context.setAutoStart(true);
        consumer = context.createConsumer(context.createQueue(destinationQueue));
        consumer.setMessageListener(this); // register us
    }
}</pre></div>



<p>Last but not least we could also destroy the executor. Looking forward to a pull request :-).</p>



<h2 class="wp-block-heading">Links</h2>



<ul class="wp-block-list"><li><a rel="noreferrer noopener" href="https://github.com/sterlp/training/blob/master/jms-trainging/src/test/java/org/sterl/training/jms/ibm/IbmReconnectExampleTest.java" target="_blank">Source Code on GitHub</a></li><li><a rel="noreferrer noopener" href="https://docs.oracle.com/cd/E19798-01/821-1751/abljw/index.html" target="_blank">Oracle Docs for connection pool and reconnect for JEE</a></li><li><a href="https://eclipse-ee4j.github.io/glassfish/docs/5.1.0/administration-guide/jms.html" target="_blank" rel="noreferrer noopener">Glassfish Doc</a></li></ul>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://sterl.org/2020/04/reconnecting-jms-listener/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
