Containers and Broker-Named queues

虽然最好将 AnonymousQueue 实例用作自动删除队列,但从 2.1 版本开始,你可以在侦听器容器中使用具有侦听器容器的代理队列名称。以下示例演示如何执行此操作:

While it is preferable to use AnonymousQueue instances as auto-delete queues, starting with version 2.1, you can use broker named queues with listener containers. The following example shows how to do so:

@Bean
public Queue queue() {
    return new Queue("", false, true, true);
}

@Bean
public SimpleMessageListenerContainer container() {
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(cf());
    container.setQueues(queue());
    container.setMessageListener(m -> {
        ...
    });
    container.setMissingQueuesFatal(false);
    return container;
}

请注意名称为空的 String。当 RabbitAdmin 声明队列时,它会使用代理返回的名称更新 Queue.actualName 属性。配置容器时必须使用 setQueues() 使此方法正常工作,以便容器可以在运行时访问声明的名称。仅设置名称是不够的。

Notice the empty String for the name. When the RabbitAdmin declares queues, it updates the Queue.actualName property with the name returned by the broker. You must use setQueues() when you configure the container for this to work, so that the container can access the declared name at runtime. Just setting the names is insufficient.

在容器运行时,您无法向容器添加代理命名的队列。

You cannot add broker-named queues to the containers while they are running.

当连接被重置并建立新连接时,新队列会获得一个新名称。由于容器重新启动和重新声明队列之间存在竞争条件,因此必须将容器的 missingQueuesFatal 属性设置为 false,因为容器最初可能会尝试重新连接到旧队列。

When a connection is reset and a new one is established, the new queue gets a new name. Since there is a race condition between the container restarting and the queue being re-declared, it is important to set the container’s missingQueuesFatal property to false, since the container is likely to initially try to reconnect to the old queue.