自定义健康检查指示器需实现HealthIndicator接口并注册为Bean,重写health()方法返回Health.up()/down()/unknown()构建的状态,支持添加详情;需启用Actuator并配置端点暴露,注意轻量性、异常处理及分组或条件启用。

在 Spring Boot 中,自定义健康检查指示器(HealthIndicator)只需实现接口并注册为 Bean,Spring Boot Actuator 会自动将其纳入 /actuator/health 端点。
创建自定义 HealthIndicator 实现类
编写一个类实现 org.springframework.boot.actuate.health.HealthIndicator 接口,重写 health() 方法。该方法返回 Health 对象,可使用 Health.up()、Health.down() 或 Health.unknown() 构建,并支持添加详细信息(如数据库连接耗时、错误原因等)。
示例:检查 Redis 连接状态
@Component
public class RedisHealthIndicator implements HealthIndicator {
private final RedisTemplate<string object> redisTemplate;
<pre class="brush:php;toolbar:false;">public RedisHealthIndicator(RedisTemplate<string object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
@Override
public Health health() {
try {
// 尝试执行一个轻量操作验证连通性
redisTemplate.getConnectionFactory().getConnection().close();
return Health.up()
.withDetail("message", "Redis is available")
.build();
} catch (Exception ex) {
return Health.down()
.withDetail("error", ex.getMessage())
.withDetail("timestamp", System.currentTimeMillis())
.build();
}
}</string>
}
启用 Actuator 并暴露健康端点
确保项目已引入 spring-boot-starter-actuator 依赖,并在 application.yml 或 application.properties 中配置端点暴露:
- YAML 示例:
management:
endpoint:
health:
show-details: when_authorized # 或 always(开发时方便调试)
endpoints:
web:
exposure:
include: health,info,metrics # 至少包含 health若使用 Spring Boot 3.x + Spring Security,还需配置安全放行或认证逻辑,否则访问 /actuator/health 可能返回 401。
按条件启用或分组健康检查
可通过 @ConditionalOnProperty、@Profile 控制指示器是否生效;也可用 HealthAggregator 或自定义 Group 实现分级健康视图(如 /actuator/health/db、/actuator/health/cache)。
例如,仅在 prod 环境启用某检查:
@Component
@Profile("prod")
public class ProductionOnlyHealthIndicator implements HealthIndicator {
// ...
}或通过配置分组(Spring Boot 2.2+ 支持):
management:
endpoint:
health:
group:
custom:
include: diskSpace,redis,myCustomCheck然后访问 /actuator/health/custom 即可查看该组的聚合结果。
注意细节与常见问题
- 健康检查方法应尽量轻量,避免阻塞或长时间 IO,否则拖慢整个
/health响应 - 不要在
health()中抛出未捕获异常,必须自行处理并返回Health.down()等明确状态 - 若使用 Lombok,注意
@RequiredArgsConstructor与构造注入兼容性,避免循环依赖 - 自定义指示器 Bean 名称默认作为 health key(如
redisHealthIndicator→"redisHealthIndicator"),可通过@Bean("redis")显式指定更简洁的 key
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











