Spring Boot Actuator自定義健康檢查教程

健康檢查是Spring Boot Actuator中重要端點之一,可以非常容易查看應用運行至狀態。本文在前文的基礎上介紹如何自定義健康檢查。

1. 概述

本節我們簡單說明下依賴及啟用配置,展示缺省健康信息。首先需要引入依賴:

compile("org.springframework.boot:spring-boot-starter-actuator")

現在通過http://localhost:8080/actuator/health端點進行驗證:

{"status":"UP"}

缺省該端點返回應用中很多組件的匯總健康信息,但可以修改屬性配置展示詳細內容:

management:
  endpoint:
    health:
      show-details: always

現在再次訪問返回結果如下:

{
  "status": "UP",
  "components": {
    "diskSpace": {
      "status": "UP",
      "details": {
        "total": 214748360704,
        "free": 112483500032,
        "threshold": 10485760,
        "exists": true
      }
    },
    "ping": {
      "status": "UP"
    }
  }
}

查看DiskSpaceHealthIndicatorProperties文件的源碼:

@ConfigurationProperties(prefix = "management.health.diskspace")
public class DiskSpaceHealthIndicatorProperties {
 /**
  * Path used to compute the available disk space.
  */
 private File path = new File(".");
 /**
  * Minimum disk space that should be available.
  */
 private DataSize threshold = DataSize.ofMegabytes(10);
 public File getPath() {
  return this.path;
 }
 public void setPath(File path) {
  this.path = path;
 }
 public DataSize getThreshold() {
  return this.threshold;
 }
 public void setThreshold(DataSize threshold) {
  Assert.isTrue(!threshold.isNegative(), "threshold must be greater than or equal to 0");
  this.threshold = threshold;
 }
}

上面結果顯示當前項目啟動的路徑 . ,報警值 為10M ,這些屬性都可以通過配置進行修改。

2. 預定義健康指標

上面Json響應顯示“ping”和“diskSpace”檢查。這些檢查也稱為健康指標,如果應用引用瞭數據源,Spring會增加db健康指標;同時“diskSpace”是缺省配置。

Spring Boot包括很多預定義的健康指標,下面列出其中一部分:

  • DataSourceHealthIndicator
  • MongoHealthIndicator
  • Neo4jHealthIndicator
  • CassandraHealthIndicator
  • RedisHealthIndicator
  • CassandraHealthIndicator
  • RabbitHealthIndicator
  • CouchbaseHealthIndicator
  • DiskSpaceHealthIndicator (見上面示例)
  • ElasticsearchHealthIndicator
  • InfluxDbHealthIndicator
  • JmsHealthIndicator
  • MailHealthIndicator
  • SolrHealthIndicator

如果在Spring Boot應用中使用Mongo或Solr等,則Spring Boot會自動增加相應健康指標。

3. 自定義健康指標

Spring Boot提供瞭一捆預定義健康指標,但並沒有阻止你增加自己的健康指標。一般有兩種自定義類型檢查:

單個健康指標組件和組合健康指標組件。

3.1 自定義單個指標組件

自定義需要實現HealthIndicator接口並重新health()方法,同時增加@Component註解。假設示例應用程序與服務A(啟動)和服務B(關閉)通信。如果任一服務宕機,應用程序將被視為宕機。因此,我們將寫入兩個運行狀況指標。

@Component
public class ServiceAHealthIndicator implements HealthIndicator {
    private final String message_key = "Service A";
    @Override
    public Health health() {
        if (!isRunningServiceA()) {
            return Health.down().withDetail(message_key, "Not Available").build();
        }
        return Health.up().withDetail(message_key, "Available").build();
    }
    private Boolean isRunningServiceA() {
        Boolean isRunning = true;
        // Logic Skipped
        return isRunning;
    }
}
@Component
public class ServiceBHealthIndicator implements HealthIndicator {
    private final String message_key = "Service B";
    @Override
    public Health health() {
        if (!isRunningServiceB()) {
            return Health.down().withDetail(message_key, "Not Available").build();
        }
        return Health.up().withDetail(message_key, "Available").build();
    }
    private Boolean isRunningServiceB() {
        Boolean isRunning = false;
        // Logic Skipped
        return isRunning;
    }
}

現在,我們看到健康監控響應中增加的指標。ServerA狀態是UP,ServiceB是DOWN,因此整個監控檢測狀態為DOWN.

{
  "status": "DOWN",
  "components": {
    "diskSpace": {
      "status": "UP",
      "details": {
        "total": 214748360704,
        "free": 112483229696,
        "threshold": 10485760,
        "exists": true
      }
    },
    "ping": {
      "status": "UP"
    },
    "serviceA": {
      "status": "UP",
      "details": {
        "Service A": "Available"
      }
    },
    "serviceB": {
      "status": "DOWN",
      "details": {
        "Service B": "Not Available"
      }
    }
  }
}

3.2 自定義組合健康檢查

前面示例很容易查看各個指標各自的狀態。但有時需要基於幾個指標查看資源的狀態,則需要使用 HealthContributor ,該接口沒有定義方法,僅用於標記。如果一個服務有另外兩個動作組合進行實現,隻有兩者同時工作該服務狀態才算正常。最後使用 CompositeHealthContributors組合多個指標:

public class ServiceAHealthIndicator 
    implements HealthIndicator, HealthContributor {
...
}

下面定義組合健康檢查指標:

@Component("UserServiceAPI")
public class UserServiceAPIHealthContributor 
    implements CompositeHealthContributor {
  
  private Map<String, HealthContributor> 
          contributors = new LinkedHashMap<>();
  @Autowired
  public UserServiceAPIHealthContributor(
      ServiceAHealthIndicator serviceAHealthIndicator, ServiceBHealthIndicator serviceBHealthIndicator) {
  
    contributors.put("serverA",  serviceAHealthIndicator);
    contributors.put("serverB", serviceBHealthIndicator);
  }
  /**
   *  return list of health contributors
   */
  @Override
  public Iterator<NamedContributor<HealthContributor>> iterator() {
    return contributors.entrySet().stream()
       .map((entry) -> NamedContributor.of(entry.getKey(), entry.getValue())).iterator();
  }
  
  @Override
  public HealthContributor getContributor(String name) {
    return contributors.get(name);
  }
}

現在我們使用serverA和serverB組合新的檢查UserServiceAPI。

4. 總結

本文我們學習瞭Spring Boot健康指標及相關配置、以及預定義的健康指標,同時介紹瞭如何自定義健康指標。

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: