Sentinel 流控与降级
约 975 字大约 3 分钟
布欧-Lewyon
2026-05-15
首页 › Spring Cloud › 服务容错
Sentinel 是面向分布式服务架构的流量控制组件,以"流量"为切入点,提供流控、降级、熔断、热点限流等能力。
安装 Sentinel 控制台
# Docker 启动
docker run -d \
--name sentinel \
-p 8858:8858 \
-p 8719:8719 \
bladex/sentinel-dashboard:1.8.8
# 访问 http://localhost:8858
# 默认账号:sentinel / sentinel添加依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>配置
spring:
cloud:
sentinel:
transport:
dashboard: localhost:8858 # 控制台地址
port: 8719 # 与控制台通信的端口
eager: true # 启动即连接控制台
datasource: # 规则持久化(后文详述)@SpringBootApplication
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}资源定义
@RestController
@RequestMapping("/api/orders")
public class OrderController {
@Autowired
private OrderService orderService;
// 方式一:@SentinelResource 注解
@GetMapping("/{id}")
@SentinelResource(value = "getOrder", fallback = "getOrderFallback")
public Result<Order> getOrder(@PathVariable Long id) {
return Result.success(orderService.getOrder(id));
}
public Result<Order> getOrderFallback(Long id, Throwable t) {
log.error("获取订单失败", t);
return Result.error("系统繁忙,请稍后重试");
}
// 方式二:代码定义资源(更灵活)
@PostMapping("/create")
public Result<Order> createOrder(@RequestBody CreateOrderRequest req) {
try (Entry entry = SphU.entry("createOrder")) {
return Result.success(orderService.createOrder(req));
} catch (BlockException e) {
return Result.error("请求过快,请稍后");
}
}
// 方式三:Web 请求自动埋点(URL 自动成为资源名)
}流控规则
@Configuration
public class SentinelRulesConfig {
@PostConstruct
public void initRules() {
// 1. QPS 流控:getOrder 接口每秒最多 10 QPS
FlowRule qpsRule = new FlowRule();
qpsRule.setResource("getOrder"); // 资源名
qpsRule.setGrade(RuleConstant.FLOW_GRADE_QPS); // 限流维度
qpsRule.setCount(10); // 阈值
qpsRule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT); // 快速失败
// 2. 线程数限流:createOrder 并发最多 5 线程
FlowRule threadRule = new FlowRule();
threadRule.setResource("createOrder");
threadRule.setGrade(RuleConstant.FLOW_GRADE_THREAD);
threadRule.setCount(5);
FlowRuleManager.loadRules(List.of(qpsRule, threadRule));
}
}控制台配置
Sentinel 控制台 → 流控规则 → 新增流控规则:
资源名: getOrder
阈值类型: QPS
单机阈值: 10
流控模式: 直接
流控效果: 快速失败流控效果
| 效果 | 说明 |
|---|---|
| 快速失败 | 直接抛出 BlockException,默认模式 |
| Warm Up | 预热模式,逐渐增加到阈值(防止冷启动流量暴增) |
| 排队等待 | 匀速排队,控制请求速率(适合削峰填谷) |
熔断降级规则
@PostConstruct
public void initDegradeRules() {
// 慢调用比例:50% 请求超 200ms 则熔断
DegradeRule rtRule = new DegradeRule("getOrder")
.setGrade(RuleConstant.DEGRADE_GRADE_RT) // RT 维度
.setCount(200) // 最大 RT(ms)
.setTimeWindow(10) // 熔断时长(秒)
.setMinRequestAmount(5); // 最小请求数
// 异常比例:10% 请求异常则熔断
DegradeRule exceptionRule = new DegradeRule("createOrder")
.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO)
.setCount(0.1)
.setTimeWindow(10)
.setMinRequestAmount(5);
DegradeRuleManager.loadRules(List.of(rtRule, exceptionRule));
}熔断状态机
热点参数限流
@GetMapping("/search")
@SentinelResource(value = "searchProduct",
blockHandler = "searchBlockHandler")
public Result<List<Product>> search(
@RequestParam String keyword,
@RequestParam(defaultValue = "1") Integer page) {
return Result.success(productService.search(keyword, page));
}
public Result<List<Product>> searchBlockHandler(
String keyword, Integer page, BlockException e) {
return Result.error("搜索过于频繁,请稍后");
}// 控制台 → 热点规则
// 资源名: searchProduct
// 参数索引: 0(keyword)
// 单机阈值: 5
// 参数例外项: keyword=iPhone → 阈值 20系统自适应保护
@PostConstruct
public void initSystemRules() {
SystemRule rule = new SystemRule();
rule.setHighestSystemLoad(10.0); // Load 阈值
rule.setAvgRt(1000); // 平均 RT
rule.setMaxThread(500); // 最大线程数
rule.setQps(10000); // 入口 QPS
rule.setHighestCpuUsage(0.8); // CPU 使用率
SystemRuleManager.loadRules(List.of(rule));
}小结
| 规则类型 | 说明 | 常用配置 |
|---|---|---|
| 流控 QPS | 限制每秒请求数 | QPS 100,直接拒绝 |
| 流控线程数 | 限制并发线程数 | 线程数 5 |
| 降级 RT | 慢调用比例降级 | RT > 200ms,比例 50% |
| 降级异常 | 异常比例/数降级 | 异常比 10% |
| 热点参数 | 根据参数限流 | keyword=iPhone 阈值 20 |
| 系统规则 | 整体系统保护 | CPU / Load / RT |
@SentinelResource:资源定义 + fallback 处理。- 流控效果:快速失败 / Warm Up / 排队等待。
- 熔断有三状态流转(CLOSED → OPEN → HALF_OPEN)。
- 控制台配置规则实时生效,无需重启。
上一节:配置动态刷新与共享 下一节:Sentinel + Feign 整合与规则持久化
