首页 > 解决方案 > 将 spring boot 执行器健康状态报告为指标

问题描述

我想将应用程序的健康状态报告为衡量标准,并且我希望使用与 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 boot 执行器是否会导出我可以通过这种方式消费的 bean?

标签: spring-bootspring-boot-actuator

解决方案


参考文档描述了如何通过将HealthEndpoint' 的响应映射到一个 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;
    }

}

推荐阅读