服务治理

服务注册与发现

服务启动时注册到注册中心,消费者通过注册中心发现服务地址。

负载均衡

算法 说明 适用场景
轮询 依次分配 请求处理时间相近
加权轮询 按权重分配 服务器性能不均
最小连接 分配给连接数最少的 长连接服务
IP哈希 同一IP固定到同一服务器 需要会话保持

Nginx 配置

upstream backend {
    least_conn;
    server 10.0.0.1:8080 weight=3;
    server 10.0.0.2:8080 weight=2;
}

server {
    location /api/ {
        proxy_pass http://backend;
    }
}

熔断降级

当某个服务出现故障时,熔断器快速失败,防止故障蔓延:

@CircuitBreaker(name = "userService", fallbackMethod = "fallback")
public User getUser(String userId) {
    return restTemplate.getForObject(
        "http://user-service/users/" + userId, User.class);
}

public User fallback(String userId, Throwable e) {
    return new User(userId, "default", "临时用户");
}

可观测性三支柱

1. 监控

使用 Prometheus + Grafana 监控服务指标。

2. 日志

{
    "timestamp": "2026-06-04T10:00:00Z",
    "level": "ERROR",
    "service": "user-service",
    "message": "数据库连接超时"
}

3. 告警

groups:
  - name: service-alerts
    rules:
      - alert: HighErrorRate
        expr: error_rate > 5%
        for: 5m
        labels:
          severity: critical

配置中心

集中管理所有服务的配置,支持热更新。常用方案:Nacos、Apollo、Consul。