Spring Boot Actuator 指南
Spring Boot Actuator 生产监控:健康检查、指标、自定义指示器和 Prometheus/Grafana 集成。
1. 配置 (application.yml)
management:
endpoint:
health:
show-details: when-authorized
probes:
enabled: true
endpoints:
web:
exposure:
include: health,info,metrics,prometheus,loggers
metrics:
tags:
application: ${spring.application.name}
2. 自定义健康指示器
@Component
public class ExternalApiHealthIndicator implements HealthIndicator {
@Override
public Health health() {
try {
ResponseEntity<String> resp = restTemplate.getForEntity(
"https://api.external.com/ping", String.class);
if (resp.getStatusCode().is2xxSuccessful()) {
return Health.up().withDetail("status", resp.getStatusCode().value()).build();
}
return Health.down().withDetail("status", resp.getStatusCode().value()).build();
} catch (Exception e) {
return Health.down(e).withDetail("error", e.getMessage()).build();
}
}
}
3. 自定义 Micrometer 指标
@Service
public class ArticleService {
private final Counter publishedCounter;
private final Timer processTimer;
public ArticleService(MeterRegistry registry) {
this.publishedCounter = Counter.builder("articles.published")
.tag("type", "blog")
.register(registry);
this.processTimer = Timer.builder("articles.processing.time")
.publishPercentiles(0.5, 0.95, 0.99)
.register(registry);
}
public ArticleDto publish(Long id) {
return processTimer.record(() -> {
// 业务逻辑
publishedCounter.increment();
return ArticleDto.from(article);
});
}
}
4. 常用端点参考
| 端点 | 用途 |
|---|---|
| /actuator/health | 应用健康状态 |
| /actuator/health/liveness | K8s 存活探针 |
| /actuator/health/readiness | K8s 就绪探针 |
| /actuator/metrics | 列出所有指标 |
| /actuator/prometheus | Prometheus 抓取 |
| /actuator/loggers | 动态调整日志级别 |
| /actuator/env | 环境配置 |
| /actuator/threaddump | JVM 线程转储 |