Should I re-use JMS connections or not?
igorhvr Apr 21, 2010 9:43 AMHi,
Summary: Creating JMS connections every time is seen as an anti-pattern, but when I keep my connections open for a long time they end up being closed automatically with an error message. I need help to figure out what am I missing / what I should do...
The details:
According to the user manual and to a post I found, re-creating JMS connections (and sessions, message producers, etc) for every message is an anti-pattern:
http://hornetq.sourceforge.net/docs/hornetq-2.0.0.GA/user-manual/en/html_single/index.html#d0e10827
http://community.jboss.org/wiki/ShouldIcacheJMSconnectionsandJMSsessions
On the other hand, I am receiving error messages such as:
"WARNING: I'm closing a JMS connection you left open. Please make sure you close all JMS connections explicitly before letting them go out of scope!"
after some time. I have a stand-alone application (outside JBoss or any application server) that uses HornetQ[1].
Searching for the error message above lead me to the following post:
http://community.jboss.org/message/532379#532379
Where Tim Fox stated:
"This isn't really relevant for HornetQ. All HornetQ connections created from a specific ConnectionFactory share the same TCP connection (assuming you're using core protocol) anyway. Limiting yourself to just one JMS connection is unnecessary."
So... what is the recommended way of dealing with this?
Regards,
Igor.
[1]. This is how I am retrieving a connection factory:
private static ConnectionFactory getHornetqConnectionFactory(String hostname, int port) {
Map<String, Object> connectionParams = new HashMap<String, Object>();
connectionParams.put(TransportConstants.PORT_PROP_NAME, port);
connectionParams.put(TransportConstants.HOST_PROP_NAME, hostname);
TransportConfiguration transportConfiguration = new TransportConfiguration(NettyConnectorFactory.class.getName(),
connectionParams);
HornetQConnectionFactory cf = (HornetQConnectionFactory) HornetQJMSClient.createConnectionFactory(transportConfiguration);
cf.setReconnectAttempts(-1); // Never gives up.
cf.setRetryInterval(1000); // Time to wait in milliseconds.
return cf;
}