Skip to content

Sentinel 熔断限流

一、Sentinel 概述

┌─────────────────────────────────────────────────────────────────┐
│                        Sentinel 概述                             │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  Sentinel = 流量控制 + 熔断降级 + 系统自适应                      │
│                                                                  │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │                    Sentinel Dashboard                    │   │
│  │   (实时监控、规则配置、簇点链路)                           │   │
│  └─────────────────────────────────────────────────────────┘   │
│                              │                                    │
│         ┌────────────────────┼────────────────────┐             │
│         ▼                    ▼                    ▼             │
│  ┌──────────┐         ┌──────────┐         ┌──────────┐       │
│  │   API    │         │  Service │         │ Database │       │
│  │ Gateway  │         │  Consumer│         │   Sink   │       │
│  └──────────┘         └──────────┘         └──────────┘       │
│                                                                  │
│  功能:                                                         │
│  - 流量控制(QPS/并发)                                         │
│  - 熔断降级(响应时间/异常比例/异常数)                         │
│  - 系统自适应(CPU/Load/平均RT)                                │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

二、快速开始

Maven 依赖

xml
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

配置

yaml
spring:
  cloud:
    sentinel:
      enabled: true
      transport:
        dashboard: localhost:8080  # Sentinel Dashboard 地址
      eager: true  # 启动时立即注册

三、流控规则

限流算法

┌─────────────────────────────────────────────────────────────────┐
│                      限流算法                                    │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  1. 直接拒绝(默认)                                            │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │ 请求 ──▶ QPS > 阈值? ──▶ 是 ──▶ 拒绝                   │   │
│  │              │                                         │   │
│  │              │ 否                                        │   │
│  │              ▼                                          │   │
│  │            通过                                          │   │
│  └─────────────────────────────────────────────────────────┘   │
│                                                                  │
│  2. 冷启动(Warm Up)                                          │
│  - 阶梯式增长到阈值                                             │
│  - 适合秒杀等场景                                              │
│                                                                  │
│  3. 匀速排队                                                   │
│  - 漏桶算法                                                    │
│  - 超过阈值排队等待                                            │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

代码配置

java
@Component
public class SentinelRules {
    
    @PostConstruct
    public void initRules() {
        FlowRule rule = FlowRule.from("user-service")
            .setGrade(RuleConstant.FLOW_GRADE_QPS)
            .setCount(100)  // 每秒100个请求
            .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT)
            .build();
        
        FlowRuleManager.loadRules(Collections.singletonList(rule));
    }
}

注解使用

java
@RestController
public class UserController {
    
    @SentinelResource(value = "getUser", 
                     blockHandler = "getUserBlockHandler",
                     fallback = "getUserFallback")
    @GetMapping("/user/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.findById(id);
    }
    
    // 限流/熔断时调用
    public User getUserBlockHandler(Long id, BlockException e) {
        return User.builder().id(id).name("系统繁忙").build();
    }
    
    // 异常时调用
    public User getUserFallback(Long id, Throwable t) {
        return User.builder().id(id).name("服务异常").build();
    }
}

四、熔断策略

三种熔断策略

┌─────────────────────────────────────────────────────────────────┐
│                      熔断策略                                    │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  1. 慢调用比例                                                  │
│  ├─ 设置最大响应时间 RT                                         │
│  ├─ 当慢调用比例 > 阈值,熔断                                   │
│  └─ 例:RT>200ms 的调用 > 50% → 熔断10秒                      │
│                                                                  │
│  2. 异常比例                                                    │
│  ├─ 当异常比例 > 阈值,熔断                                     │
│  └─ 例:异常 > 50% → 熔断10秒                                  │
│                                                                  │
│  3. 异常数                                                      │
│  ├─ 当异常数 > 阈值,熔断                                       │
│  └─ 例:10分钟内异常 > 10次 → 熔断10秒                         │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

配置示例

java
@PostConstruct
public void initDegradeRule() {
    DegradeRule rule = DegradeRule.from("user-service")
        .setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO)
        .setCount(0.5)              // 异常比例 50%
        .setMinRequestAmount(5)     // 最小请求数
        .setStatIntervalMs(60000)   // 统计时间窗口 1分钟
        .setTimeWindow(10)          // 熔断时长 10秒
        .build();
    
    DegradeRuleManager.loadRules(Collections.singletonList(rule));
}

五、Sentinel + Feign

依赖

xml
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

配置

yaml
feign:
  sentinel:
    enabled: true  # 启用 Sentinel

降级处理

java
@FeignClient(name = "user-service", fallback = UserClientFallback.class)
public interface UserClient {
    @GetMapping("/user/{id}")
    User getUser(@PathVariable Long id);
}

@Component
public class UserClientFallback implements UserClient {
    @Override
    public User getUser(Long id) {
        return User.builder().id(id).name("降级用户").build();
    }
}

六、Sentinel + Gateway

依赖

xml
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-gateway-alibaba-sentinel</artifactId>
</dependency>

配置

yaml
spring:
  cloud:
    gateway:
      routes:
        - id: user-route
          uri: http://localhost:8080
          predicates:
            - Path=/api/user/**
          filters:
            - name: Sentinel
              args:
                resource-name: /api/user/**
                fallback-uri: /defaultFallback

七、面试高频问题

Q1: Sentinel 和 Hystrix 区别?

对比SentinelHystrix
隔离策略信号量/线程池线程池
熔断策略响应时间/异常比例/异常数异常比例
实时性滑动窗口滚动窗口
运维Dashboard

Q2: 降级和熔断区别?

  • 降级:主动返回兜底数据
  • 熔断:连续失败后停止调用一段时间

Q3: @SentinelResource 注解参数?

  • value:资源名
  • blockHandler:限流/熔断处理
  • fallback:异常处理
  • exceptionsToIgnore:忽略的异常

八、下一章预告

下一章我们将学习 Config 配置中心

  • Spring Cloud Config
  • Nacos 配置管理
  • 配置刷新

基于 MIT 许可发布