46.6.2 编写自定义HealthIndicators

你可以注册实现HealthIndicator接口的Spring beans来提供自定义健康信息。你需要实现health()方法,并返回一个Health响应,该响应需要包含一个status和其他用于展示的详情。

  1. import org.springframework.boot.actuate.health.HealthIndicator;
  2. import org.springframework.stereotype.Component;
  3. @Component
  4. public class MyHealth implements HealthIndicator {
  5. @Override
  6. public Health health() {
  7. int errorCode = check(); // perform some specific health check
  8. if (errorCode != 0) {
  9. return Health.down().withDetail("Error Code", errorCode).build();
  10. }
  11. return Health.up().build();
  12. }
  13. }

对于给定HealthIndicator的标识是bean name去掉HealthIndicator后缀剩下的部分。在以上示例中,可以在my的实体中获取健康信息。

除Spring Boot预定义的Status类型,Health也可以返回一个代表新的系统状态的自定义Status。在这种情况下,你需要提供一个HealthAggregator接口的自定义实现,或使用management.health.status.order属性配置默认实现。

例如,假设一个新的,代码为FATALStatus被用于你的一个HealthIndicator实现中。为了配置严重性级别,你需要将以下配置添加到application属性文件中:

  1. management.health.status.order=DOWN, OUT_OF_SERVICE, UNKNOWN, UP

如果使用HTTP访问health端点,你可能想要注册自定义的status,并使用HealthMvcEndpoint进行映射。例如,你可以将FATAL映射为HttpStatus.SERVICE_UNAVAILABLE