I see, I tested this and I get a
javax.jms.InvalidClientIDException: clientId already exists for every send within an onMessage() (except for the first onMessage()).
I can see that all the onMessage() calls take place in the same thread. However it seems the jmsTemplate.send() is trying to call createConnection(). I tried using both SingleConnectionFactory and CachingConnectionFactory.
Portion of stack trace for the javax.jms.InvalidClientIDException exception:
Code:
at org.springframework.jms.connection.SingleConnectionFactory.doCreateConnection(SingleConnectionFactory.java:342)
at org.springframework.jms.connection.SingleConnectionFactory.initConnection(SingleConnectionFactory.java:288)
at org.springframework.jms.connection.SingleConnectionFactory.createConnection(SingleConnectionFactory.java:225)
at org.springframework.jms.support.JmsAccessor.createConnection(JmsAccessor.java:184)
at org.springframework.jms.core.JmsTemplate.execute(JmsTemplate.java:456)
at org.springframework.jms.core.JmsTemplate.send(JmsTemplate.java:534)
I also wrote a CustomSingleConnection factory that extends SingleConnectionFactory
Code:
public class CustomConnectionFactory extends SingleConnectionFactory{
ConnectionFactory factory = null;
Connection connection = null;
int count = 0;
public CustomConnectionFactory(ConnectionFactory factory){
super(factory);
this.factory = factory;
}
public Connection createConnection()
throws JMSException{
count++;
System.out.println("Create connection was called " + count + " times in the thread " + Thread.currentThread().getId());
if(null==connection){
System.out.println("Connection was NULL creating new connection!");
connection = factory.createConnection();
System.out.println("Connection created with clientId " + connection.getClientID());
}
connection.setExceptionListener(new ExceptionListener() {
public void onException(JMSException ex) {
System.out.println("Connection got closed!!!!!!!!!!!!!" + ex.getMessage());
}
});
return connection;
}
}
CustomConnectionFactory works for me because the connection gets closed at the end of every send() call and recreated at the next send() call. But in any case I would'nt want a new connection to be opened everytime a send() is called.
This is what my config looks like:
Code:
<bean id="pubCachingConnectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
<property name="targetConnectionFactory" ref="pubConnectionFactory" />
<property name="reconnectOnException" value="true"/>
<property name="sessionCacheSize" value="1" />
</bean>
Any idea why the CachingConnectionFactory would not simply reuse the previously created connection?