如何使用非线程安全的 MessageListener 实现并发 [英] How to Achieve Concurrency With a Non-Thread-Safe MessageListener
问题描述
这个问题的答案解释了如何当侦听器不是线程安全的时,在 Spring AMQP 中使用带有
的原型范围.
The answer to this question explains how to use prototype scope with <rabbit:listener-container/>
in Spring AMQP when the listener is not thread-safe.
另一位用户(在评论中)询问如何仅使用 Java 配置来配置相同的环境.
Another user asked (in a comment) how to configure the same environment using only Java Configuration.
推荐答案
对于侦听器使用无状态 bean 通常是最佳实践,但如果不可能,则配置 @Prototype
范围侦听器(和多个容器) 仅使用 Java 配置,您可以使用:
It's generally best practice to use stateless beans for listeners but when that's not possible, to configure @Prototype
scope listener (and multiple containers) using only Java Configuration, you can use:
@Bean
public SimpleMessageListenerContainer container1() {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory());
container.setQueueNames("test.mismatch");
container.setMessageListener(new MessageListenerAdapter(listener()));
container.setMismatchedQueuesFatal(true);
return container;
}
...
@Bean
public SimpleMessageListenerContainer containerN() {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory());
container.setQueueNames("test.mismatch");
container.setMessageListener(new MessageListenerAdapter(listener()));
container.setMismatchedQueuesFatal(true);
return container;
}
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public MyNotThreadSafeListener listener() {
return new MyNotThreadSafeListener();
}
请记住,注入到 MyNotThreadSafeListener
中的任何依赖项也必须是原型 bean.
Remember that any dependencies injected into MyNotThreadSafeListener
must also be prototype beans.
最重要的是无状态 bean 是最好的.
Bottom line is stateless beans are best.
这篇关于如何使用非线程安全的 MessageListener 实现并发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!