在 spring boot 中编写自定义健康检查探针需实现 healthindicator 接口并注册为 bean,spring boot actuator 自动聚合至 /actuator/health 端点;应使用 health.builder() 构建响应,避免耗时操作与敏感信息泄露。

在 Spring Boot 中编写自定义健康检查探针,核心是实现 HealthIndicator 接口,并将其注册为 Spring Bean。Spring Boot Actuator 会自动发现并聚合这些指标,暴露在 /actuator/health 端点中。
创建自定义 HealthIndicator 实现类
新建一个类,实现 org.springframework.boot.actuate.health.HealthIndicator 接口,重写 health() 方法。该方法需返回 Health 对象,用 Health.up()、Health.down() 或 Health.outOfService() 构建状态,并可附加详细信息(如数据库连接耗时、依赖服务响应码等)。
- 推荐使用
Health.builder()链式调用,更清晰可控 - 避免在
health()中执行耗时或阻塞操作(如远程 HTTP 调用未设超时),否则拖慢整个健康端点响应 - 敏感信息(如密码、密钥)不要放入 health details
示例:检查 Redis 连通性
假设项目已引入 spring-boot-starter-data-redis 和 spring-boot-starter-actuator:
<font size="2"><pre class="brush:php;toolbar:false;">@Component
public class RedisHealthIndicator implements HealthIndicator {
private final RedisTemplate<string object> redisTemplate;
public RedisHealthIndicator(RedisTemplate<string object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
@Override
public Health health() {
try {
// 执行轻量探测:PING 或 SET key value EX 1(带过期避免污染)
Boolean pingResult = redisTemplate.execute((RedisCallback<boolean>) con -> con.ping());
if (Boolean.TRUE.equals(pingResult)) {
return Health.up()
.withDetail("ping", "success")
.withDetail("timestamp", System.currentTimeMillis())
.build();
}
} catch (Exception e) {
return Health.down()
.withDetail("error", e.getMessage())
.withDetail("timestamp", System.currentTimeMillis())
.build();
}
return Health.down().build();
}
}</boolean></string></string>
启用和访问健康端点
确保 application.yml 或 application.properties 中已配置:
-
management.endpoints.web.exposure.include=health(至少暴露 health) - 如需查看详细信息(含自定义指标的 details),加
management.endpoint.health.show-details=when_authorized或always(生产慎用) - 若使用 Spring Security,需放行
/actuator/health路径
启动应用后,访问 http://localhost:8080/actuator/health,响应中将包含 "redis": { "status": "UP", ... } 字段。
进阶:分组与条件启用
可通过 @ConditionalOnProperty 控制探针是否生效,例如只在启用 Redis 时加载:
<font size="2"><pre class="brush:php;toolbar:false;">@Component
@ConditionalOnProperty(name = "spring.redis.host", havingValue = "localhost", matchIfMissing = false)
public class RedisHealthIndicator implements HealthIndicator { ... }
也可用 @Endpoint 自定义更灵活的端点,但多数场景下 HealthIndicator 已足够简洁可靠。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











