Spring Boot 自定义Kubernetes readiness probe 实现方法咨询
自定义就绪检测实现步骤
1. 实现自定义健康检测类
你需要的customCheck对应Spring Boot Actuator的HealthIndicator接口实现,直接在你的Spring Boot项目中新增该实现类,在类中编写外部服务状态判断逻辑即可:
import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; // 注解中指定Bean名称为customCheck,和配置中的检测项id对应 @Component("customCheck") public class ExternalServiceHealthIndicator implements HealthIndicator { // 注入你调用外部服务的工具类,比如RestTemplate、Feign客户端等 private final ExternalServiceClient externalServiceClient; public ExternalServiceHealthIndicator(ExternalServiceClient externalServiceClient) { this.externalServiceClient = externalServiceClient; } @Override public Health health() { try { // 调用外部服务探活接口,判断服务是否正常 boolean serviceAlive = externalServiceClient.checkAlive(); if (serviceAlive) { // 外部服务正常,返回UP状态 return Health.up().withDetail("externalService", "运行正常").build(); } else { // 外部服务异常,返回DOWN状态 return Health.down().withDetail("externalService", "服务不可用").build(); } } catch (Exception e) { // 调用报错同样返回DOWN return Health.down().withDetail("errorMsg", e.getMessage()).build(); } } }
2. 配置Actuator就绪健康组
在项目的application.properties或application.yml中添加如下配置,将自定义的customCheck加入就绪检测组:
# 内置就绪状态检测+自定义外部服务检测共同作为就绪判断条件 management.endpoint.health.group.readiness.include=readinessState,customCheck # 可选配置:开启就绪端点的详情展示,方便问题排查 management.endpoint.health.group.readiness.show-details=always
3. 调整Kubernetes探针配置
建议将原有探针路径调整为就绪组专属端点,Kubernetes会直接根据就绪组的整体状态判断Pod是否可以接收流量,调整后的YAML如下:
readinessProbe: initialDelaySeconds: 10 periodSeconds: 10 httpGet: path: /actuator/health/readiness # 替换为就绪组专属端点 port: 12345
运行逻辑说明
就绪组内所有检测项都返回UP状态时,/actuator/health/readiness接口才会返回200状态码,Kubernetes会将该Pod标记为就绪,纳入服务负载均衡池;只要有任意一个检测项返回DOWN,接口就会返回503状态码,Kubernetes不会将流量转发到该Pod。
内容的提问来源于stack exchange,提问作者Hummus
相关产品推荐
相关产品推荐

