Spring Cloud實戰小貼士:健康檢查

https://mp.weixin.qq.com/s/NB9KVhtWj1UaepqHKZ4gKQredis

今天在博客的交流區收到一條不錯的問題,拿出來給你們分享一下。具體問題以下:

由於項目裏面用到了redis集羣,但並非用spring boot的配置方式,啓動後項目健康檢查總是檢查redis的時候狀態爲down,致使註冊到eureka後項目狀態也是down。spring

"redis": { 
    "status": "DOWN", 
    "error": "org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool" 
}

問下能不能設置spring boot不檢查 redis的健康狀態。微信

問題原帖:http://qa.didispace.com/?/question/7
歡迎你們來此交流ide

緣由分析

如提問者所述,因爲在Spring Boot項目中引用了Redis模塊,因此Spring Boot Actuator會對其進行健康檢查,正常狀況下不會出現問題,可是因爲採用了其餘配置方式,致使redis的鏈接檢查沒有經過。這樣就會致使了Consul或Eureka的HealthCheck認爲該服務是DOWN狀態。ui

那麼redis的健康檢查是如何實現的呢?咱們不妨來看看健康檢查的自動化配置中針對redis的配置源碼:this

@Configuration
@ConditionalOnBean(RedisConnectionFactory.class)
@ConditionalOnEnabledHealthIndicator("redis")
public static class RedisHealthIndicatorConfiguration extends
      CompositeHealthIndicatorConfiguration<RedisHealthIndicator, RedisConnectionFactory> {

   @Autowired
   private Map<String, RedisConnectionFactory> redisConnectionFactories;

   @Bean
   @ConditionalOnMissingBean(name = "redisHealthIndicator")
   public HealthIndicator redisHealthIndicator() {
      return createHealthIndicator(this.redisConnectionFactories);
   }

}

以上內容取自:
org.springframework.boot.actuate.autoconfigure.HealthIndicatorAutoConfiguration類。spa

從自動化配置中咱們能夠看到,會自動加載一個針對redis的HealthIndicator實現,而且該Bean命名爲redisHealthIndicator。code

解決方法

經過上面的分析,咱們已經知道了是哪一個Bean致使了服務實例的健康檢查不經過,那麼如何解決該問題的方法也就立刻能想到了:咱們只須要再實現一個redis的HealthIndicator實現來替代原先默認的檢查邏輯。好比:blog

@Component
public class RedisHealthIndicator implements HealthIndicator {

    @Override
    public Health health() {
        return Health.up().build();
    }
}

上面經過實現HealthIndicator接口中的health方法,直接返回了up狀態。經過@Component註解,讓Spring Boot掃描到該類就能自動的進行加載,並覆蓋原來的redis健康檢查實現。固然,這裏的實現並很差,由於它只是爲了讓健康檢查能夠經過,可是並無作真正的健康檢查。如提問者所說,採用了其餘配置訪問,那麼正確的作法就是在health方法中實現針對其餘配置的內容進行健康檢查。接口

注意:這裏隱含了一個實現命名的問題,因爲默認的bean名稱會使用redisHealthIndicator,因此這裏的定義能夠替換默認的實現,由於它的名字與@ConditionalOnMissingBean(name = "redisHealthIndicator")中的命名一致。可是若是您自定義的實現類並不是叫RedisHealthIndicator,它的默認名稱與自動化配置的名稱是不匹配的,那麼就不會替換,這個時候須要在@Component註解中指定該Bean的名稱爲redisHealthIndicator

SpringCloud新書推薦

Spring Cloud實戰小貼士:健康檢查
Spring Cloud實戰小貼士:健康檢查
版權聲明

本文采用 CC BY 3.0 CN協議 進行許可。 可自由轉載、引用,但需署名做者且註明文章出處。如轉載至微信公衆號,請在文末添加做者公衆號二維碼。
長按指紋
一鍵關注
Spring Cloud實戰小貼士:健康檢查
Spring Cloud實戰小貼士:健康檢查

相關文章
相關標籤/搜索