天天看點

springcloud stream 報錯 Rabbit health check failed

在使用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(開玩笑的)