解决Spring Boot应用在Kubernetes上健康检查接口返回OUT_OF_SERVICE的问题

现象

在将Spring Boot应用部署到Kubernetes上时,健康检查接口/actuator/health返回的状态为{"status":"OUT_OF_SERVICE","groups":["liveness","readiness"]},而期望的是返回正常的健康状态。值得注意的是,我司统一的参照规范是将/actuator/health重定向到/healthcheck接口,并且三种探针的HTTP检查路径也都是/healthcheck

问题原因

从 Spring Boot 2.3 开始,LivenessStateHealthIndicator 和RereadynessStateHealthIndicator类将公开应用程序的活动性和就绪状态。当我们将应用程序部署到 Kubernetes 时,Spring Boot 将自动注册这些健康指标。而本次的问题是一次dubbo客户端升级导致的,目前不清楚是否是dubbo升级导致了其他依赖的版本更新。

解决方法

为了解决这个问题,我们可以采取以下步骤:

https://springdoc.cn/spring-boot/actuator.html#actuator.endpoints.health.writing-custom-health-indicators

该链接展示了Spring Boot Actutor在几种健康状态下返回的HTTP状态代码,如下图:

1.创建一个自定义的HealthEndpoint来处理健康检查请求,并将readiness或liveness的状态映射为UP/UNKNOWN状态。

复制代码
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthEndpoint;
import org.springframework.boot.actuate.health.Status;
import org.springframework.stereotype.Component;

@Component
@Endpoint(id = "health")
public class CustomHealthEndpoint {

    private final HealthEndpoint healthEndpoint;

    public CustomHealthEndpoint(HealthEndpoint healthEndpoint) {
        this.healthEndpoint = healthEndpoint;
    }

    @ReadOperation
    public Health health() {
        Health health = healthEndpoint.health();
        Status status = health.getStatus();

        // 如果状态是readiness或liveness,则设置为UNKNOWN,否则返回原始健康状态
        if (status.getCode().equals("readiness") || status.getCode().equals("liveness")) {
            return Health.unknown().withDetails(health.getDetails()).build();
        } else {
            return health;
        }
    }
}

2.将out_of_service返回的状态码映射成200。

application.properties:

复制代码
management.endpoint.health.status.http-mapping.out-of-service=200

application.yml:

复制代码
management:
    endpoint:
        health:
            status:
                http-mapping.out-of-service:200

通过上述配置,当应用程序的健康状态被判断为"out-of-service"时,Actuator将使用HTTP响应码200来表示该状态。这意味着当使用Actuator的健康检查端点时,如果应用程序的健康状态为"out-of-service",将返回HTTP响应码200。

总结

通过自定义HealthEndpoint和配置探针的HTTP路径,我们成功解决了Spring Boot应用在Kubernetes上健康检查接口返回OUT_OF_SERVICE的问题。现在,健康检查接口返回正确的健康状态,并且探针路径也与公司的重定向配置保持一致。这样,我们可以确保应用在Kubernetes环境中的健康检查正常运行,同时满足公司的需求。

相关推荐
程序员爱钓鱼5 小时前
Python编程实战 · 基础入门篇 | 类型转换与输入输出
后端·python
程序员爱钓鱼5 小时前
Python编程实战 · 基础入门篇 | 运算符详解
后端·python·编程语言
xiezhr5 小时前
见过哪些醍醐灌顶的Java代码:从"卧槽"到"原来如此"的顿悟
java·后端·设计模式
canonical_entropy5 小时前
Nop平台架构白皮书:一个基于广义可逆计算理论的软件构造体系评估
后端·低代码·领域驱动设计
IT_陈寒5 小时前
SpringBoot 3.2新特性盘点:这5个隐藏功能让你的开发效率翻倍 🚀
前端·人工智能·后端
韩立学长5 小时前
【开题答辩实录分享】以《智能垃圾回收小程序》为例进行答辩实录分享
spring boot·小程序
潜心编码5 小时前
基于Flask的志愿者管理系统
后端·python·flask
你总是一副不开心的样子(´ . .̫ .5 小时前
关于监控与部署
云原生·容器·kubernetes
Victor3565 小时前
Redis(78) 如何设置Redis的缓存失效策略?
后端
开心-开心急了5 小时前
Flask入门教程——李辉 第四章 静态文件 关键知识梳理 更新1次
后端·python·flask