[英]AMQP async listener starts listening to message only after an event happens
I currently have an AMQP async listener that is listening to messages on a queue automatically. 我目前有一个AMQP异步侦听器,它可以自动侦听队列中的消息。
However, my requirement is that I shouldn't have this listener listening to messages until a certain event has happened. 但是,我的要求是在某个事件发生之前,我不应该让此侦听器侦听消息。 For event, I am thinking of using @EventListener annotation.
对于事件,我正在考虑使用@EventListener批注。
The async listener looks like this: 异步侦听器如下所示:
@Configuration
public class ExampleAmqpConfiguration {
@Bean
public SimpleMessageListenerContainer messageListenerContainer() {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(rabbitConnectionFactory());
container.setQueueName("some.queue");
container.setMessageListener(exampleListener());
return container;
}
@Bean
public ConnectionFactory rabbitConnectionFactory() {
CachingConnectionFactory connectionFactory =
new CachingConnectionFactory("localhost");
connectionFactory.setUsername("guest");
connectionFactory.setPassword("guest");
return connectionFactory;
}
@Bean
public MessageListener exampleListener() {
return new MessageListener() {
public void onMessage(Message message) {
System.out.println("received: " + message);
}
};
}
}
I was thinking of adding the @EventListener to the method messageListenerContainer() so it looks like this: 我正在考虑将@EventListener添加到方法messageListenerContainer()中,因此它看起来像这样:
@Bean
@EventListener
public SimpleMessageListenerContainer messageListenerContainer(CustomeEvent customEvent) {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(rabbitConnectionFactory());
container.setQueueName("some.queue");
container.setMessageListener(exampleListener());
return container;
}
However, the messageListenerContainer() bean just seems to run at start up, regardless of the EventListener. 但是,无论事件侦听器如何,messageListenerContainer()bean似乎在启动时都在运行。
What is proper way for this async listner to listen to messages, only after a CustomEvent happens? 仅当CustomEvent发生后,此异步列表器才能侦听消息的正确方法是什么?
Thanks. 谢谢。
Set the containers autoStartup
property to false
. 将容器的
autoStartup
属性设置为false
。
In your @EventListener
, auto wire the container and start()
it. 在
@EventListener
,自动连接容器并对其进行start()
。
EDIT 编辑
public class MyEventListener {
@Autowired
private SimpleMessageListenerContainer container;
@EventListener
public void someEvent(MyEvent event) {
this.container.start();
}
}
and 和
@Bean
public MyEventListener listener() {
return new EventListener();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.