Class DirectMessageListenerContainer
java.lang.Object
org.springframework.amqp.rabbit.connection.RabbitAccessor
org.springframework.amqp.rabbit.listener.ObservableListenerContainer
org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer
org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer
- All Implemented Interfaces:
MessageListenerContainer
,Aware
,BeanNameAware
,DisposableBean
,InitializingBean
,ApplicationContextAware
,ApplicationEventPublisherAware
,Lifecycle
,Phased
,SmartLifecycle
- Direct Known Subclasses:
DirectReplyToMessageListenerContainer
The
SimpleMessageListenerContainer
is not so simple. Recent changes to the
rabbitmq java client has facilitated a much simpler listener container that invokes the
listener directly on the rabbit client consumer thread. There is no txSize property -
each message is acked (or nacked) individually.- Since:
- 2.0
- Author:
- Gary Russell, Artem Bilan, Nicolas Ristock, Cao Weibo
-
Nested Class Summary
Nested classes/interfaces inherited from class org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer
AbstractMessageListenerContainer.JavaLangErrorHandler, AbstractMessageListenerContainer.SharedConnectionNotInitializedException, AbstractMessageListenerContainer.WrappedTransactionException
-
Field Summary
Modifier and TypeFieldDescriptionprotected final List<org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer.SimpleConsumer>
Fields inherited from class org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer
consumersMonitor, DEFAULT_DEBATCHING_ENABLED, DEFAULT_PREFETCH_COUNT, DEFAULT_RECOVERY_INTERVAL, DEFAULT_SHUTDOWN_TIMEOUT
Fields inherited from class org.springframework.amqp.rabbit.connection.RabbitAccessor
logger
Fields inherited from interface org.springframework.context.SmartLifecycle
DEFAULT_PHASE
-
Constructor Summary
ConstructorDescriptionCreate an instance;RabbitAccessor.setConnectionFactory(ConnectionFactory)
must be called before starting.DirectMessageListenerContainer
(ConnectionFactory connectionFactory) Create an instance with the provided connection factory. -
Method Summary
Modifier and TypeMethodDescriptionprotected void
void
addQueueNames
(String... queueNames) Add queue(s) to this container's list of queues.void
Add queue(s) to this container's list of queues.protected void
protected void
consumerRemoved
(org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer.SimpleConsumer consumer) Called whenever a consumer is removed.protected void
Register any invokers within this container.protected void
protected void
Close the registered invokers.protected void
doStart()
Start this container, and notify all invoker tasks.protected void
doStop()
This method is invoked when the container is stopping.protected int
When adjusting down, return a consumer that can be canceled.protected void
Subclasses can override this to take additional actions when the monitor task runs.boolean
removeQueueNames
(String... queueNames) Remove queue(s) from this container's list of queues.boolean
removeQueues
(Queue... queues) Remove queue(s) from this container's list of queues.void
setAckTimeout
(long ackTimeout) An approximate timeout; whenmessagesPerAck
is greater than 1, and this time elapses since the last ack, the pending acks will be sent either when the next message arrives, or a short time later if no additional messages arrive.void
setConsumersPerQueue
(int consumersPerQueue) Each queue runs in its own consumer; set this property to create multiple consumers for each queue.final void
setExclusive
(boolean exclusive) Set to true for an exclusive consumer - if true, theconsumers per queue
must be 1.void
setMessagesPerAck
(int messagesPerAck) Set the number of messages to receive before acknowledging (success).final void
setMissingQueuesFatal
(boolean missingQueuesFatal) If all of the configured queue(s) are not available on the broker, this setting determines whether the condition is fatal.void
setMonitorInterval
(long monitorInterval) Set how often to run a task to check for failed consumers and idle containers.void
setQueueNames
(String... queueName) Set the name of the queue(s) to receive messages from.void
setTaskScheduler
(TaskScheduler taskScheduler) Set the task scheduler to use for the task that monitors idle containers and failed consumers.Methods inherited from class org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer
actualInvokeListener, addAfterReceivePostProcessors, afterPropertiesSet, causeChainHasImmediateAcknowledgeAmqpException, checkMessageListener, checkMismatchedQueues, configureAdminIfNeeded, debatch, destroy, doInvokeListener, doInvokeListener, doSetPossibleAuthenticationFailureFatal, executeListener, executeListenerAndHandleException, getAcknowledgeMode, getAdviceChain, getAfterReceivePostProcessors, getAmqpAdmin, getApplicationEventPublisher, getBatchingStrategy, getConnectionFactory, getConsumeDelay, getConsumerArguments, getConsumerTagStrategy, getExclusiveConsumerExceptionLogger, getFailedDeclarationRetryInterval, getIdleEventInterval, getJavaLangErrorHandler, getLastReceive, getMessageAckListener, getMessageListener, getMessagePropertiesConverter, getPhase, getPrefetchCount, getQueueNames, getQueueNamesAsSet, getQueueNamesToQueues, getRecoveryBackOff, getRoutingConnectionFactory, getRoutingLookupKey, getShutdownTimeout, getTaskExecutor, getTransactionAttribute, getTransactionManager, handleListenerException, initialize, initializeProxy, invokeErrorHandler, invokeListener, isActive, isAlwaysRequeueWithTxManagerRollback, isAsyncReplies, isAutoDeclare, isAutoStartup, isChannelLocallyTransacted, isDeBatchingEnabled, isDefaultRequeueRejected, isExclusive, isExposeListenerChannel, isForceCloseChannel, isGlobalQos, isMismatchedQueuesFatal, isMissingQueuesFatal, isMissingQueuesFatalSet, isNoLocal, isPossibleAuthenticationFailureFatal, isPossibleAuthenticationFailureFatalSet, isRunning, isStatefulRetryFatalWithNullMessageId, lazyLoad, prepareHolderForRollback, publishConsumerFailedEvent, publishIdleContainerEvent, publishMissingQueueEvent, redeclareElementsIfNecessary, removeAfterReceivePostProcessor, setAcknowledgeMode, setAdviceChain, setAfterReceivePostProcessors, setAlwaysRequeueWithTxManagerRollback, setAmqpAdmin, setApplicationEventPublisher, setAutoDeclare, setAutoStartup, setBatchingStrategy, setConsumeDelay, setConsumerArguments, setConsumerTagStrategy, setDeBatchingEnabled, setDefaultRequeueRejected, setErrorHandler, setErrorHandlerLoggerName, setExclusiveConsumerExceptionLogger, setExposeListenerChannel, setFailedDeclarationRetryInterval, setForceCloseChannel, setGlobalQos, setIdleEventInterval, setjavaLangErrorHandler, setLookupKeyQualifier, setMessageAckListener, setMessageListener, setMessagePropertiesConverter, setMismatchedQueuesFatal, setNoLocal, setNotRunning, setObservationConvention, setPhase, setPossibleAuthenticationFailureFatal, setPrefetchCount, setQueues, setRecoveryBackOff, setRecoveryInterval, setShutdownTimeout, setStatefulRetryFatalWithNullMessageId, setTaskExecutor, setTransactionAttribute, setTransactionManager, setupMessageListener, shutdown, start, stop, updateLastReceive, validateConfiguration, wrapToListenerExecutionFailedExceptionIfNeeded
Methods inherited from class org.springframework.amqp.rabbit.listener.ObservableListenerContainer
checkMicrometer, checkObservation, getApplicationContext, getBeanName, getListenerId, getMicrometerHolder, setApplicationContext, setBeanName, setListenerId, setMicrometerEnabled, setMicrometerTags, setObservationEnabled
Methods inherited from class org.springframework.amqp.rabbit.connection.RabbitAccessor
convertRabbitAccessException, createConnection, getChannel, getConnection, getObservationRegistry, getTransactionalResourceHolder, isChannelTransacted, obtainObservationRegistry, setChannelTransacted, setConnectionFactory
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Methods inherited from interface org.springframework.amqp.rabbit.listener.MessageListenerContainer
isConsumerBatchEnabled
Methods inherited from interface org.springframework.context.SmartLifecycle
stop
-
Field Details
-
consumers
protected final List<org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer.SimpleConsumer> consumers
-
-
Constructor Details
-
DirectMessageListenerContainer
public DirectMessageListenerContainer()Create an instance;RabbitAccessor.setConnectionFactory(ConnectionFactory)
must be called before starting. -
DirectMessageListenerContainer
Create an instance with the provided connection factory.- Parameters:
connectionFactory
- the connection factory.
-
-
Method Details
-
setConsumersPerQueue
public void setConsumersPerQueue(int consumersPerQueue) Each queue runs in its own consumer; set this property to create multiple consumers for each queue. If the container is already running, the number of consumers per queue will be adjusted up or down as necessary.- Parameters:
consumersPerQueue
- the consumers per queue.
-
setExclusive
public final void setExclusive(boolean exclusive) Set to true for an exclusive consumer - if true, theconsumers per queue
must be 1.- Overrides:
setExclusive
in classAbstractMessageListenerContainer
- Parameters:
exclusive
- true for an exclusive consumer.
-
setTaskScheduler
Set the task scheduler to use for the task that monitors idle containers and failed consumers.- Parameters:
taskScheduler
- the scheduler.
-
setMonitorInterval
public void setMonitorInterval(long monitorInterval) Set how often to run a task to check for failed consumers and idle containers.- Parameters:
monitorInterval
- the interval; default 10000 but it will be adjusted down to the smallest of this,idleEventInterval
/ 2 (if configured) orfailedDeclarationRetryInterval
.
-
setQueueNames
Description copied from class:AbstractMessageListenerContainer
Set the name of the queue(s) to receive messages from.- Specified by:
setQueueNames
in interfaceMessageListenerContainer
- Overrides:
setQueueNames
in classAbstractMessageListenerContainer
- Parameters:
queueName
- the desired queueName(s) (can not benull
)
-
setMissingQueuesFatal
public final void setMissingQueuesFatal(boolean missingQueuesFatal) If all of the configured queue(s) are not available on the broker, this setting determines whether the condition is fatal. When true, and the queues are missing during startup, the context refresh() will fail.When false, the condition is not considered fatal and the container will continue to attempt to start the consumers.
Defaults to false for this container.
- Overrides:
setMissingQueuesFatal
in classAbstractMessageListenerContainer
- Parameters:
missingQueuesFatal
- the missingQueuesFatal to set.- See Also:
-
setMessagesPerAck
public void setMessagesPerAck(int messagesPerAck) Set the number of messages to receive before acknowledging (success). A failed message will short-circuit this counter.- Parameters:
messagesPerAck
- the number of messages.- See Also:
-
setAckTimeout
public void setAckTimeout(long ackTimeout) An approximate timeout; whenmessagesPerAck
is greater than 1, and this time elapses since the last ack, the pending acks will be sent either when the next message arrives, or a short time later if no additional messages arrive. In that case, the actual time depends on themonitorInterval
.- Parameters:
ackTimeout
- the timeout in milliseconds (default 20000);- See Also:
-
addQueueNames
Description copied from class:AbstractMessageListenerContainer
Add queue(s) to this container's list of queues.- Overrides:
addQueueNames
in classAbstractMessageListenerContainer
- Parameters:
queueNames
- The queue(s) to add.
-
addQueues
Description copied from class:AbstractMessageListenerContainer
Add queue(s) to this container's list of queues.- Overrides:
addQueues
in classAbstractMessageListenerContainer
- Parameters:
queues
- The queue(s) to add.
-
removeQueueNames
Description copied from class:AbstractMessageListenerContainer
Remove queue(s) from this container's list of queues.- Overrides:
removeQueueNames
in classAbstractMessageListenerContainer
- Parameters:
queueNames
- The queue(s) to remove.- Returns:
- the boolean result of removal on the target
queueNames
List.
-
removeQueues
Description copied from class:AbstractMessageListenerContainer
Remove queue(s) from this container's list of queues.- Overrides:
removeQueues
in classAbstractMessageListenerContainer
- Parameters:
queues
- The queue(s) to remove.- Returns:
- the boolean result of removal on the target
queueNames
List.
-
findIdleConsumer
protected int findIdleConsumer()When adjusting down, return a consumer that can be canceled. Called while synchronized on consumersMonitor.- Returns:
- the consumer index or -1 if non idle.
- Since:
- 2.0.6
-
doInitialize
protected void doInitialize()Description copied from class:AbstractMessageListenerContainer
Register any invokers within this container.Subclasses need to implement this method for their specific invoker management process.
- Specified by:
doInitialize
in classAbstractMessageListenerContainer
-
doStart
protected void doStart()Description copied from class:AbstractMessageListenerContainer
Start this container, and notify all invoker tasks.- Overrides:
doStart
in classAbstractMessageListenerContainer
-
doStop
protected void doStop()Description copied from class:AbstractMessageListenerContainer
This method is invoked when the container is stopping.- Overrides:
doStop
in classAbstractMessageListenerContainer
-
actualStart
protected void actualStart() -
checkConnect
protected void checkConnect() -
doRedeclareElementsIfNecessary
protected void doRedeclareElementsIfNecessary() -
processMonitorTask
protected void processMonitorTask()Subclasses can override this to take additional actions when the monitor task runs. -
doShutdown
protected void doShutdown()Description copied from class:AbstractMessageListenerContainer
Close the registered invokers.Subclasses need to implement this method for their specific invoker management process.
A shared Rabbit Connection, if any, will automatically be closed afterwards.
- Specified by:
doShutdown
in classAbstractMessageListenerContainer
- See Also:
-
consumerRemoved
protected void consumerRemoved(org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer.SimpleConsumer consumer) Called whenever a consumer is removed.- Parameters:
consumer
- the consumer.
-