← 返回首页
🛡️

高可用架构设计

📂 architecture ⏱ 1 min 150 words

高可用架构设计

故障域与多活部署

高可用架构的第一原则是识别并隔离故障域。故障域是可能发生故障的最小边界,包括硬件故障、网络分区、数据中心宕机等。通过将服务部署在不同故障域中,可以确保单一故障不会导致整个系统不可用。

# Kubernetes 多区域部署示例
apiVersion: apps/v1
kind: Deployment
metadata:
  name: order-service
spec:
  replicas: 3
  template:
    spec:
      topologySpreadConstraints:
        - maxSkew: 1
          topologyKey: topology.kubernetes.io/zone
          whenUnsatisfiable: DoNotSchedule
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
            - weight: 100
              podAffinityTerm:
                labelSelector:
                  matchExpressions:
                    - key: app
                      operator: In
                      values: ["order-service"]
                topologyKey: kubernetes.io/hostname

多活部署策略包括同城双活和异地多活。同城双活在同一个城市的不同机房部署两套完整系统,通过专线同步数据,RPO 接近零。异地多活则在不同地理区域部署独立系统,各区域可独立处理请求,但数据同步延迟较高。

自动故障转移

自动故障转移是高可用的关键机制。系统需要实时监控各组件的健康状态,在检测到故障时自动将流量切换到健康节点。

// 基于心跳的健康检查与自动故障转移
@Component
public class HealthCheckService {
    private final LoadBalancer loadBalancer;
    private final ScheduledExecutorService scheduler;
    
    @Autowired
    public HealthCheckService(LoadBalancer loadBalancer) {
        this.loadBalancer = loadBalancer;
        this.scheduler = Executors.newScheduledThreadPool(2);
    }
    
    @PostConstruct
    public void startHealthCheck() {
        scheduler.scheduleAtFixedRate(() -> {
            List<ServiceInstance> instances = loadBalancer.getAllInstances();
            for (ServiceInstance instance : instances) {
                try {
                    boolean healthy = checkHealth(instance);
                    if (!healthy) {
                        loadBalancer.markUnhealthy(instance);
                        triggerFailover(instance);
                    }
                } catch (Exception e) {
                    loadBalancer.markUnhealthy(instance);
                }
            }
        }, 0, 10, TimeUnit.SECONDS);
    }
    
    private void triggerFailover(ServiceInstance failedInstance) {
        log.warn("触发故障转移: {}", failedInstance.getId());
        // 将流量切换到备用节点
        loadBalancer.rebalance();
        // 发送告警通知
        alertService.sendAlert("节点故障: " + failedInstance.getId());
    }
}

可用性度量与目标

高可用通常用 SLA(服务等级协议)来衡量,可用性百分比对应不同的停机时间:

实现更高可用性需要在冗余设计、监控告警、自动化运维等方面持续投入。关键是根据业务重要性选择合适的可用性目标,避免过度设计带来的成本浪费。