如何使用Spring Boot Actuator导出Bean将应用健康状态上报为计量指标
Spring Boot Actuator 对外提供了可直接注入消费的 HealthEndpoint Bean,通过它可以拿到和 /actuator/health 端点返回结果完全一致的健康检查数据,完全复用内置的所有健康指示器逻辑,不需要自己单独实现健康校验规则。
具体使用说明
- 首先确保项目已引入
spring-boot-starter-actuator依赖,健康端点默认处于启用状态,无需额外配置即可注入使用 - 调用
HealthEndpoint的health()方法即可拿到整体应用的健康状态对象,支持获取全局状态、各细分健康组件的检测结果 - 你需求是上报Gauge类型指标,原代码中使用Counter类型不符合需求,Counter是累计值类型,Gauge才适合上报瞬时状态值,可根据健康状态码映射为不同的数值上报
修改后可用的代码示例
import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthEndpoint; import org.springframework.boot.actuate.health.Status; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import io.micrometer.core.instrument.Gauge; import io.micrometer.core.instrument.MeterRegistry; @Component public class HealthGaugeMetric { private final MeterRegistry meterRegistry; private final HealthEndpoint healthEndpoint; public HealthGaugeMetric(MeterRegistry meterRegistry, HealthEndpoint healthEndpoint) { this.meterRegistry = meterRegistry; this.healthEndpoint = healthEndpoint; } @Scheduled(fixedRate = 30000L) public void reportHealth() { Health health = healthEndpoint.health(); Status status = health.getStatus(); // 可根据业务需求自定义状态和数值的映射规则 int statusValue = switch (status.getCode()) { case "UP" -> 1; case "DOWN" -> 0; case "OUT_OF_SERVICE" -> -1; case "UNKNOWN" -> 2; default -> 3; }; Gauge.builder("service.status", () -> statusValue) .tag("status_code", status.getCode()) .register(meterRegistry); } }
如果需要获取包含所有组件健康详情的完整结果,也可以调用 healthEndpoint.health(ApiVersion.V3, true) 方法拉取全量数据,也支持通过 healthForPath 方法获取指定健康组件的单独状态。
内容的提问来源于stack exchange,提问作者JSF
相关产品推荐
相关产品推荐

