Spring 启动健康检查计划

Spring Boot health check schedule

有没有办法让SpringActuator定期进行健康检查?我在想,也许可以选择在我的 HealthIndicator 自定义实现中使用一些 Runnable,但对我来说,这个想法看起来不太好。 我想检查 Cassandra,如果失败,执行一些紧急操作

您可以定期从某些外部监控系统(如 Nagios)调用 /health 端点,并在响应不是 HTTP 200 时采取适当的措施。如果您对 /health 端点进行经过身份验证的调用,则响应正文包含详细信息失败(未经身份验证的调用只有 HTTP 响应代码)。

Spring 现在的执行器不打算采取任何行动。它仅供 /health 端点使用。

但如果您真的想扩展这个想法并对失败的健康检查采取一些措施,那么请查看 spring-boot actuator 的源代码。

https://github.com/spring-projects/spring-boot/tree/master/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/cassandra

它包含每个健康检查的实现。 您可以轻松地重用它们并编写自己的实现来定期调用每个 HealthIndicator

有关详细信息,请查看 org.springframework.boot.actuate.health.HealthEndpoint 的外观。

你可以定期做同样的事情。

请注意,这可能不是最好的主意。您将严重依赖特定版本执行器的实现细节。更新 Sping Boot 版本后(他们经常发布新版本,由于安全修复和新功能,更新是个好主意)您的自定义逻辑可能无法编译、停止工作或工作不正常。

我通过谷歌搜索发现了这个条目,因为我希望定期 运行 健康检查。正如前面提到的 post,您可以从外部监控系统定期调用健康端点,但假设您想使用千分尺将健康指标发送到外部注册表(如 NewRelic)并且您不想依赖外部 ping。然后你可以像下面这样使用 import org.springframework.boot.actuate.health.HealthEndpoint:

@Configuration
@EnableScheduling
public class HealthMetricsConfiguration {

  private final String GAUGE_NAME = "gaugeName";

  private AtomicInteger gauge;

  private HealthEndpoint healthEndpoint;

  public HealthMetricsConfiguration(MeterRegistry registry, HealthEndpoint healthEndpoint) {
    this.healthEndpoint = healthEndpoint;
    gauge = registry.gauge(GAUGE_NAME, new AtomicInteger());
    gauge.set(getStatusCode(this.healthEndpoint));
  }

  private int getStatusCode(HealthEndpoint healthEndPoint) {
    Status status = healthEndPoint.health().getStatus();
    if(Status.OUT_OF_SERVICE.equals(status)) {
      return 3;
    }else if(Status.DOWN.equals(status)) {
      return 2;
    }else if(Status.UP.equals(status)) {
      return 1;
    }else {
      return 0; //Status.UNKNOWN
    }
  }

  @Scheduled(fixedDelayString = 60000, initialDelayString = 60000)
  public void periodicRunSelfHealthCheck() {
    gauge.set(getStatusCode(this.healthEndpoint));
  }
}

关键是 healthEndpoint.health() 会 运行 您的健康检查。代码 运行 每分钟进行一次健康检查。

如果您使用的是 Spring Boot >= 2.2,您可以使用单独的库 spring-boot-async-health-indicator 定期 运行 您的健康检查。

只需用 @AsyncHealth 注释您的 HealthIndicator(并可能重新定义 refreshRate 属性以确定 运行 它的频率)。

示例:

@AsyncHealth
@Component
public class PeriodicalHealthCheck implements HealthIndicator {

    @Override
    public Health health() { //will be executed asynchronously
        actualCheck();
        return Health.up().build();
    }

}

免责声明:我创建这个库就是为了这个目的