Class CachingConnectionFactory
- All Implemented Interfaces:
com.rabbitmq.client.ShutdownListener,EventListener,ConnectionFactory,Aware,BeanNameAware,DisposableBean,InitializingBean,ApplicationContextAware,ApplicationEventPublisherAware,ApplicationListener<ContextClosedEvent>,Lifecycle,Phased,SmartLifecycle
ConnectionFactory implementation that (when the cache mode is CachingConnectionFactory.CacheMode.CHANNEL (default)
returns the same Connection from all createConnection()
calls, and ignores calls to Connection.close() and caches
Channel.
By default, only one Channel will be cached, with further requested Channels being created and disposed on demand.
Consider raising the "channelCacheSize" value in case of a high-concurrency
environment.
When the cache mode is CachingConnectionFactory.CacheMode.CONNECTION, a new (or cached) connection is used for each
createConnection();
connections are cached according to the "connectionCacheSize" value.
Both connections and channels are cached in this mode.
CachingConnectionFactory.CacheMode.CONNECTION is not compatible with a Rabbit Admin that auto-declares queues etc.
NOTE: This ConnectionFactory requires explicit closing of all Channels obtained from its Connection(s).
This is the usual recommendation for native Rabbit access code anyway. However, with this ConnectionFactory, its use
is mandatory in order to actually allow for Channel reuse. Channel.close() returns the channel to the
cache, if there is room, or physically closes the channel otherwise.
- Author:
- Mark Pollack, Mark Fisher, Dave Syer, Gary Russell, Artem Bilan, Steve Powell, Will Droste, Leonardo Ferreira
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic enumThe cache mode.static enumThe type of publisher confirms to use.Nested classes/interfaces inherited from class org.springframework.amqp.rabbit.connection.AbstractConnectionFactory
AbstractConnectionFactory.AddressShuffleMode, AbstractConnectionFactory.DefaultChannelCloseLogger -
Field Summary
Fields inherited from class org.springframework.amqp.rabbit.connection.AbstractConnectionFactory
DEFAULT_CLOSE_TIMEOUT, loggerFields inherited from interface org.springframework.context.SmartLifecycle
DEFAULT_PHASE -
Constructor Summary
ConstructorsConstructorDescriptionCreate a new CachingConnectionFactory initializing the hostname to be the value returned from InetAddress.getLocalHost(), or "localhost" if getLocalHost() throws an exception.CachingConnectionFactory(int port) Create a new CachingConnectionFactory given a port on the hostname returned from InetAddress.getLocalHost(), or "localhost" if getLocalHost() throws an exception.CachingConnectionFactory(com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory) Create a new CachingConnectionFactory for the given target ConnectionFactory.CachingConnectionFactory(String hostname) Create a new CachingConnectionFactory given a host name.CachingConnectionFactory(String hostNameArg, int port) Create a new CachingConnectionFactory given a host name and port.Create a new CachingConnectionFactory given aURI. -
Method Summary
Modifier and TypeMethodDescriptionvoidaddConnectionListener(ConnectionListener listener) voidprotected voidcloseAndClear(Collection<ChannelProxy> theChannels) protected voidcloseChannels(Collection<ChannelProxy> theChannels) final Connectionfinal voiddestroy()Close the underlying shared connection.intprotected ExecutorServiceDetermine the executor service used for target channels.intintgetPhase()Return the cache properties from the underlying publisher sub-factory.booleanReturn true if publisher confirms are enabled.booleanReturn true if publisher returns are enabled.booleanbooleanReturn true if simple publisher confirms are enabled.protected voidreset(Deque<ChannelProxy> channels, Deque<ChannelProxy> txChannels, Map<com.rabbitmq.client.Channel, ChannelProxy> channelsAwaitingAcks) voidClose the connection(s).voidsetCacheMode(CachingConnectionFactory.CacheMode cacheMode) voidsetChannelCacheSize(int sessionCacheSize) The number of channels to maintain in the cache.voidsetChannelCheckoutTimeout(long channelCheckoutTimeout) Sets the channel checkout timeout.voidsetConnectionCacheSize(int connectionCacheSize) voidsetConnectionLimit(int connectionLimit) Set the connection limit when using cache mode CONNECTION.voidsetConnectionListeners(List<? extends ConnectionListener> listeners) voidsetPublisherChannelFactory(PublisherCallbackChannelFactory publisherChannelFactory) Set the factory to use to createPublisherCallbackChannelinstances.voidSet the confirm type to use; defaultCachingConnectionFactory.ConfirmType.NONE.voidsetPublisherConnectionFactory(AbstractConnectionFactory publisherConnectionFactory) Set a custom publisher connection factory; the type does not need to be the same as this factory.voidsetPublisherReturns(boolean publisherReturns) voidstart()voidstop()toString()Methods inherited from class org.springframework.amqp.rabbit.connection.AbstractConnectionFactory
addChannelListener, clearConnectionListeners, createBareConnection, doSetPublisherConnectionFactory, getAddresses, getApplicationContext, getApplicationEventPublisher, getBeanName, getChannelListener, getCloseTimeout, getConnectionListener, getConnectionNameStrategy, getContextStopped, getDefaultHostName, getExecutorService, getHost, getPort, getPublisherConnectionFactory, getRabbitConnectionFactory, getUsername, getVirtualHost, hasPublisherConnectionFactory, onApplicationEvent, removeConnectionListener, setAddresses, setAddressResolver, setAddressShuffleMode, setApplicationContext, setApplicationEventPublisher, setBeanName, setChannelListeners, setCloseExceptionLogger, setCloseTimeout, setConnectionCreatingBackOff, setConnectionNameStrategy, setConnectionThreadFactory, setConnectionTimeout, setExecutor, setHost, setPassword, setPort, setRecoveryListener, setRequestedHeartBeat, setUri, setUri, setUsername, setVirtualHost, shutdownCompletedMethods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface org.springframework.context.ApplicationListener
supportsAsyncExecutionMethods inherited from interface com.rabbitmq.client.ShutdownListener
shutdownCompletedMethods inherited from interface org.springframework.context.SmartLifecycle
isAutoStartup, stop
-
Constructor Details
-
CachingConnectionFactory
public CachingConnectionFactory()Create a new CachingConnectionFactory initializing the hostname to be the value returned from InetAddress.getLocalHost(), or "localhost" if getLocalHost() throws an exception. -
CachingConnectionFactory
-
CachingConnectionFactory
public CachingConnectionFactory(int port) Create a new CachingConnectionFactory given a port on the hostname returned from InetAddress.getLocalHost(), or "localhost" if getLocalHost() throws an exception.- Parameters:
port- the port number
-
CachingConnectionFactory
-
CachingConnectionFactory
-
CachingConnectionFactory
public CachingConnectionFactory(com.rabbitmq.client.ConnectionFactory rabbitConnectionFactory) Create a new CachingConnectionFactory for the given target ConnectionFactory.- Parameters:
rabbitConnectionFactory- the target ConnectionFactory
-
-
Method Details
-
setPublisherConnectionFactory
public void setPublisherConnectionFactory(@Nullable AbstractConnectionFactory publisherConnectionFactory) Description copied from class:AbstractConnectionFactorySet a custom publisher connection factory; the type does not need to be the same as this factory.- Overrides:
setPublisherConnectionFactoryin classAbstractConnectionFactory- Parameters:
publisherConnectionFactory- the factory.
-
setChannelCacheSize
public void setChannelCacheSize(int sessionCacheSize) The number of channels to maintain in the cache. By default, channels are allocated on demand (unbounded) and this represents the maximum cache size. To limit the available channels, seesetChannelCheckoutTimeout(long).- Parameters:
sessionCacheSize- the channel cache size.- See Also:
-
getChannelCacheSize
public int getChannelCacheSize() -
getCacheMode
-
setCacheMode
-
getConnectionCacheSize
public int getConnectionCacheSize() -
setConnectionCacheSize
public void setConnectionCacheSize(int connectionCacheSize) -
setConnectionLimit
public void setConnectionLimit(int connectionLimit) Set the connection limit when using cache mode CONNECTION. When the limit is reached and there are no idle connections, thechannelCheckoutTimeLimitis used to wait for a connection to become idle.- Parameters:
connectionLimit- the limit.- Since:
- 1.5.5
-
isPublisherConfirms
public boolean isPublisherConfirms()Description copied from interface:ConnectionFactoryReturn true if publisher confirms are enabled.- Specified by:
isPublisherConfirmsin interfaceConnectionFactory- Returns:
- publisherConfirms.
-
isPublisherReturns
public boolean isPublisherReturns()Description copied from interface:ConnectionFactoryReturn true if publisher returns are enabled.- Specified by:
isPublisherReturnsin interfaceConnectionFactory- Returns:
- publisherReturns.
-
setPublisherReturns
public void setPublisherReturns(boolean publisherReturns) -
isSimplePublisherConfirms
public boolean isSimplePublisherConfirms()Description copied from interface:ConnectionFactoryReturn true if simple publisher confirms are enabled.- Specified by:
isSimplePublisherConfirmsin interfaceConnectionFactory- Returns:
- simplePublisherConfirms
-
setPublisherConfirmType
Set the confirm type to use; defaultCachingConnectionFactory.ConfirmType.NONE.- Parameters:
confirmType- the confirm type.- Since:
- 2.2
-
setChannelCheckoutTimeout
public void setChannelCheckoutTimeout(long channelCheckoutTimeout) Sets the channel checkout timeout. When greater than 0, enables channel limiting in that thechannelCacheSizebecomes the total number of available channels per connection rather than a simple cache size. Note that changing thechannelCacheSizedoes not affect the limit on existing connection(s), invokedestroy()to cause a new connection to be created with the new limit.Since 1.5.5, also applies to getting a connection when the cache mode is CONNECTION.
- Parameters:
channelCheckoutTimeout- the timeout in milliseconds; default 0 (channel limiting not enabled).- Since:
- 1.4.2
- See Also:
-
setPublisherChannelFactory
Set the factory to use to createPublisherCallbackChannelinstances.- Parameters:
publisherChannelFactory- the factory.- Since:
- 2.1.6
-
getPhase
public int getPhase()- Specified by:
getPhasein interfacePhased- Specified by:
getPhasein interfaceSmartLifecycle
-
afterPropertiesSet
public void afterPropertiesSet()- Specified by:
afterPropertiesSetin interfaceInitializingBean
-
start
-
stop
-
isRunning
-
setConnectionListeners
- Overrides:
setConnectionListenersin classAbstractConnectionFactory
-
addConnectionListener
- Specified by:
addConnectionListenerin interfaceConnectionFactory- Overrides:
addConnectionListenerin classAbstractConnectionFactory
-
createConnection
- Specified by:
createConnectionin interfaceConnectionFactory- Throws:
AmqpException
-
destroy
public final void destroy()Close the underlying shared connection. UseresetConnection()to close the connection while the application is still running.As this bean implements DisposableBean, a bean factory will automatically invoke this on destruction of its cached singletons.
If called after the context is closed, the connection factory can no longer server up connections.
- Specified by:
destroyin interfaceDisposableBean- Overrides:
destroyin classAbstractConnectionFactory
-
resetConnection
public void resetConnection()Close the connection(s). This will impact any in-process operations. New connection(s) will be created on demand after this method returns. This might be used to force a reconnect to the primary broker after failing over to a secondary broker.- Specified by:
resetConnectionin interfaceConnectionFactory
-
reset
protected void reset(Deque<ChannelProxy> channels, Deque<ChannelProxy> txChannels, Map<com.rabbitmq.client.Channel, ChannelProxy> channelsAwaitingAcks) -
closeAndClear
-
closeChannels
-
getCacheProperties
-
getPublisherConnectionFactoryCacheProperties
Return the cache properties from the underlying publisher sub-factory.- Returns:
- the properties.
- Since:
- 2.0.2
-
getChannelsExecutor
Determine the executor service used for target channels.- Returns:
- specified executor service otherwise the default one is created and returned.
- Since:
- 1.7.9
-
toString
- Overrides:
toStringin classAbstractConnectionFactory
-