Spring Boot 3.x 微服务架构实战:熔断+限流

1. 架构设计

采用分层架构:

$$ 
\begin{array}{c}
\text{API网关} \\
\downarrow \\
\text{服务集群} \quad (\text{服务A, 服务B}) \\
\downarrow \\
\text{注册中心} \quad \text{配置中心}
\end{array}
$$
核心组件:
- **注册中心**:Nacos(服务发现)
- **熔断限流**:Sentinel
- **API网关**:Spring Cloud Gateway
- **配置中心**:Nacos Config

#### 2. 环境准备
```bash
# 启动Nacos(注册中心+配置中心)
docker run --name nacos -p 8848:8848 -e MODE=standalone nacos/nacos-server:v2.2.0

# 启动Sentinel控制台
docker run --name sentinel -p 8858:8858 bladex/sentinel-dashboard

3. 核心代码实现

1. 父工程pom.xml(依赖管理)

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>2022.0.0.0</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

2. 服务提供者(user-service)

// 启动类
@SpringBootApplication
@EnableDiscoveryClient
public class UserServiceApp {
    public static void main(String[] args) {
        SpringApplication.run(UserServiceApp.class, args);
    }
}

// Controller(熔断演示)
@RestController
@SentinelResource(value = "user-api", blockHandler = "blockHandler")
public class UserController {
    
    @GetMapping("/user/{id}")
    public User getUser(@PathVariable Long id) {
        // 模拟服务不稳定
        if (id % 5 == 0) throw new RuntimeException("服务异常");
        return new User(id, "User-" + id);
    }
    
    // 熔断降级方法
    public User blockHandler(Long id, BlockException ex) {
        return new User(-1L, "熔断保护");
    }
}

3. API网关配置

spring:
  cloud:
    gateway:
      routes:
        - id: user-service
          uri: lb://user-service
          predicates:
            - Path=/user/**
          filters:
            - StripPrefix=1
            - name: RequestRateLimiter
              args:
                redis-rate-limiter.replenishRate: 10   # 每秒10个令牌
                redis-rate-limiter.burstCapacity: 20    # 令牌桶容量

4. Sentinel熔断规则配置

@PostConstruct
public void initFlowRules() {
    List<FlowRule> rules = new ArrayList<>();
    FlowRule rule = new FlowRule();
    rule.setResource("user-api");
    rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
    rule.setCount(5);  // 每秒最大5次调用
    rules.add(rule);
    FlowRuleManager.loadRules(rules);
}

4. 熔断策略(基于Sentinel)
策略类型触发条件恢复条件
慢调用比例响应时间 > 500ms 比例超50%连续5个请求RT<200ms
异常比例异常比例 > 60%连续10个请求异常率<30%
异常数异常数 > 5次/分钟连续3分钟无异常
5. 限流算法对比
算法公式适用场景
令牌桶$r = \frac{C}{T}$平滑突发流量
漏桶$r_{out} \leq r_{max}$恒定速率处理
滑动窗口$\sum_{i=1}^{n} req_i \leq L$精确控制时间段内请求量
6. 测试验证
  1. 压力测试:
    ab -n 1000 -c 50 http://localhost:8080/user/1
    

  2. 观察指标:
    • Sentinel控制台:QPS、拒绝请求数、异常比例
    • 熔断器状态:OPEN/HALF-OPEN/CLOSED
7. 高可用保障
  1. 集群部署:每个服务至少2个实例
  2. 健康检查:Kubernetes探针
  3. 级联保护:网关层+服务层双重限流
  4. 动态配置:Nacos实时更新规则

注意事项:

  1. 生产环境需启用Sentinel持久化(默认规则存在内存)
  2. 网关限流键建议使用用户ID/IP等维度
  3. 熔断恢复时间窗口需根据业务调整

通过此架构可实现:

  • 单节点故障自动隔离
  • 突发流量削峰填谷
  • 异常服务快速降级
  • 资源利用率提升30%+

更多推荐