首页 > 解决方案 > RabbitTemplate 错误:ApplicationContext 已关闭,ConnectionFactory 无法再创建连接

问题描述

我正在使用Springboot 1.5.3amqp-client 4.0.2

我有一个大部分时间都可以正常工作的制作人,但有时我会收到以下错误:

java.lang.IllegalStateException: The ApplicationContext is closed and the ConnectionFactory can no longer create connections.
    at org.springframework.amqp.rabbit.connection.CachingConnectionFactory.createConnection(CachingConnectionFactory.java:561) ~[spring-rabbit-1.7.2.RELEASE.jar!/:na]
    at org.springframework.amqp.rabbit.core.RabbitTemplate.doExecute(RabbitTemplate.java:1430) ~[spring-rabbit-1.7.2.RELEASE.jar!/:na]
    at org.springframework.amqp.rabbit.core.RabbitTemplate.execute(RabbitTemplate.java:1411) ~[spring-rabbit-1.7.2.RELEASE.jar!/:na]
    at org.springframework.amqp.rabbit.core.RabbitTemplate.send(RabbitTemplate.java:712) ~[spring-rabbit-1.7.2.RELEASE.jar!/:na]
    at org.springframework.amqp.rabbit.core.RabbitTemplate.convertAndSend(RabbitTemplate.java:813) ~[spring-rabbit-1.7.2.RELEASE.jar!/:na]
    at org.springframework.amqp.rabbit.core.RabbitTemplate.convertAndSend(RabbitTemplate.java:803) ~[spring-rabbit-1.7.2.RELEASE.jar!/:na]  
    at com.my.amqp.producer.MyProducer.produce(MyProducer.java:16) ~[classes!/:0.6.0-SNAPSHOT]

这是从 producer(...) 方法调用 RabbitTemplate.convertAndSend 的类:

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

public class MyProducer {
    @Value("${rabbit.exchange.in.name}")
    public String exchangeNameIn;

    @Autowired
    RabbitTemplate rabbitTemplate;

    public void produce(String messageToBeDelivered, String routingKey, int messageDelay) throws Exception {
        if (messageDelay > 0) {
            rabbitTemplate.convertAndSend(exchangeNameIn, routingKey, messageToBeDelivered,
                m -> {
                    m.getMessageProperties().setCorrelationId("test-id".getBytes());
                    m.getMessageProperties().setHeader("x-delay", messageDelay);
                    return m;
                });
        } else {
            rabbitTemplate.convertAndSend(exchangeNameIn, routingKey, messageToBeDelivered,
                m -> {
                    m.getMessageProperties().setCorrelationId("test-id".getBytes());
                    return m;
                });
        }
    }
}

与rabbitmq相关的属性:

spring.rabbitmq.listener.concurrency=5
spring.rabbitmq.listener.max-concurrency=5

标签: spring-bootrabbitmqspring-rabbit

解决方案


Boot 1.5.x 多年来一直不受支持。

甚至不再支持 Spring AMQP 1.7.x(和 spring framework 4.x)。

有关支持的版本,请参见此处。

也就是说,该错误仅表示您的应用程序在应用程序上下文关闭后尝试重新连接到 RabbitMQ。


推荐阅读