微服务健康检查:配置 Actuator 端点与 K8s 探针联动实现服务自愈
·
微服务健康检查:配置 Actuator 端点与 K8s 探针联动实现服务自愈
1. Spring Boot Actuator 配置
核心依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
端点配置(application.yml):
management:
endpoint:
health:
probes:
enabled: true # 启用专用探针端点
show-details: always
endpoints:
web:
exposure:
include: health,info # 暴露健康检查端点
2. Kubernetes 探针配置
在部署清单中定义两类探针:
apiVersion: apps/v1
kind: Deployment
spec:
template:
spec:
containers:
- name: my-service
livenessProbe: # 存活探针(失败时重启容器)
httpGet:
path: /actuator/health/liveness
port: 8080
initialDelaySeconds: 20 # 容器启动后等待时间
periodSeconds: 5 # 检查间隔
failureThreshold: 3 # 连续失败次数触发重启
readinessProbe: # 就绪探针(失败时从负载均衡移除)
httpGet:
path: /actuator/health/readiness
port: 8080
initialDelaySeconds: 15
periodSeconds: 5
failureThreshold: 2
3. 探针端点说明
| 探针类型 | Actuator 端点 | 作用场景 |
|---|---|---|
| 存活探针 | /actuator/health/liveness | 检测应用是否崩溃,失败时触发容器重启 |
| 就绪探针 | /actuator/health/readiness | 检测应用是否可处理流量,失败时从 Service Endpoints 移除 |
4. 自定义健康检查(可选)
实现自定义健康指示器:
@Component
public class DatabaseHealthIndicator implements HealthIndicator {
@Override
public Health health() {
return checkDatabase() ?
Health.up().build() :
Health.down().withDetail("error", "DB connection failed").build();
}
private boolean checkDatabase() { /* 数据库检查逻辑 */ }
}
5. 自愈机制流程图
graph LR
A[K8s 存活探针] -->|检测失败| B[重启容器]
C[K8s 就绪探针] -->|检测失败| D[从服务发现移除]
E[自定义健康检查] -->|异常状态| F[触发探针失败]
6. 最佳实践
- 探针超时配置:
livenessProbe: timeoutSeconds: 1 # 1秒超时 - 区分探针逻辑:
- 存活探针:检查核心进程状态
- 就绪探针:检查依赖服务(DB/缓存等)
- 优雅停机:
lifecycle: preStop: exec: command: ["sh", "-c", "sleep 30"] # 预留流量排空时间
7. 验证步骤
- 强制使健康检查失败:
kubectl exec <pod-name> -- curl -X POST http://localhost:8080/actuator/down - 观察事件日志:
kubectl describe pod <pod-name> | grep -A 10 Events - 验证容器重启:
kubectl get pod <pod-name> -w
关键优势:当服务因依赖故障或资源枯竭进入异常状态时,该方案能在 10-15 秒内自动隔离或恢复实例,实现零人工干预的服务自愈。
更多推荐
所有评论(0)