Spring Boot如何配置Liveness和Readiness探针
什么是存活探针和就绪探针
当我们采用Kubernetes作为编排平台时,每个Pod节点上的kubelet都负责维持该节点内Pod的健康状态。
例如,某些应用程序在启动后可能需要短暂准备时间才能开始接收请求。kubelet可以确保只有当应用准备就绪时才会向其转发流量。此外,如果Pod的主进程因任何意外原因崩溃,kubelet将自动重启容器。
为履行这些职责,Kubernetes提供了两种健康检查机制:存活探针(liveness probes)和就绪探针(readiness probes)。kubelet 将使用就绪探针来判断应用何时准备好接收请求。更具体地说,当 Pod 的所有容器都就绪时,该 Pod 才会被视为就绪状态。类似地,kubelet 可以通过存活探针检查 Pod 是否仍在运行。基本上,存活探针会帮助 kubelet 判断何时需要重启容器。
SpringBoot中配置存活探针和就绪探针
自Spring Boot 2.3起,LivenessStateHealthIndicator与ReadinessStateHealthIndicator类将对外暴露应用程序的存活状态和就绪状态。当我们将应用部署到Kubernetes环境时,Spring Boot会自动注册这些健康指标。
如此一来,我们便可分别使用/actuator/health/liveness和/actuator/health/readiness端点作为存活探针和就绪探针的检测接口。
在Spring Boot 2.3.2和以上:
- 首先添加actuator的依赖:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- 然后添加相应的配置:
management:endpoints:web:exposure:include: healthendpoint:health:probes:enabled: trueshow-details: alwayshealth:# /actuator/health/livenesslivenessState:enabled: true# /actuator/health/readinessreadinessState:enabled: true
浏览器访问:
// http://localhost:8080/actuator/health
{"status": "UP","components": {"diskSpace": {"status": "UP","details": {"total": 107369984000,"free": 59385589760,"threshold": 10485760,"path": "C:\\workspace\\demo\\.","exists": true}},"livenessState": {"status": "UP"},"ping": {"status": "UP"},"readinessState": {"status": "UP"}},"groups": ["liveness","readiness"]
}
//http://localhost:8080/actuator/health/liveness
{"status":"UP"}
//http://localhost:8080/actuator/health/readiness
{"status":"UP"}
Kubernetes中配置存活探针和就绪探针
标准的 Kubernetes YAML 写法:
containers:
- name: my-app...livenessProbe:httpGet:path: /actuator/health/liveness # 注意这里的写法port: 8080timeoutSeconds: 1periodSeconds: 10readinessProbe:httpGet:path: /actuator/health/readinessport: 8080timeoutSeconds: 1periodSeconds: 10
参考:https://www.baeldung.com/spring-liveness-readiness-probes