在使用SpringCloud Stream集成RabbitMQ的时候报了这个错:
一开始我被<code>Connection refused: connect</code>迷惑了,查了半天为啥连不上RabbitMQ。翻源码、debug发现连接的地址没错,看RabbitMQ控制台也有connection和channel,说明实际还是连上了。
那为啥还报这个错呢?
仔细一看抛异常的是<code>RabbitHealthIndicator</code>,原来是SpringBoot Actuator想要监控RabbitMQ的连接状态,但是连接被拒绝。
我的配置文件如下:
就是因为我使用了<code>spring.cloud.stream.binders.*.environment</code>属性配置rabbitMQ的相关信息,但是没配置<code>spring.rabbitmq</code>。这就导致自动配置检测到类路径下有rabbit相关的类,就配置了rabbit相关的Bean。
其中<code>org.springframework.boot.actuate.amqp.RabbitHealthIndicator</code>负责监控rabbit的连接状况,通过下面这个配置类自动配置。
但是没有检测到<code>spring.rabbitmq</code>相关的配置,就使用了默认的配置,尝试连接<code>localhost:5672</code>,然后就出现了<code>org.springframework.amqp.AmqpConnectException: java.net.ConnectException: Connection refused: connect</code>。
问题的关键在于,<code>spring.cloud.stream.binders.*.environment</code>为每个binder创建了单独的上下文环境,跟application context是完全隔离的。所以,仅仅配置了<code>spring.cloud.stream.binders.*.environment</code>,使Actuator从application context中没有找到rabbitmq的配置。
参考Spring Cloud Stream and RabbitMQ health check
<code>RabbitHealthIndicator</code>需要<code>spring.rabbitmq</code>的配置,就给他:将<code>spring.cloud.stream.binders.*.environment</code>里面的配置拿到<code>spring.rabbitmq</code>中。
禁用<code>RabbitHealthIndicator</code>。上面提到的配置类上还有一个<code>@ConditionalOnEnabledHealthIndicator("rabbit")</code>,意思就是:配置<code>management.health.rabbit.enabled</code>为true的时候生效。禁用即可解决。
在localhost安装一个RabbitMQ(开玩笑的)