本文介绍了如何实现Spring AMQP Listener Container中的并发性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的容器XML配置:

<rabbit:listener-container
        connection-factory="myConnectionFactory"
        acknowledge="none"
        concurrency="10"
        requeue-rejected="false">
    <rabbit:listener ref="myListener" queues="myQueue"/>
</rabbit:listener-container>

myListener 只是一个类

@Component("myListener")
public class MyListener implements MessageListener {
    @Autowired
    SomeDependency dependency;
    ....
}

我已指定我的XML中的concurrency =10。这意味着什么完全

I've specified concurrency="10" in my XML. What does this mean exactly?

我发现。它们没有那么有用说明:

I've found some docs. They are not that helpful stating:






我感兴趣的是 MyListener 必须是线程安全的,即


What I am interested in is whether MyListener has to be thread safe i.e.


  • 是否创建了许多实例或许多线程使用了单个实例?

  • 我可以访问没有同步的实例字段吗?

  • SomeDependency依赖实例化一次或者每个线程/实例?

  • 依赖需要线程安全吗?

  • are there many instances created or single instance used by many threads?
  • can I access instance fields w/o synchronization?
  • is SomeDependency dependency instantiated once or for each thread/instance?
  • does dependency need to be thread safe?

推荐答案

是的,要使用并发性,您的监听器必须是线程安全的。每个容器有一个侦听器实例。但是,< rabbit:listener-container /> namespace元素实际上只是添加共享属性的便利,每个侦听器元素都有自己的容器。

Yes, to use concurrency, your listener has to be thread-safe. There is one listener instance per container. However, the <rabbit:listener-container/> namespace element is actually just a convenience for adding "shared" attributes, each listener element gets its own container.

通常最好使用无状态对象(没有写入的字段),但这并不总是可行。

It's generally best to use stateless objects (no fields that are written to), but that's not always possible.

如果你的监听器不是线程安全的,你可以使用...

If your listener is not thread-safe, you can use...

<rabbit:listener-container
    connection-factory="myConnectionFactory"
    acknowledge="none"
    requeue-rejected="false">
    <rabbit:listener ref="myListener" queues="myQueue"/>
    <rabbit:listener ref="myListener" queues="myQueue"/>
    <rabbit:listener ref="myListener" queues="myQueue"/>
    <rabbit:listener ref="myListener" queues="myQueue"/>
    ...
</rabbit:listener-container>

...并添加 @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)。然后,您将为每个侦听器获取一个容器,并将为每个侦听器注入一个不同的侦听器实例。

...and add @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE). You will then get a container for each listener and a different instance of the listener will be injected into each.

您还需要任何非线程安全的原型范围注入侦听器的依赖项。

You will also need prototype scope for any non-thread-safe dependencies injected into the listener.

这篇关于如何实现Spring AMQP Listener Container中的并发性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 03:46