在运行时向兔子侦听器动态添加队列

Dynamic addition of queues to a rabbit listener at runtime

我有一个项目,我们将在 rabbit 中有数百(可能是数千)个队列,并且每个队列都需要由一个消费者池使用。

在 rabbit 中(使用 spring-amqp),你有 rabbitlistener 注释,它允许我静态分配这个特定消费者将处理的队列。

我的问题是 - 对于 rabbit 和 spring,有没有一种干净的方法让我获取一部分队列(比如说以 a-c 开头的队列),然后监听任何创建的队列而消费者是 运行.

示例(开始时):

而消费者是 运行:

这是我目前拥有的(非常简单的)代码:

    @Component
    public class MessageConsumer {

        public MessageConsumer() {
            // ideally grab a section of queues here, initialize a parameter and give to the rabbitlistener annotation
        }

        @RabbitListener(queues= {"ant-queue", "apple-queue", "cat-queue"})
        public void processQueues(String messageAsJson) {
            < how do I update the queues declared in rabbit listener above ? >
        }
    }

编辑:

我应该补充一点——我已经浏览了我在网上找到的 spring amqp 文档,但我没有发现除静态(硬编码或通过属性)声明队列之外的任何内容

  • 注入(@Autowired 或其他)RabbitListenerEndpointRegistry.

  • 获取对侦听器容器的引用(使用注解上的 id 属性为其提供已知 id)(registry.getListenerContainer(id)).

  • 将容器转换为 AbstractMessageListenerContainer 并调用 addQueues()addQueueNames()

请注意,动态添加队列时使用 DirectMessageListenerContainer 效率更高;使用 SimpleMessageListenerContainer 消费者被停止并重新启动。使用直接容器,每个队列都有自己的消费者。

参见 Choosing a container