报告 spring 引导执行器健康状态作为指标

Report spring boot actuator health status as a metric

我想报告应用程序的健康状况作为衡量标准,我希望使用与 spring-boot-actuator 相同的健康指标,但是,我没有看到任何可导出的组件spring-boot-actuator 依赖项,我可以在这里使用。

我想写的代码:

@Component
public class HealthCounterMetric {
  private final Counter statusCounter;

  public HealthCounterMetric(MeterRegistry meterRegistry, SystemHealth systemHealth) {
    this.statusCounter = meterRegistry.counter("service.status");
  }

  @Scheduled(fixedRate = 30000L)
  public void reportHealth() {
    //do report health
  }
}

当然,SystemHealth 不是导出的 bean。 spring 引导执行器是否导出我可以通过这种方式使用的 bean?

参考文档describes how to do this by mapping the HealthEndpoint's response to a gauge:

@Configuration(proxyBeanMethods = false)
public class MyHealthMetricsExportConfiguration {

    public MyHealthMetricsExportConfiguration(MeterRegistry registry, HealthEndpoint healthEndpoint) {
        // This example presumes common tags (such as the app) are applied elsewhere
        Gauge.builder("health", healthEndpoint, this::getStatusCode).strongReference(true).register(registry);
    }

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

}