Sentinel流量控制与熔断
约 1575 字大约 5 分钟
sentinelflow-control
2025-04-01
概述
Sentinel 是阿里巴巴开源的面向分布式服务架构的流量控制组件。它以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度保障服务的稳定性。Sentinel 与 Spring Cloud 深度集成,是微服务流量治理的核心工具。
核心概念
| 概念 | 说明 |
|---|---|
| 资源(Resource) | 被保护的对象,可以是方法、URL、服务调用等 |
| 规则(Rule) | 定义保护策略,如 QPS 阈值、熔断条件等 |
| Slot Chain | 责任链,按顺序执行各种规则检查 |
快速接入
引入依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>spring:
cloud:
sentinel:
transport:
dashboard: localhost:8080
port: 8719
eager: true # 立即初始化,而非懒加载流量控制规则
基本流控
@RestController
public class OrderController {
@GetMapping("/api/orders/{id}")
@SentinelResource(value = "getOrder",
blockHandler = "getOrderBlockHandler",
fallback = "getOrderFallback")
public Order getOrder(@PathVariable Long id) {
return orderService.findById(id);
}
// 限流/降级时的处理方法
public Order getOrderBlockHandler(Long id, BlockException ex) {
if (ex instanceof FlowException) {
throw new TooManyRequestsException("请求过于频繁,请稍后再试");
}
if (ex instanceof DegradeException) {
return Order.defaultOrder(id);
}
throw new ServiceException("Service temporarily unavailable");
}
// 业务异常的降级处理
public Order getOrderFallback(Long id, Throwable ex) {
return Order.defaultOrder(id);
}
}编程方式定义规则
@Configuration
public class SentinelRulesConfig {
@PostConstruct
public void initFlowRules() {
List<FlowRule> rules = new ArrayList<>();
// QPS 限流
FlowRule qpsRule = new FlowRule();
qpsRule.setResource("getOrder");
qpsRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
qpsRule.setCount(100); // 每秒最多100次
qpsRule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT); // 直接拒绝
rules.add(qpsRule);
// 并发线程数限流
FlowRule threadRule = new FlowRule();
threadRule.setResource("createOrder");
threadRule.setGrade(RuleConstant.FLOW_GRADE_THREAD);
threadRule.setCount(50); // 最多50个并发线程
rules.add(threadRule);
// 匀速排队(漏桶算法)
FlowRule warmUpRule = new FlowRule();
warmUpRule.setResource("batchImport");
warmUpRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
warmUpRule.setCount(10);
warmUpRule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER);
warmUpRule.setMaxQueueingTimeMs(5000); // 最大排队等待时间
rules.add(warmUpRule);
FlowRuleManager.loadRules(rules);
}
}流控效果
熔断降级规则
@PostConstruct
public void initDegradeRules() {
List<DegradeRule> rules = new ArrayList<>();
// 1. 慢调用比例熔断
DegradeRule slowRatioRule = new DegradeRule();
slowRatioRule.setResource("getOrder");
slowRatioRule.setGrade(CircuitBreakerStrategy.SLOW_REQUEST_RATIO.getType());
slowRatioRule.setCount(500); // 慢调用阈值:500ms
slowRatioRule.setSlowRatioThreshold(0.5); // 慢调用比例阈值 50%
slowRatioRule.setMinRequestAmount(10); // 最小请求数
slowRatioRule.setStatIntervalMs(10000); // 统计窗口 10秒
slowRatioRule.setTimeWindow(30); // 熔断时长 30秒
rules.add(slowRatioRule);
// 2. 异常比例熔断
DegradeRule errorRatioRule = new DegradeRule();
errorRatioRule.setResource("createOrder");
errorRatioRule.setGrade(CircuitBreakerStrategy.ERROR_RATIO.getType());
errorRatioRule.setCount(0.5); // 异常比例阈值 50%
errorRatioRule.setMinRequestAmount(10);
errorRatioRule.setStatIntervalMs(10000);
errorRatioRule.setTimeWindow(60); // 熔断时长 60秒
rules.add(errorRatioRule);
// 3. 异常数熔断
DegradeRule errorCountRule = new DegradeRule();
errorCountRule.setResource("payOrder");
errorCountRule.setGrade(CircuitBreakerStrategy.ERROR_COUNT.getType());
errorCountRule.setCount(10); // 异常数阈值
errorCountRule.setMinRequestAmount(5);
errorCountRule.setStatIntervalMs(60000); // 1分钟内
errorCountRule.setTimeWindow(120);
rules.add(errorCountRule);
DegradeRuleManager.loadRules(rules);
}熔断状态机
系统保护规则
@PostConstruct
public void initSystemRules() {
List<SystemRule> rules = new ArrayList<>();
SystemRule rule = new SystemRule();
rule.setHighestSystemLoad(10.0); // 系统最高负载
rule.setHighestCpuUsage(0.8); // CPU 使用率阈值 80%
rule.setAvgRt(200); // 所有入口的平均响应时间
rule.setMaxThread(500); // 入口最大并发线程数
rule.setQps(5000); // 所有入口的总QPS
rules.add(rule);
SystemRuleManager.loadRules(rules);
}权限控制规则
// 定义权限规则
@PostConstruct
public void initAuthorityRules() {
List<AuthorityRule> rules = new ArrayList<>();
AuthorityRule rule = new AuthorityRule();
rule.setResource("sensitiveApi");
rule.setStrategy(RuleConstant.AUTHORITY_WHITE); // 白名单
rule.setLimitApp("app-a,app-b"); // 只允许 app-a 和 app-b 访问
rules.add(rule);
AuthorityRuleManager.loadRules(rules);
}
// 自定义来源解析
@Component
public class CustomRequestOriginParser implements RequestOriginParser {
@Override
public String parseOrigin(HttpServletRequest request) {
return request.getHeader("X-App-Name");
}
}集群流控
// 集群流控配置
FlowRule clusterRule = new FlowRule();
clusterRule.setResource("createOrder");
clusterRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
clusterRule.setCount(1000); // 整个集群的总QPS限制
clusterRule.setClusterMode(true);
clusterRule.setClusterConfig(new ClusterFlowConfig()
.setFlowId(1001L)
.setThresholdType(ClusterRuleConstant.FLOW_THRESHOLD_GLOBAL)
.setSampleCount(10)
.setWindowIntervalMs(1000));Dashboard 控制台
# 启动 Sentinel Dashboard
java -jar sentinel-dashboard.jar --server.port=8080Dashboard 提供的功能:
| 功能 | 说明 |
|---|---|
| 实时监控 | QPS、响应时间、线程数实时图表 |
| 流控规则 | 动态配置流量控制规则 |
| 降级规则 | 动态配置熔断降级规则 |
| 热点规则 | 对热点参数进行限流 |
| 系统规则 | 系统级别的保护规则 |
| 权限规则 | 黑白名单控制 |
| 集群流控 | 配置集群流控 |
| 机器列表 | 查看接入的应用实例 |
与 Spring Cloud 集成
全局统一异常处理
@Component
public class CustomBlockExceptionHandler implements BlockExceptionHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
BlockException ex) throws Exception {
response.setContentType("application/json;charset=utf-8");
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
Map<String, Object> body = new HashMap<>();
if (ex instanceof FlowException) {
body.put("code", 429);
body.put("message", "请求被限流,请稍后重试");
} else if (ex instanceof DegradeException) {
body.put("code", 503);
body.put("message", "服务暂时不可用,已熔断降级");
} else if (ex instanceof ParamFlowException) {
body.put("code", 429);
body.put("message", "热点参数限流");
} else if (ex instanceof AuthorityException) {
body.put("code", 403);
body.put("message", "无权访问");
} else {
body.put("code", 429);
body.put("message", "系统繁忙,请稍后重试");
}
response.getWriter().write(new ObjectMapper().writeValueAsString(body));
}
}规则持久化(Nacos)
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>spring:
cloud:
sentinel:
datasource:
flow:
nacos:
server-addr: nacos:8848
data-id: ${spring.application.name}-flow-rules
group-id: SENTINEL_GROUP
data-type: json
rule-type: flow
degrade:
nacos:
server-addr: nacos:8848
data-id: ${spring.application.name}-degrade-rules
group-id: SENTINEL_GROUP
data-type: json
rule-type: degrade总结
Sentinel 提供了全面的流量治理能力:流量控制防止服务过载,熔断降级保障服务可用性,系统保护避免系统崩溃,权限控制实现访问管理。通过 Dashboard 可以实时监控和动态调整规则,配合 Nacos 实现规则持久化。在微服务架构中,Sentinel 是保障系统稳定性的关键组件。
贡献者
更新日志
2026/3/14 13:09
查看所有更新日志
9f6c2-feat: organize wiki content and refresh site setup于