001/** 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.activemq.jms.pool; 018 019import java.util.Properties; 020import java.util.concurrent.atomic.AtomicBoolean; 021import java.util.concurrent.atomic.AtomicReference; 022 023import javax.jms.Connection; 024import javax.jms.ConnectionFactory; 025import javax.jms.JMSException; 026import javax.jms.QueueConnection; 027import javax.jms.QueueConnectionFactory; 028import javax.jms.TopicConnection; 029import javax.jms.TopicConnectionFactory; 030 031import org.apache.commons.pool2.KeyedPooledObjectFactory; 032import org.apache.commons.pool2.PooledObject; 033import org.apache.commons.pool2.impl.DefaultPooledObject; 034import org.apache.commons.pool2.impl.GenericKeyedObjectPool; 035import org.slf4j.Logger; 036import org.slf4j.LoggerFactory; 037 038/** 039 * A JMS provider which pools Connection, Session and MessageProducer instances 040 * so it can be used with tools like <a href="http://camel.apache.org/activemq.html">Camel</a> and Spring's 041 * <a href="http://activemq.apache.org/spring-support.html">JmsTemplate and MessagListenerContainer</a>. 042 * Connections, sessions and producers are returned to a pool after use so that they can be reused later 043 * without having to undergo the cost of creating them again. 044 * 045 * b>NOTE:</b> while this implementation does allow the creation of a collection of active consumers, 046 * it does not 'pool' consumers. Pooling makes sense for connections, sessions and producers, which 047 * are expensive to create and can remain idle a minimal cost. Consumers, on the other hand, are usually 048 * just created at startup and left active, handling incoming messages as they come. When a consumer is 049 * complete, it is best to close it rather than return it to a pool for later reuse: this is because, 050 * even if a consumer is idle, ActiveMQ will keep delivering messages to the consumer's prefetch buffer, 051 * where they'll get held until the consumer is active again. 052 * 053 * If you are creating a collection of consumers (for example, for multi-threaded message consumption), you 054 * might want to consider using a lower prefetch value for each consumer (e.g. 10 or 20), to ensure that 055 * all messages don't end up going to just one of the consumers. See this FAQ entry for more detail: 056 * http://activemq.apache.org/i-do-not-receive-messages-in-my-second-consumer.html 057 * 058 * Optionally, one may configure the pool to examine and possibly evict objects as they sit idle in the 059 * pool. This is performed by an "idle object eviction" thread, which runs asynchronously. Caution should 060 * be used when configuring this optional feature. Eviction runs contend with client threads for access 061 * to objects in the pool, so if they run too frequently performance issues may result. The idle object 062 * eviction thread may be configured using the {@link org.apache.activemq.jms.pool.PooledConnectionFactory#setTimeBetweenExpirationCheckMillis} method. By 063 * default the value is -1 which means no eviction thread will be run. Set to a non-negative value to 064 * configure the idle eviction thread to run. 065 * 066 */ 067public class PooledConnectionFactory implements ConnectionFactory, QueueConnectionFactory, TopicConnectionFactory { 068 private static final transient Logger LOG = LoggerFactory.getLogger(PooledConnectionFactory.class); 069 070 protected final AtomicBoolean stopped = new AtomicBoolean(false); 071 private GenericKeyedObjectPool<ConnectionKey, ConnectionPool> connectionsPool; 072 073 protected Object connectionFactory; 074 075 private int maximumActiveSessionPerConnection = 500; 076 private int idleTimeout = 30 * 1000; 077 private boolean blockIfSessionPoolIsFull = true; 078 private long blockIfSessionPoolIsFullTimeout = -1L; 079 private long expiryTimeout = 0l; 080 private boolean createConnectionOnStartup = true; 081 private boolean useAnonymousProducers = true; 082 private boolean reconnectOnException = true; 083 084 // Temporary value used to always fetch the result of makeObject. 085 private final AtomicReference<ConnectionPool> mostRecentlyCreated = new AtomicReference<ConnectionPool>(null); 086 087 public void initConnectionsPool() { 088 if (this.connectionsPool == null) { 089 this.connectionsPool = new GenericKeyedObjectPool<ConnectionKey, ConnectionPool>( 090 new KeyedPooledObjectFactory<ConnectionKey, ConnectionPool>() { 091 @Override 092 public PooledObject<ConnectionPool> makeObject(ConnectionKey connectionKey) throws Exception { 093 Connection delegate = createConnection(connectionKey); 094 095 ConnectionPool connection = createConnectionPool(delegate); 096 connection.setIdleTimeout(getIdleTimeout()); 097 connection.setExpiryTimeout(getExpiryTimeout()); 098 connection.setMaximumActiveSessionPerConnection(getMaximumActiveSessionPerConnection()); 099 connection.setBlockIfSessionPoolIsFull(isBlockIfSessionPoolIsFull()); 100 if (isBlockIfSessionPoolIsFull() && getBlockIfSessionPoolIsFullTimeout() > 0) { 101 connection.setBlockIfSessionPoolIsFullTimeout(getBlockIfSessionPoolIsFullTimeout()); 102 } 103 connection.setUseAnonymousProducers(isUseAnonymousProducers()); 104 connection.setReconnectOnException(isReconnectOnException()); 105 106 if (LOG.isTraceEnabled()) { 107 LOG.trace("Created new connection: {}", connection); 108 } 109 110 PooledConnectionFactory.this.mostRecentlyCreated.set(connection); 111 112 return new DefaultPooledObject<ConnectionPool>(connection); 113 } 114 115 @Override 116 public void destroyObject(ConnectionKey connectionKey, PooledObject<ConnectionPool> pooledObject) throws Exception { 117 ConnectionPool connection = pooledObject.getObject(); 118 try { 119 if (LOG.isTraceEnabled()) { 120 LOG.trace("Destroying connection: {}", connection); 121 } 122 connection.close(); 123 } catch (Exception e) { 124 LOG.warn("Close connection failed for connection: " + connection + ". This exception will be ignored.",e); 125 } 126 } 127 128 @Override 129 public boolean validateObject(ConnectionKey connectionKey, PooledObject<ConnectionPool> pooledObject) { 130 ConnectionPool connection = pooledObject.getObject(); 131 if (connection != null && connection.expiredCheck()) { 132 if (LOG.isTraceEnabled()) { 133 LOG.trace("Connection has expired: {} and will be destroyed", connection); 134 } 135 136 return false; 137 } 138 139 return true; 140 } 141 142 @Override 143 public void activateObject(ConnectionKey connectionKey, PooledObject<ConnectionPool> pooledObject) throws Exception { 144 } 145 146 @Override 147 public void passivateObject(ConnectionKey connectionKey, PooledObject<ConnectionPool> pooledObject) throws Exception { 148 } 149 150 }); 151 152 // Set max idle (not max active) since our connections always idle in the pool. 153 this.connectionsPool.setMaxIdlePerKey(1); 154 this.connectionsPool.setLifo(false); 155 156 // We always want our validate method to control when idle objects are evicted. 157 this.connectionsPool.setTestOnBorrow(true); 158 this.connectionsPool.setTestWhileIdle(true); 159 } 160 } 161 162 /** 163 * @return the currently configured ConnectionFactory used to create the pooled Connections. 164 */ 165 public Object getConnectionFactory() { 166 return connectionFactory; 167 } 168 169 /** 170 * Sets the ConnectionFactory used to create new pooled Connections. 171 * <p/> 172 * Updates to this value do not affect Connections that were previously created and placed 173 * into the pool. In order to allocate new Connections based off this new ConnectionFactory 174 * it is first necessary to {@link #clear} the pooled Connections. 175 * 176 * @param toUse 177 * The factory to use to create pooled Connections. 178 */ 179 public void setConnectionFactory(final Object toUse) { 180 if (toUse instanceof ConnectionFactory) { 181 this.connectionFactory = toUse; 182 } else { 183 throw new IllegalArgumentException("connectionFactory should implement javax.jmx.ConnectionFactory"); 184 } 185 } 186 187 @Override 188 public QueueConnection createQueueConnection() throws JMSException { 189 return (QueueConnection) createConnection(); 190 } 191 192 @Override 193 public QueueConnection createQueueConnection(String userName, String password) throws JMSException { 194 return (QueueConnection) createConnection(userName, password); 195 } 196 197 @Override 198 public TopicConnection createTopicConnection() throws JMSException { 199 return (TopicConnection) createConnection(); 200 } 201 202 @Override 203 public TopicConnection createTopicConnection(String userName, String password) throws JMSException { 204 return (TopicConnection) createConnection(userName, password); 205 } 206 207 @Override 208 public Connection createConnection() throws JMSException { 209 return createConnection(null, null); 210 } 211 212 @Override 213 public synchronized Connection createConnection(String userName, String password) throws JMSException { 214 if (stopped.get()) { 215 LOG.debug("PooledConnectionFactory is stopped, skip create new connection."); 216 return null; 217 } 218 219 ConnectionPool connection = null; 220 ConnectionKey key = new ConnectionKey(userName, password); 221 222 // This will either return an existing non-expired ConnectionPool or it 223 // will create a new one to meet the demand. 224 if (getConnectionsPool().getNumIdle(key) < getMaxConnections()) { 225 try { 226 connectionsPool.addObject(key); 227 connection = mostRecentlyCreated.getAndSet(null); 228 connection.incrementReferenceCount(); 229 } catch (Exception e) { 230 throw createJmsException("Error while attempting to add new Connection to the pool", e); 231 } 232 } else { 233 try { 234 // We can race against other threads returning the connection when there is an 235 // expiration or idle timeout. We keep pulling out ConnectionPool instances until 236 // we win and get a non-closed instance and then increment the reference count 237 // under lock to prevent another thread from triggering an expiration check and 238 // pulling the rug out from under us. 239 while (connection == null) { 240 connection = connectionsPool.borrowObject(key); 241 synchronized (connection) { 242 if (connection.getConnection() != null) { 243 connection.incrementReferenceCount(); 244 break; 245 } 246 247 // Return the bad one to the pool and let if get destroyed as normal. 248 connectionsPool.returnObject(key, connection); 249 connection = null; 250 } 251 } 252 } catch (Exception e) { 253 throw createJmsException("Error while attempting to retrieve a connection from the pool", e); 254 } 255 256 try { 257 connectionsPool.returnObject(key, connection); 258 } catch (Exception e) { 259 throw createJmsException("Error when returning connection to the pool", e); 260 } 261 } 262 263 return newPooledConnection(connection); 264 } 265 266 protected Connection newPooledConnection(ConnectionPool connection) { 267 return new PooledConnection(connection); 268 } 269 270 private JMSException createJmsException(String msg, Exception cause) { 271 JMSException exception = new JMSException(msg); 272 exception.setLinkedException(cause); 273 exception.initCause(cause); 274 return exception; 275 } 276 277 protected Connection createConnection(ConnectionKey key) throws JMSException { 278 if (connectionFactory instanceof ConnectionFactory) { 279 if (key.getUserName() == null && key.getPassword() == null) { 280 return ((ConnectionFactory) connectionFactory).createConnection(); 281 } else { 282 return ((ConnectionFactory) connectionFactory).createConnection(key.getUserName(), key.getPassword()); 283 } 284 } else { 285 throw new IllegalStateException("connectionFactory should implement javax.jms.ConnectionFactory"); 286 } 287 } 288 289 public void start() { 290 LOG.debug("Staring the PooledConnectionFactory: create on start = {}", isCreateConnectionOnStartup()); 291 stopped.set(false); 292 if (isCreateConnectionOnStartup()) { 293 try { 294 // warm the pool by creating a connection during startup 295 createConnection().close(); 296 } catch (JMSException e) { 297 LOG.warn("Create pooled connection during start failed. This exception will be ignored.", e); 298 } 299 } 300 } 301 302 public void stop() { 303 if (stopped.compareAndSet(false, true)) { 304 LOG.debug("Stopping the PooledConnectionFactory, number of connections in cache: {}", 305 connectionsPool != null ? connectionsPool.getNumActive() : 0); 306 try { 307 if (connectionsPool != null) { 308 connectionsPool.close(); 309 } 310 } catch (Exception e) { 311 } 312 } 313 } 314 315 /** 316 * Clears all connections from the pool. Each connection that is currently in the pool is 317 * closed and removed from the pool. A new connection will be created on the next call to 318 * {@link #createConnection}. Care should be taken when using this method as Connections that 319 * are in use be client's will be closed. 320 */ 321 public void clear() { 322 323 if (stopped.get()) { 324 return; 325 } 326 327 getConnectionsPool().clear(); 328 } 329 330 /** 331 * Returns the currently configured maximum number of sessions a pooled Connection will 332 * create before it either blocks or throws an exception when a new session is requested, 333 * depending on configuration. 334 * 335 * @return the number of session instances that can be taken from a pooled connection. 336 */ 337 public int getMaximumActiveSessionPerConnection() { 338 return maximumActiveSessionPerConnection; 339 } 340 341 /** 342 * Sets the maximum number of active sessions per connection 343 * 344 * @param maximumActiveSessionPerConnection 345 * The maximum number of active session per connection in the pool. 346 */ 347 public void setMaximumActiveSessionPerConnection(int maximumActiveSessionPerConnection) { 348 this.maximumActiveSessionPerConnection = maximumActiveSessionPerConnection; 349 } 350 351 /** 352 * Controls the behavior of the internal session pool. By default the call to 353 * Connection.getSession() will block if the session pool is full. If the 354 * argument false is given, it will change the default behavior and instead the 355 * call to getSession() will throw a JMSException. 356 * 357 * The size of the session pool is controlled by the @see #maximumActive 358 * property. 359 * 360 * @param block - if true, the call to getSession() blocks if the pool is full 361 * until a session object is available. defaults to true. 362 */ 363 public void setBlockIfSessionPoolIsFull(boolean block) { 364 this.blockIfSessionPoolIsFull = block; 365 } 366 367 /** 368 * Returns whether a pooled Connection will enter a blocked state or will throw an Exception 369 * once the maximum number of sessions has been borrowed from the the Session Pool. 370 * 371 * @return true if the pooled Connection createSession method will block when the limit is hit. 372 * @see #setBlockIfSessionPoolIsFull(boolean) 373 */ 374 public boolean isBlockIfSessionPoolIsFull() { 375 return this.blockIfSessionPoolIsFull; 376 } 377 378 /** 379 * Returns the maximum number to pooled Connections that this factory will allow before it 380 * begins to return connections from the pool on calls to ({@link #createConnection}. 381 * 382 * @return the maxConnections that will be created for this pool. 383 */ 384 public int getMaxConnections() { 385 return getConnectionsPool().getMaxIdlePerKey(); 386 } 387 388 /** 389 * Sets the maximum number of pooled Connections (defaults to one). Each call to 390 * {@link #createConnection} will result in a new Connection being create up to the max 391 * connections value. 392 * 393 * @param maxConnections the maxConnections to set 394 */ 395 public void setMaxConnections(int maxConnections) { 396 getConnectionsPool().setMaxIdlePerKey(maxConnections); 397 getConnectionsPool().setMaxTotalPerKey(maxConnections); 398 } 399 400 /** 401 * Gets the Idle timeout value applied to new Connection's that are created by this pool. 402 * <p/> 403 * The idle timeout is used determine if a Connection instance has sat to long in the pool unused 404 * and if so is closed and removed from the pool. The default value is 30 seconds. 405 * 406 * @return idle timeout value (milliseconds) 407 */ 408 public int getIdleTimeout() { 409 return idleTimeout; 410 } 411 412 /** 413 * Sets the idle timeout value for Connection's that are created by this pool in Milliseconds, 414 * defaults to 30 seconds. 415 * <p/> 416 * For a Connection that is in the pool but has no current users the idle timeout determines how 417 * long the Connection can live before it is eligible for removal from the pool. Normally the 418 * connections are tested when an attempt to check one out occurs so a Connection instance can sit 419 * in the pool much longer than its idle timeout if connections are used infrequently. 420 * 421 * @param idleTimeout 422 * The maximum time a pooled Connection can sit unused before it is eligible for removal. 423 */ 424 public void setIdleTimeout(int idleTimeout) { 425 this.idleTimeout = idleTimeout; 426 } 427 428 /** 429 * allow connections to expire, irrespective of load or idle time. This is useful with failover 430 * to force a reconnect from the pool, to reestablish load balancing or use of the master post recovery 431 * 432 * @param expiryTimeout non zero in milliseconds 433 */ 434 public void setExpiryTimeout(long expiryTimeout) { 435 this.expiryTimeout = expiryTimeout; 436 } 437 438 /** 439 * @return the configured expiration timeout for connections in the pool. 440 */ 441 public long getExpiryTimeout() { 442 return expiryTimeout; 443 } 444 445 /** 446 * @return true if a Connection is created immediately on a call to {@link start}. 447 */ 448 public boolean isCreateConnectionOnStartup() { 449 return createConnectionOnStartup; 450 } 451 452 /** 453 * Whether to create a connection on starting this {@link PooledConnectionFactory}. 454 * <p/> 455 * This can be used to warm-up the pool on startup. Notice that any kind of exception 456 * happens during startup is logged at WARN level and ignored. 457 * 458 * @param createConnectionOnStartup <tt>true</tt> to create a connection on startup 459 */ 460 public void setCreateConnectionOnStartup(boolean createConnectionOnStartup) { 461 this.createConnectionOnStartup = createConnectionOnStartup; 462 } 463 464 /** 465 * Should Sessions use one anonymous producer for all producer requests or should a new 466 * MessageProducer be created for each request to create a producer object, default is true. 467 * 468 * When enabled the session only needs to allocate one MessageProducer for all requests and 469 * the MessageProducer#send(destination, message) method can be used. Normally this is the 470 * right thing to do however it does result in the Broker not showing the producers per 471 * destination. 472 * 473 * @return true if a PooledSession will use only a single anonymous message producer instance. 474 */ 475 public boolean isUseAnonymousProducers() { 476 return this.useAnonymousProducers; 477 } 478 479 /** 480 * Sets whether a PooledSession uses only one anonymous MessageProducer instance or creates 481 * a new MessageProducer for each call the create a MessageProducer. 482 * 483 * @param value 484 * Boolean value that configures whether anonymous producers are used. 485 */ 486 public void setUseAnonymousProducers(boolean value) { 487 this.useAnonymousProducers = value; 488 } 489 490 /** 491 * Gets the Pool of ConnectionPool instances which are keyed by different ConnectionKeys. 492 * 493 * @return this factories pool of ConnectionPool instances. 494 */ 495 protected GenericKeyedObjectPool<ConnectionKey, ConnectionPool> getConnectionsPool() { 496 initConnectionsPool(); 497 return this.connectionsPool; 498 } 499 500 /** 501 * Sets the number of milliseconds to sleep between runs of the idle Connection eviction thread. 502 * When non-positive, no idle object eviction thread will be run, and Connections will only be 503 * checked on borrow to determine if they have sat idle for too long or have failed for some 504 * other reason. 505 * <p/> 506 * By default this value is set to -1 and no expiration thread ever runs. 507 * 508 * @param timeBetweenExpirationCheckMillis 509 * The time to wait between runs of the idle Connection eviction thread. 510 */ 511 public void setTimeBetweenExpirationCheckMillis(long timeBetweenExpirationCheckMillis) { 512 getConnectionsPool().setTimeBetweenEvictionRunsMillis(timeBetweenExpirationCheckMillis); 513 } 514 515 /** 516 * @return the number of milliseconds to sleep between runs of the idle connection eviction thread. 517 */ 518 public long getTimeBetweenExpirationCheckMillis() { 519 return getConnectionsPool().getTimeBetweenEvictionRunsMillis(); 520 } 521 522 /** 523 * @return the number of Connections currently in the Pool 524 */ 525 public int getNumConnections() { 526 return getConnectionsPool().getNumIdle(); 527 } 528 529 /** 530 * Delegate that creates each instance of an ConnectionPool object. Subclasses can override 531 * this method to customize the type of connection pool returned. 532 * 533 * @param connection 534 * 535 * @return instance of a new ConnectionPool. 536 */ 537 protected ConnectionPool createConnectionPool(Connection connection) { 538 return new ConnectionPool(connection); 539 } 540 541 /** 542 * Returns the timeout to use for blocking creating new sessions 543 * 544 * @return true if the pooled Connection createSession method will block when the limit is hit. 545 * @see #setBlockIfSessionPoolIsFull(boolean) 546 */ 547 public long getBlockIfSessionPoolIsFullTimeout() { 548 return blockIfSessionPoolIsFullTimeout; 549 } 550 551 /** 552 * Controls the behavior of the internal session pool. By default the call to 553 * Connection.getSession() will block if the session pool is full. This setting 554 * will affect how long it blocks and throws an exception after the timeout. 555 * 556 * The size of the session pool is controlled by the @see #maximumActive 557 * property. 558 * 559 * Whether or not the call to create session blocks is controlled by the @see #blockIfSessionPoolIsFull 560 * property 561 * 562 * @param blockIfSessionPoolIsFullTimeout - if blockIfSessionPoolIsFullTimeout is true, 563 * then use this setting to configure how long to block before retry 564 */ 565 public void setBlockIfSessionPoolIsFullTimeout(long blockIfSessionPoolIsFullTimeout) { 566 this.blockIfSessionPoolIsFullTimeout = blockIfSessionPoolIsFullTimeout; 567 } 568 569 /** 570 * @return true if the underlying connection will be renewed on JMSException, false otherwise 571 */ 572 public boolean isReconnectOnException() { 573 return reconnectOnException; 574 } 575 576 /** 577 * Controls weather the underlying connection should be reset (and renewed) on JMSException 578 * 579 * @param reconnectOnException 580 * Boolean value that configures whether reconnect on exception should happen 581 */ 582 public void setReconnectOnException(boolean reconnectOnException) { 583 this.reconnectOnException = reconnectOnException; 584 } 585 586 /** 587 * Called by any superclass that implements a JNDIReferencable or similar that needs to collect 588 * the properties of this class for storage etc. 589 * 590 * This method should be updated any time there is a new property added. 591 * 592 * @param props 593 * a properties object that should be filled in with this objects property values. 594 */ 595 protected void populateProperties(Properties props) { 596 props.setProperty("maximumActiveSessionPerConnection", Integer.toString(getMaximumActiveSessionPerConnection())); 597 props.setProperty("maxConnections", Integer.toString(getMaxConnections())); 598 props.setProperty("idleTimeout", Integer.toString(getIdleTimeout())); 599 props.setProperty("expiryTimeout", Long.toString(getExpiryTimeout())); 600 props.setProperty("timeBetweenExpirationCheckMillis", Long.toString(getTimeBetweenExpirationCheckMillis())); 601 props.setProperty("createConnectionOnStartup", Boolean.toString(isCreateConnectionOnStartup())); 602 props.setProperty("useAnonymousProducers", Boolean.toString(isUseAnonymousProducers())); 603 props.setProperty("blockIfSessionPoolIsFullTimeout", Long.toString(getBlockIfSessionPoolIsFullTimeout())); 604 props.setProperty("reconnectOnException", Boolean.toString(isReconnectOnException())); 605 } 606}