在 Spring AMQP 中关闭与 SimpleMessageListenerContainer 相关的连接

Close connections related to SimpleMessageListenerContainer in Spring AMQP

我目前正在开发基于事件的异步 AMQP 消息侦听器,如下所示:

@Configuration
public class ExampleAmqpConfiguration {

    @Bean(name = "container")
    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);
            }
        };
    }
}

我已将容器 bean 的自动启动 属性 更改为 false。我已经将这个 bean 自动连接到一个事件列表器,该事件列表器在 StartEvent 发生时启动容器:

@EventListener
public void startContainer(StartEvent startEvent) {
     this.container.start();
}

同时,我也将bean自动连接到另一个停止容器并关闭容器的事件,希望容器停止并且不会有挥之不去的连接:

@EventListener
public void endContainer(EndEvent endEvent) {
     this.container.stop();
     this.container.shutdown();
}

然而,在 EndEvent 之后,我在我的 RabbitMQ 管理控制台中发现所有通道都已关闭,但仍然存在挥之不去的连接。

这是否意味着 shutdown() 不是用于删除延迟连接的正确方法?如果是这样,正确的使用方法是什么?

谢谢。

您需要在 CachingConnectionFactory 上调用 resetConnection() 来关闭连接;正如 class 名称所暗示的那样;连接已缓存。