自愈机制设计

自愈是系统在检测到故障后,自动修复自己的能力。

自愈的层次

flowchart TD
    A["自愈机制"] --> B["应用层自愈"]
    A --> C["容器层自愈"]
    A --> D["基础设施层自愈"]

    B --> B1["健康检查 + 自动重启"]
    B1 --> B2["限流 + 降级"]
    B1 --> B3["故障转移"]

    C --> C1["K8s 存活探针"]
    C1 --> C2["K8s 自动重启"]
    C1 --> C3["水平 Pod 自动伸缩"]

    D --> D1["多可用区部署"]
    D1 --> D2["自动故障转移"]
    D1 --> D3["数据复制与恢复"]

自愈机制设计

1. 健康检查 + 自动重启

liveness-auto-restart.yaml
livenessProbe:
  httpGet:
    path: /health/live
    port: 8080
  failureThreshold: 3
  periodSeconds: 10
# 连续失败 3 次后重启,30 秒内检测到故障

2. 资源限制 + 水平扩展

hpa-autoscaling.yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: myapp
  minReplicas: 3
  maxReplicas: 10
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 70

本章总结

核心要点

  1. 自愈是分层的:应用层、容器层、基础设施层
  2. 健康检查是自愈的基础:检测故障
  3. 自动重启是最基本的自愈:K8s 存活探针