0

I am using Apache Camel with Spring to send messages from my Java service. I need to reset JMS connection in case of any error occurred at exchange. I am using below code to achieve my objective.

try
{
    producerTemplate.sendBody(endPoint, bytes);
}
catch (final RuntimeCamelException exception)
{
    LOGGER.error("Exception occured in sendBody", exception.getMessage(), exception);
    handleError(); // handle error here.
}

In camel context, I have defined CachingConnectionFactory with exception listener and made reconnectOnException=true

<bean id="testConnectionFactory" class="org.apache.qpid.jms.JmsConnectionFactory">
    <property name="username" value="${user.name}" />
    <property name="password" value="${user.password}" />
    <property name="clientID" value="${host.address}" />
    <property name="remoteURI"
        value="amqp://${host.address}:${host.port}?jms.clientID=${host.address}?jms.username=${user.name}&amp;jms.password=${user.password}&amp;jms.redeliveryPolicy.maxRedeliveries=${message.retry.count}&amp;amqp.saslMechanisms=PLAIN" />
</bean>

<bean id="testCachingConnectionFactory"
    class="org.springframework.jms.connection.CachingConnectionFactory">
            <property name="exceptionListener" ref="testCachingConnectionFactory" />
            <property name="targetConnectionFactory" ref="testConnectionFactory" />
            <property name="reconnectOnException" value="true" />
</bean>

In my case, JMSSecurityException is thrown from try block at below line

producerTemplate.sendBody(endPoint, bytes)

execution goes inside catch block but OnException() of SingleConnectionFactory is never called even though exceptionListener is defined. The idea is to call ultimately resetConnection() (inside OnException) to reset JMS connection.

1 Answers1

2

Implement ExceptionListenerand add the exception listener definition as a property to your spring connection factory testCachingConnectionFactory.

For example create an exception listener class (component) JmsExceptionListener:

public class JmsExceptionListener implements ExceptionListener {    
    @Override
    public void onException(JMSException exception) {
        // what ever you wanna do here!
    }
}

Then add a bean definition for JmsExceptionListener:

<bean id="jmsExceptionListener" class="JmsExceptionListener"></bean>

And then add the definition as an exception-listener property:

<property name="exceptionListener" ref="jmsExceptionListener"/>

instead of what you are using in your configuration:

<property name="exceptionListener" ref="testCachingConnectionFactory" />

Omoro
  • 972
  • 11
  • 22
  • 1
    CachingConnectionFactory's parent class SingleConnectionFactory itself implements ExceptionListener...so we don't need to create any custom class. – Dhaval Salwala Oct 31 '17 at 20:03