Class DirectMessageListenerContainer
java.lang.Object
org.springframework.amqp.rabbit.connection.RabbitAccessor
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
-
Nested Class Summary
Nested classes/interfaces inherited from class org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer
AbstractMessageListenerContainer.JavaLangErrorHandler, AbstractMessageListenerContainer.SharedConnectionNotInitializedException, AbstractMessageListenerContainer.WrappedTransactionException -
Field Summary
FieldsModifier 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_TIMEOUTFields inherited from class org.springframework.amqp.rabbit.connection.RabbitAccessor
loggerFields inherited from interface org.springframework.context.SmartLifecycle
DEFAULT_PHASE -
Constructor Summary
ConstructorsConstructorDescriptionCreate 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 voidvoidaddQueueNames(String... queueNames) Add queue(s) to this container's list of queues.voidAdd queue(s) to this container's list of queues.protected voidprotected voidconsumerRemoved(org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer.SimpleConsumer consumer) Called whenever a consumer is removed.protected voidRegister any invokers within this container.protected voidprotected voidClose the registered invokers.protected voiddoStart()Start this container, and notify all invoker tasks.protected voiddoStop()This method is invoked when the container is stopping.protected intWhen adjusting down, return a consumer that can be canceled.protected voidSubclasses can override this to take additional actions when the monitor task runs.booleanremoveQueueNames(String... queueNames) Remove queue(s) from this container's list of queues.booleanremoveQueues(Queue... queues) Remove queue(s) from this container's list of queues.voidsetAckTimeout(long ackTimeout) An approximate timeout; whenmessagesPerAckis 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.voidsetConsumersPerQueue(int consumersPerQueue) Each queue runs in its own consumer; set this property to create multiple consumers for each queue.final voidsetExclusive(boolean exclusive) Set to true for an exclusive consumer - if true, theconsumers per queuemust be 1.voidsetMessagesPerAck(int messagesPerAck) Set the number of messages to receive before acknowledging (success).final voidsetMissingQueuesFatal(boolean missingQueuesFatal) If all of the configured queue(s) are not available on the broker, this setting determines whether the condition is fatal.voidsetMonitorInterval(long monitorInterval) Set how often to run a task to check for failed consumers and idle containers.voidsetQueueNames(String... queueName) Set the name of the queue(s) to receive messages from.voidsetTaskScheduler(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, getAcknowledgeMode, getAdviceChain, getAfterReceivePostProcessors, getAmqpAdmin, getApplicationContext, getApplicationEventPublisher, getBatchingStrategy, getBeanName, getConnectionFactory, getConsumeDelay, getConsumerArguments, getConsumerTagStrategy, getExclusiveConsumerExceptionLogger, getFailedDeclarationRetryInterval, getIdleEventInterval, getJavaLangErrorHandler, getLastReceive, getListenerId, 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, setApplicationContext, setApplicationEventPublisher, setAutoDeclare, setAutoStartup, setBatchingStrategy, setBeanName, setConsumeDelay, setConsumerArguments, setConsumerTagStrategy, setDeBatchingEnabled, setDefaultRequeueRejected, setErrorHandler, setErrorHandlerLoggerName, setExclusiveConsumerExceptionLogger, setExposeListenerChannel, setFailedDeclarationRetryInterval, setForceCloseChannel, setGlobalQos, setIdleEventInterval, setjavaLangErrorHandler, setListenerId, setLookupKeyQualifier, setMessageListener, setMessagePropertiesConverter, setMicrometerEnabled, setMicrometerTags, setMismatchedQueuesFatal, setNoLocal, setNotRunning, setPhase, setPossibleAuthenticationFailureFatal, setPrefetchCount, setQueues, setRecoveryBackOff, setRecoveryInterval, setShutdownTimeout, setStatefulRetryFatalWithNullMessageId, setTaskExecutor, setTransactionAttribute, setTransactionManager, setupMessageListener, shutdown, start, stop, updateLastReceive, validateConfiguration, wrapToListenerExecutionFailedExceptionIfNeededMethods inherited from class org.springframework.amqp.rabbit.connection.RabbitAccessor
convertRabbitAccessException, createConnection, getChannel, getConnection, getTransactionalResourceHolder, isChannelTransacted, setChannelTransacted, setConnectionFactoryMethods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface org.springframework.amqp.rabbit.listener.MessageListenerContainer
isConsumerBatchEnabledMethods 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 queuemust be 1.- Overrides:
setExclusivein 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:AbstractMessageListenerContainerSet the name of the queue(s) to receive messages from.- Specified by:
setQueueNamesin interfaceMessageListenerContainer- Overrides:
setQueueNamesin 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:
setMissingQueuesFatalin 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; whenmessagesPerAckis 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:AbstractMessageListenerContainerAdd queue(s) to this container's list of queues.- Overrides:
addQueueNamesin classAbstractMessageListenerContainer- Parameters:
queueNames- The queue(s) to add.
-
addQueues
Description copied from class:AbstractMessageListenerContainerAdd queue(s) to this container's list of queues.- Overrides:
addQueuesin classAbstractMessageListenerContainer- Parameters:
queues- The queue(s) to add.
-
removeQueueNames
Description copied from class:AbstractMessageListenerContainerRemove queue(s) from this container's list of queues.- Overrides:
removeQueueNamesin classAbstractMessageListenerContainer- Parameters:
queueNames- The queue(s) to remove.- Returns:
- the boolean result of removal on the target
queueNamesList.
-
removeQueues
Description copied from class:AbstractMessageListenerContainerRemove queue(s) from this container's list of queues.- Overrides:
removeQueuesin classAbstractMessageListenerContainer- Parameters:
queues- The queue(s) to remove.- Returns:
- the boolean result of removal on the target
queueNamesList.
-
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:AbstractMessageListenerContainerRegister any invokers within this container.Subclasses need to implement this method for their specific invoker management process.
- Specified by:
doInitializein classAbstractMessageListenerContainer
-
doStart
protected void doStart()Description copied from class:AbstractMessageListenerContainerStart this container, and notify all invoker tasks.- Overrides:
doStartin classAbstractMessageListenerContainer
-
doStop
protected void doStop()Description copied from class:AbstractMessageListenerContainerThis method is invoked when the container is stopping.- Overrides:
doStopin 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:AbstractMessageListenerContainerClose 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:
doShutdownin 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.
-