Sentinel

Sentinel 是阿里巴巴开源的面向分布式服务架构的流量治理组件,以流量为切入点,覆盖流量控制、熔断降级、系统自适应保护等多个维度。

核心功能

功能说明
流量控制QPS 限流、并发线程数限流、热点参数限流
熔断降级基于慢调用比例、异常比例、异常数三种策略
系统自适应保护根据系统负载、CPU 使用率自动限流
集群限流通过 Token Server 实现集群级别的精准限流
实时监控Dashboard 提供实时流量监控与规则推送

处理链(SlotChain)

业务请求
    │
    ▼
NodeSelectorSlot → ClusterBuilderSlot → StatisticSlot
    → FlowSlot → DegradeSlot → SystemSlot → AuthoritySlot
    │
    ├── 通过 → 执行业务逻辑
    └── 拒绝 → 抛出 BlockException

快速接入(Spring Cloud Alibaba)

依赖

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

配置

spring:
  cloud:
    sentinel:
      transport:
        dashboard: localhost:8080
        port: 8719

资源定义

@SentinelResource(
    value = "queryOrder",
    blockHandler = "queryOrderBlocked",
    fallback    = "queryOrderFallback"
)
public OrderDTO queryOrder(Long id) {
    return orderService.getById(id);
}
 
public OrderDTO queryOrderBlocked(Long id, BlockException ex) {
    return OrderDTO.empty();  // 限流/熔断降级结果
}
 
public OrderDTO queryOrderFallback(Long id, Throwable t) {
    return OrderDTO.empty();  // 业务异常降级结果
}

流量控制规则

字段说明
resource资源名
grade0=并发线程数,1=QPS
count阈值
strategy0=直接,1=关联,2=链路
controlBehavior0=快速失败,1=Warm Up,2=排队等待
FlowRule rule = new FlowRule("queryOrder")
    .setGrade(RuleConstant.FLOW_GRADE_QPS)
    .setCount(100);
FlowRuleManager.loadRules(List.of(rule));

熔断降级策略

策略触发条件状态机
慢调用比例RT > 阈值 且 慢调用比 > 设定值CLOSED → OPEN → HALF_OPEN
异常比例异常比例 > 阈值(如 50%)同上
异常数异常总数 > 阈值同上

热点参数限流

对某个参数的特定值单独设置阈值,适用于爆款商品等场景:

@SentinelResource("hotItem")
public Item getItem(@RequestParam Long itemId) {
    return itemService.get(itemId);
}

在控制台为 itemId=1001 单独设置 QPS=10,其他值使用默认阈值。

与 Hystrix 对比

特性SentinelHystrix
限流支持(多维度)不支持
熔断支持支持
控制台实时规则推送只读监控
规则动态刷新支持(Nacos/Apollo)不支持
维护状态活跃停止维护

规则持久化(Nacos 推模式)

spring:
  cloud:
    sentinel:
      datasource:
        flow:
          nacos:
            server-addr: 127.0.0.1:8848
            dataId: sentinel-flow-rules
            groupId: SENTINEL_GROUP
            rule-type: flow

相关链接

Spring Cloud 实战