0
# Connection Management
1
2
Connection factory implementations providing connection pooling, caching, single connection sharing, and transaction-aware connection management for optimal resource utilization. Spring JMS offers various connection management strategies to balance performance, resource usage, and transaction requirements.
3
4
## Capabilities
5
6
### CachingConnectionFactory
7
8
A connection factory wrapper that caches connections, sessions, and producers for improved performance by reusing expensive JMS resources.
9
10
```java { .api }
11
/**
12
* Connection factory with caching capabilities for improved performance
13
*/
14
public class CachingConnectionFactory implements ConnectionFactory, ExceptionListener, DisposableBean {
15
16
// Constructors
17
public CachingConnectionFactory();
18
public CachingConnectionFactory(ConnectionFactory targetConnectionFactory);
19
20
// Target connection factory configuration
21
public void setTargetConnectionFactory(ConnectionFactory targetConnectionFactory);
22
public ConnectionFactory getTargetConnectionFactory();
23
24
// Session cache configuration
25
public void setSessionCacheSize(int sessionCacheSize);
26
public int getSessionCacheSize();
27
28
// Producer/Consumer cache configuration
29
public void setCacheProducers(boolean cacheProducers);
30
public boolean isCacheProducers();
31
public void setCacheConsumers(boolean cacheConsumers);
32
public boolean isCacheConsumers();
33
34
// Connection cache configuration
35
public void setCacheLevel(int cacheLevel);
36
public int getCacheLevel();
37
public void setCacheLevelName(String constantName);
38
39
// Reconnection configuration
40
public void setReconnectOnException(boolean reconnectOnException);
41
public boolean isReconnectOnException();
42
43
// Exception handling
44
public void setExceptionListener(ExceptionListener exceptionListener);
45
46
// Statistics and monitoring
47
public String getCacheStatistics();
48
public void clearCache();
49
50
// Lifecycle methods
51
public void resetConnection();
52
public void destroy();
53
}
54
```
55
56
### SingleConnectionFactory
57
58
A connection factory that returns the same connection on all createConnection() calls, suitable for simple scenarios where connection sharing is acceptable.
59
60
```java { .api }
61
/**
62
* Connection factory that uses a single shared connection
63
*/
64
public class SingleConnectionFactory implements ConnectionFactory, ExceptionListener, DisposableBean {
65
66
// Constructors
67
public SingleConnectionFactory();
68
public SingleConnectionFactory(Connection target);
69
public SingleConnectionFactory(ConnectionFactory targetConnectionFactory);
70
71
// Target connection factory configuration
72
public void setTargetConnectionFactory(ConnectionFactory targetConnectionFactory);
73
public ConnectionFactory getTargetConnectionFactory();
74
75
// Connection configuration
76
public void setConnection(Connection connection);
77
78
// Client ID configuration
79
public void setClientId(String clientId);
80
public String getClientId();
81
82
// Exception handling and reconnection
83
public void setExceptionListener(ExceptionListener exceptionListener);
84
public void setReconnectOnException(boolean reconnectOnException);
85
public boolean isReconnectOnException();
86
87
// Lifecycle methods
88
public void resetConnection();
89
public void destroy();
90
91
// Connection creation
92
public Connection createConnection() throws JMSException;
93
public Connection createConnection(String username, String password) throws JMSException;
94
}
95
```
96
97
### UserCredentialsConnectionFactoryAdapter
98
99
Connection factory adapter that applies given user credentials to every standard createConnection() call, returning a wrapped Connection that applies the given user credentials to every createSession() call.
100
101
```java { .api }
102
/**
103
* Connection factory adapter for applying user credentials
104
*/
105
public class UserCredentialsConnectionFactoryAdapter implements ConnectionFactory {
106
107
// Constructors
108
public UserCredentialsConnectionFactoryAdapter();
109
110
// Target connection factory configuration
111
public void setTargetConnectionFactory(ConnectionFactory targetConnectionFactory);
112
public ConnectionFactory getTargetConnectionFactory();
113
114
// Credentials configuration
115
public void setUsername(String username);
116
public void setPassword(String password);
117
118
// Connection creation with credentials
119
public Connection createConnection() throws JMSException;
120
public Connection createConnection(String username, String password) throws JMSException;
121
}
122
```
123
124
### TransactionAwareConnectionFactoryProxy
125
126
Proxy for a target JMS ConnectionFactory that is aware of Spring-managed transactions, similar to a transactional JNDI ConnectionFactory as provided by a Java EE application server.
127
128
```java { .api }
129
/**
130
* Transaction-aware connection factory proxy
131
*/
132
public class TransactionAwareConnectionFactoryProxy implements ConnectionFactory {
133
134
// Constructors
135
public TransactionAwareConnectionFactoryProxy();
136
public TransactionAwareConnectionFactoryProxy(ConnectionFactory targetConnectionFactory);
137
138
// Target connection factory configuration
139
public void setTargetConnectionFactory(ConnectionFactory targetConnectionFactory);
140
public ConnectionFactory getTargetConnectionFactory();
141
142
// Transaction synchronization configuration
143
public void setSynchedLocalTransactionAllowed(boolean synchedLocalTransactionAllowed);
144
public boolean isSynchedLocalTransactionAllowed();
145
146
// Connection creation
147
public Connection createConnection() throws JMSException;
148
public Connection createConnection(String username, String password) throws JMSException;
149
}
150
```
151
152
### JmsTransactionManager
153
154
PlatformTransactionManager implementation for JMS, providing transaction management for JMS operations using local JMS transactions.
155
156
```java { .api }
157
/**
158
* PlatformTransactionManager for JMS transactions
159
*/
160
public class JmsTransactionManager extends AbstractPlatformTransactionManager implements InitializingBean {
161
162
// Constructors
163
public JmsTransactionManager();
164
public JmsTransactionManager(ConnectionFactory connectionFactory);
165
166
// Connection factory configuration
167
public void setConnectionFactory(ConnectionFactory connectionFactory);
168
public ConnectionFactory getConnectionFactory();
169
170
// Transaction configuration
171
public void setResourceFactory(ConnectionFactory resourceFactory);
172
173
// Template methods for transaction management
174
protected Object doGetTransaction() throws TransactionException;
175
protected void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException;
176
protected void doCommit(DefaultTransactionStatus status) throws TransactionException;
177
protected void doRollback(DefaultTransactionStatus status) throws TransactionException;
178
}
179
```
180
181
### Connection and Resource Management Utilities
182
183
Utility classes for managing JMS connections and resources with proper exception handling and resource cleanup.
184
185
```java { .api }
186
/**
187
* Utility methods for JMS connection and resource management
188
*/
189
public abstract class ConnectionFactoryUtils {
190
191
// Connection management
192
public static Connection doGetTransactionalConnection(ConnectionFactory cf, ResourceFactory resourceFactory)
193
throws JMSException;
194
public static void releaseConnection(Connection con, ConnectionFactory cf, boolean started);
195
196
// Session management
197
public static Session getTransactionalSession(ConnectionFactory cf, ResourceFactory resourceFactory, boolean startConnection)
198
throws JMSException;
199
public static boolean isSessionTransactional(Session session, ConnectionFactory cf);
200
201
// Resource synchronization
202
public static void registerSynchronization(JmsResourceHolder resourceHolder, ConnectionFactory connectionFactory,
203
ResourceFactory resourceFactory);
204
205
// Exception conversion
206
public static JmsException convertJmsAccessException(JMSException ex);
207
}
208
209
/**
210
* Resource holder for JMS connections and sessions
211
*/
212
public class JmsResourceHolder extends ResourceHolderSupport {
213
214
// Constructors
215
public JmsResourceHolder();
216
public JmsResourceHolder(Connection connection, Session session);
217
public JmsResourceHolder(ConnectionFactory connectionFactory, Connection connection, Session session);
218
219
// Resource management
220
public void addConnection(Connection connection);
221
public void addSession(Session session, Connection connection);
222
public Connection getConnection();
223
public Session getSession();
224
public Session getSession(Class<?> requiredType);
225
226
// Transaction support
227
public boolean isTransacted();
228
public void commitAll() throws JMSException;
229
public void closeAll();
230
}
231
```
232
233
### SmartConnectionFactory
234
235
Extended ConnectionFactory interface that indicates that the underlying JMS ConnectionFactory is capable of providing pooled Connections that participate in a particular transaction.
236
237
```java { .api }
238
/**
239
* Extended ConnectionFactory interface for advanced connection features
240
*/
241
public interface SmartConnectionFactory extends ConnectionFactory {
242
243
/**
244
* Create a connection that should be used within a transaction
245
* @return a connection suitable for transactional use
246
* @throws JMSException in case of JMS errors
247
*/
248
Connection createConnection() throws JMSException;
249
250
/**
251
* Determine whether the underlying ConnectionFactory supports the given ConnectionFactory
252
* @param connectionFactory the ConnectionFactory to check
253
* @return true if supported, false otherwise
254
*/
255
boolean shouldClose(Connection connection);
256
}
257
```
258
259
**Usage Examples:**
260
261
```java
262
import org.springframework.jms.connection.*;
263
import javax.jms.ConnectionFactory;
264
265
// Configuration for different connection management strategies
266
@Configuration
267
public class ConnectionConfig {
268
269
// Basic connection factory (typically from JNDI or JMS provider)
270
@Bean
271
public ConnectionFactory targetConnectionFactory() {
272
// Configure your actual JMS provider's connection factory
273
// e.g., ActiveMQ, IBM MQ, etc.
274
return new org.apache.activemq.ActiveMQConnectionFactory("tcp://localhost:61616");
275
}
276
277
// Caching connection factory for performance
278
@Bean
279
public ConnectionFactory cachingConnectionFactory() {
280
CachingConnectionFactory factory = new CachingConnectionFactory(targetConnectionFactory());
281
factory.setSessionCacheSize(10);
282
factory.setCacheProducers(true);
283
factory.setCacheConsumers(true);
284
factory.setReconnectOnException(true);
285
return factory;
286
}
287
288
// Single connection factory for simple scenarios
289
@Bean
290
public ConnectionFactory singleConnectionFactory() {
291
SingleConnectionFactory factory = new SingleConnectionFactory(targetConnectionFactory());
292
factory.setReconnectOnException(true);
293
factory.setClientId("myApplication");
294
return factory;
295
}
296
297
// Connection factory with user credentials
298
@Bean
299
public ConnectionFactory credentialsConnectionFactory() {
300
UserCredentialsConnectionFactoryAdapter factory = new UserCredentialsConnectionFactoryAdapter();
301
factory.setTargetConnectionFactory(targetConnectionFactory());
302
factory.setUsername("jmsuser");
303
factory.setPassword("jmspassword");
304
return factory;
305
}
306
307
// Transaction-aware connection factory
308
@Bean
309
public ConnectionFactory transactionAwareConnectionFactory() {
310
TransactionAwareConnectionFactoryProxy factory =
311
new TransactionAwareConnectionFactoryProxy(cachingConnectionFactory());
312
factory.setSynchedLocalTransactionAllowed(true);
313
return factory;
314
}
315
316
// JMS transaction manager
317
@Bean
318
public PlatformTransactionManager jmsTransactionManager() {
319
return new JmsTransactionManager(transactionAwareConnectionFactory());
320
}
321
322
// JmsTemplate with caching connection factory
323
@Bean
324
public JmsTemplate jmsTemplate() {
325
return new JmsTemplate(cachingConnectionFactory());
326
}
327
}
328
329
// Service using transactional JMS operations
330
@Service
331
@Transactional
332
public class OrderProcessingService {
333
334
@Autowired
335
private JmsTemplate jmsTemplate;
336
337
// Transactional message sending
338
@Transactional
339
public void processOrderWithTransaction(Order order) {
340
// Send order confirmation
341
jmsTemplate.convertAndSend("order.confirmation", order);
342
343
// Send inventory update
344
jmsTemplate.convertAndSend("inventory.update",
345
new InventoryUpdate(order.getProductId(), -order.getQuantity()));
346
347
// Send billing notification
348
jmsTemplate.convertAndSend("billing.notification",
349
new BillingInfo(order.getCustomerId(), order.getTotal()));
350
351
// If any exception occurs, all messages will be rolled back
352
}
353
}
354
355
// Monitoring and management
356
@Component
357
public class JmsConnectionMonitor {
358
359
@Autowired
360
private ConnectionFactory connectionFactory;
361
362
public void monitorConnectionHealth() {
363
if (connectionFactory instanceof CachingConnectionFactory) {
364
CachingConnectionFactory cachingFactory = (CachingConnectionFactory) connectionFactory;
365
System.out.println("Cache statistics: " + cachingFactory.getCacheStatistics());
366
}
367
}
368
369
public void resetConnections() {
370
if (connectionFactory instanceof CachingConnectionFactory) {
371
((CachingConnectionFactory) connectionFactory).resetConnection();
372
} else if (connectionFactory instanceof SingleConnectionFactory) {
373
((SingleConnectionFactory) connectionFactory).resetConnection();
374
}
375
}
376
}
377
```