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 | 资源名 |
| grade | 0=并发线程数,1=QPS |
| count | 阈值 |
| strategy | 0=直接,1=关联,2=链路 |
| controlBehavior | 0=快速失败,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 对比
| 特性 | Sentinel | Hystrix |
|---|---|---|
| 限流 | 支持(多维度) | 不支持 |
| 熔断 | 支持 | 支持 |
| 控制台 | 实时规则推送 | 只读监控 |
| 规则动态刷新 | 支持(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相关链接
- 限流熔断 ← 返回限流熔断目录