Spring Boot自定义健康指示器
Actuator 提供健康检查端点,可扩展自定义健康指示器。
内置健康指示器
Spring Boot 自动配置以下健康检查:
| 指示器 | 检查内容 |
|---|---|
| DataSourceHealthIndicator | 数据库连接 |
| RedisHealthIndicator | Redis连接 |
| DiskSpaceHealthIndicator | 磁盘空间 |
| MongoHealthIndicator | MongoDB连接 |
自定义健康指示器
Java
@Component
public class CustomHealthIndicator implements HealthIndicator {
@Override
public Health health() {
// 执行健康检查逻辑
if (checkService()) {
return Health.up()
.withDetail("service", "正常")
.withDetail("response_time", "50ms")
.build();
} else {
return Health.down()
.withDetail("service", "异常")
.withDetail("error", "连接超时")
.build();
}
}
private boolean checkService() {
// 实际检查逻辑
return true;
}
}
健康状态
Java
// 不同状态
Health.up() // 健康
Health.down() // 不健康
Health.unknown() // 未知
Health.outOfService() // 停止服务
帥康检查响应示例
JSON
{
"status": "UP",
"components": {
"custom": {
"status": "UP",
"details": {
"service": "正常",
"response_time": "50ms"
}
},
"db": {
"status": "UP",
"details": {
"database": "MySQL",
"validationQuery": "isValid()"
}
}
}
}
Reactive健康指示器
Java
@Component
public class ReactiveHealthIndicator implements ReactiveHealthIndicator {
@Override
public Mono<Health> health() {
return checkExternalService()
.map(healthy -> Health.up()
.withDetail("external", "available")
.build())
.onErrorResume(ex -> Mono.just(Health.down()
.withDetail("error", ex.getMessage())
.build()));
}
private Mono<Boolean> checkExternalService() {
return webClient.get()
.retrieve()
.bodyToMono(Boolean.class);
}
}
配置健康检查
YAML
management:
endpoint:
health:
show-details: always # 显示详情
show-components: always
health:
custom:
enabled: true
db:
enabled: true
diskspace:
enabled: true
threshold: 10MB
健康状态聚合
Java
@Component
public class CompositeHealthIndicator implements HealthIndicator {
private final List<HealthIndicator> indicators;
public CompositeHealthIndicator(List<HealthIndicator> indicators) {
this.indicators = indicators;
}
@Override
public Health health() {
for (HealthIndicator indicator : indicators) {
Health health = indicator.health();
if (health.getStatus() != Status.UP) {
return health;
}
}
return Health.up().build();
}
}
配置详情显示策略
| 配置值 | 说明 |
|---|---|
| never | 不显示详情 |
| when-authorized | 授权用户显示 |
| always | 总是显示 |
生产环境建议使用 when-authorized,避免敏感信息泄露。
要点总结
- 实现HealthIndicator接口自定义检查逻辑
- 使用Health.up()/down()返回健康状态
- 可添加详细信息便于排查问题
- Reactive应用使用ReactiveHealthIndicator
📝 发现内容有误?点击此处直接编辑