一、Spring Cloud Sentinel 整体架构
Spring Cloud Sentinel 是阿里巴巴开源的高可用流量防护组件 Sentinel 的 Spring Cloud 版本扩展,它通过自动装配和注解方式,让开发者更方便地在微服务架构中实现限流、熔断、降级等高可用控制。
1. Sentinel 核心目标
流量控制:控制 QPS 或线程数,避免突发流量压垮服务。
熔断降级:当调用链路中某服务不稳定,进行熔断,快速失败。
系统自适应保护:基于系统负载(如 CPU 使用率)动态控制流量。
实时监控:提供 Dashboard 支持运行时规则管理和实时流量监控。
2. Sentinel 架构总览(逻辑层)
┌────────────┐
│ Dashboard │ ← Web 控制台
└────┬───────┘
│ 推送规则
┌─────▼─────────┐
│ Spring 应用实例│
└─────┬─────────┘
│
┌──────────────┴────────────────┐
│ Sentinel Java Core │
└──────────────┬────────────────┘
│
┌──────────────▼───────────────────────┐
│ 插件机制(Transport、Cluster、Adapter)│
└───────────────────────────────────────┘
3. Sentinel 核心模块(Java Core)
1. Slot Chain(插槽链)机制
Sentinel 的核心是基于责任链模式构建的 SlotChain,形成一条拦截链:
ProcessorSlotChain chain = SlotChainProvider.newSlotChain();
chain.entry(context, resourceWrapper, node, count, prioritized, args);
Slot 执行链条:
执行顺序如下:
插槽名 | 作用描述 |
---|---|
NodeSelectorSlot |
维护资源调用路径关系,生成调用树 |
ClusterBuilderSlot |
构建资源的 ClusterNode(统计信息、全局限流) |
LogSlot |
日志记录(可扩展) |
StatisticSlot |
记录线程数、QPS、RT 等指标 |
SystemSlot |
系统保护规则(如 CPU 使用率、系统负载) |
AuthoritySlot |
黑白名单校验 |
FlowSlot |
限流控制(核心) |
DegradeSlot |
熔断降级(RT、异常比率、异常数) |
📌 每个 Slot 都是 ProcessorSlot
的实现,通过 DefaultSlotChainBuilder
构建链条。
2. 数据模型结构(核心类)
类名 | 描述说明 |
---|---|
Context |
表示一次调用上下文(入口资源 + 调用链) |
ResourceWrapper |
封装资源名和资源类型 |
Node |
资源的统计信息结构,构成调用树结构 |
ClusterNode |
资源全局统计结构,所有上下文共享 |
StatisticNode |
实现统计逻辑,如 QPS、RT、线程数等 |
Entry |
表示一次资源访问,用于控制和清理 |
4. 规则控制逻辑
Sentinel 的规则均为内存规则,支持动态更新(从控制台拉取或本地配置):
1. 流控规则(FlowRule)
FlowRule rule = new FlowRule();
rule.setResource("order-service");
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
rule.setCount(100); // QPS限流
FlowRuleManager.loadRules(Collections.singletonList(rule));
核心算法:滑动窗口 + 令牌桶 / 漏桶 + 熔断控制
2. 熔断规则(DegradeRule)
支持三种熔断:
RT 模式
异常比率
异常数
3. 系统保护规则(SystemRule)
基于:
系统 load
RT
QPS
线程数
内存使用率
5. Spring Cloud Sentinel 整合架构(Adapter)
Sentinel 在 Spring Cloud 中的核心整合模块是:
spring-cloud-starter-alibaba-sentinel
1. 入口适配层 Adapter(如 RestTemplate、Feign、Gateway)
Sentinel 为各类组件提供适配器,如:
场景 | 适配器实现类 |
---|---|
RestTemplate |
SentinelRestTemplateInterceptor |
Feign |
SentinelFeign 动态代理 + fallbackFactory |
Gateway |
SentinelGatewayFilter + SentinelGatewayBlockExceptionHandler |
2. Spring Boot 自动装配
SentinelAutoConfiguration
注册默认规则管理器、控制器、过滤器等
6. 调用流程全图(以 RestTemplate 为例)
客户端请求 → Controller → RestTemplate
↓
SentinelRestTemplateInterceptor
↓
SphU.entry(resourceName) ← SlotChain 检查
↓
正常执行或 BlockException 异常
7. 自定义扩展机制
1. 自定义 Block 异常处理器
public class MyExceptionHandler implements BlockExceptionHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, BlockException ex) throws IOException {
response.getWriter().write("系统繁忙,请稍后再试");
}
}
注册:
spring.cloud.sentinel.filter.exception-handler-class: com.example.MyExceptionHandler
2. 自定义 Slot 插槽链
可以通过 SPI 扩展:
META-INF/services/com.alibaba.csp.sentinel.slotchain.SlotChainBuilder
8. 与 Dashboard 的通信机制
Sentinel 默认使用 Netty 启动一个本地服务,向 Dashboard 注册:
启动:
CommandCenterInitFunc
,默认端口 8719与控制台通信:
HeartbeatSender
定时心跳上报拉取规则:控制台推送 JSON → 应用端解析并加载入 RuleManager
9. 集群限流机制(扩展)
通过以下组件实现集群流控:
Token Server:中心化限流服务节点
Token Client:各微服务接入限流客户端
核心类:
ClusterFlowSlot
ClusterNodeManager
10. 总结
维度 | 说明 |
---|---|
架构核心 | SlotChain + 插槽机制 + 统计模型 |
Spring 整合方式 | Starter 自动配置,注解 + 配置驱动 |
控制粒度 | 支持 QPS、线程数、RT、异常率等 |
动态规则 | Dashboard 或 Nacos/Redis/ZK 推送 |
扩展能力 | 插槽、拦截器、异常处理器、日志等 |
二、深入剖析 Sentinel 熔断机制的完整执行流程
1. Sentinel 熔断降级机制
Sentinel 的熔断机制由 DegradeRule
控制,主要用于应对系统不稳定,如:
响应时间过长(RT)
异常比例过高
异常数过多
触发后,对应资源在一段时间内拒绝请求(快速失败),避免请求雪崩。
2. 触发入口:客户端调用链路起点
以 Spring Cloud + RestTemplate 示例:
@RestController
public class OrderController {
@GetMapping("/order")
public String order() {
// Sentinel 入口
try (Entry entry = SphU.entry("orderService")) {
return restTemplate.getForObject("http://user-service/user", String.class);
} catch (BlockException e) {
return "熔断了";
}
}
}
🔗 入口方法:
Entry entry = SphU.entry("orderService");
这是 Sentinel 的核心资源调用拦截点。
3. 核心机制:Slot Chain 执行链
Sentinel 使用责任链模式,每个资源被访问时,会经过一系列 ProcessorSlot
:
DefaultProcessorSlotChain:
┌──────────────┬───────────────┬────────────┬─────────────┬──────────────┬────────────┐
│ NodeSelector │ ClusterBuilder│ LogSlot │ Statistic │ SystemSlot │ ... │
└──────────────┴───────────────┴────────────┴─────────────┴──────────────┴────────────┘
↓
DegradeSlot
其中最后一个用于熔断的是:DegradeSlot
4. DegradeSlot 逻辑详解(熔断执行核心)
路径:com.alibaba.csp.sentinel.slots.block.degrade.DegradeSlot
➤ 1. Slot 执行入口
public void entry(Context context, ResourceWrapper resource, ...)
throws Throwable {
// 获取资源配置的所有熔断规则
List<DegradeRule> rules = DegradeRuleManager.getRules(resource.getName());
for (DegradeRule rule : rules) {
rule.passCheck(context, resource, ...); // 核心判断
}
fireEntry(context, resource, ...); // 继续传给下一个 slot
}
5. DegradeRule 判定机制分析
路径:DegradeRule#passCheck(...)
Sentinel 支持三种熔断策略(由 grade
控制):
grade |
类型 | 触发条件 |
---|---|---|
0 |
RT(慢调用) | 平均响应时间 > count 且 QPS 达到最小请求数 |
1 |
异常比例 | 异常比例 > count 且请求数足够 |
2 |
异常数 | 异常次数 > count 且时间窗口内 |
➤ 以“异常比例熔断”为例:
if (grade == RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO) {
if (exceptionQps / totalQps > count) {
// 熔断触发
cut(); // 开启熔断
throw new DegradeException(...);
}
}
cut()
方法:this.pass = false; this.cutTime = currentTime;
表示开启熔断,记录开始时间。
熔断窗口时间
timeWindow
:
例如设置为 10 秒,则在此期间,所有请求都会被拒绝。
6. 熔断触发后的行为
当熔断开启,后续调用会走下面的逻辑:
if (!pass && currentTime - cutTime < timeWindow) {
throw new DegradeException(resource.getName());
}
即抛出 DegradeException
→ 被上层捕获
7. 熔断后请求流程(图示)
用户请求
↓
SphU.entry("resourceName")
↓
SlotChain 执行 → 到达 DegradeSlot
↓
读取 DegradeRuleManager 中的规则
↓
调用 passCheck()
↓
判断异常比例、RT 或 异常数
↓
满足熔断 → 调用 cut() → 抛出 DegradeException
↓
上层捕获异常(BlockException)
↓
执行 fallback 或返回默认值
8. 降级规则配置方式
动态规则推送(如 Dashboard / Nacos):
[
{
"resource": "orderService",
"count": 0.2,
"grade": 1,
"timeWindow": 10,
"minRequestAmount": 5,
"statIntervalMs": 1000,
"slowRatioThreshold": 0.5
}
]
或通过代码:
DegradeRule rule = new DegradeRule();
rule.setResource("orderService");
rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);
rule.setCount(0.5); // 异常比例 50%
rule.setTimeWindow(10);
rule.setMinRequestAmount(10);
DegradeRuleManager.loadRules(Collections.singletonList(rule));
9. 降级恢复逻辑
当进入熔断后,过了时间窗口(timeWindow)后,会自动关闭熔断:
if (!pass && currentTime - cutTime >= timeWindow) {
pass = true; // 恢复服务访问
}
即:自动恢复,无需人工干预。
10. 总结:熔断完整流程回顾
阶段 | 描述 |
---|---|
请求入口 | 使用 SphU.entry(...) 拦截资源访问 |
Slot 执行链 | 最终进入 DegradeSlot ,执行降级判断 |
降级判断 | 三种策略:慢调用、异常比例、异常数 |
状态变更 | 调用 cut() 标记资源熔断 |
拒绝请求 | 抛出 DegradeException ,上层 fallback |
恢复机制 | 熔断时间窗口后自动恢复(滑动时间窗) |
三、深入剖析 Sentinel 如何完成降级(Degrade)机制
从客户端发起请求到 Sentinel 判断并执行降级的 整个底层流程,包括:
客户端调用入口
Sentinel SlotChain 架构
DegradeSlot
插槽作用三种降级策略详解(慢调用、异常比例、异常数)
统计数据结构(滑动窗口)
降级状态切换和恢复机制
异常抛出与 fallback 处理
1. 降级 vs 限流:区别简析
类型 | 限流(Flow) | 降级(Degrade) |
---|---|---|
控制指标 | QPS / 并发数 | RT、异常比例、异常数 |
触发时机 | 系统压力大 | 系统异常增多或响应变慢 |
控制方式 | 当前立即拒绝 / 排队等待 | 在窗口期内,所有请求快速失败 |
插槽类 | FlowSlot |
DegradeSlot |
抛出异常 | FlowException |
DegradeException |
2. 降级核心流程概览
客户端请求
↓
SphU.entry("资源名")
↓
SlotChain 执行 → DegradeSlot
↓
DegradeRuleManager 查找所有规则
↓
依策略判断是否熔断(passCheck)
↓
触发熔断 → 抛出 DegradeException
↓
上层处理 fallback
3. 客户端入口:资源访问调用
try (Entry entry = SphU.entry("orderService")) {
// 正常调用
} catch (BlockException e) {
// 降级触发 fallback
return "服务降级";
}
核心代码:
CtSph.entry(resource) → ProcessorSlotChain.entry() → DegradeSlot.entry()
4. SlotChain:DegradeSlot 插槽位置
NodeSelectorSlot
→ ClusterBuilderSlot
→ LogSlot
→ StatisticSlot
→ SystemSlot
→ FlowSlot
→ AuthoritySlot
→ DegradeSlot ← 降级判断
5. DegradeSlot:执行降级逻辑
类路径:com.alibaba.csp.sentinel.slots.block.degrade.DegradeSlot
核心代码:
public void entry(Context context, ResourceWrapper resource, ...) throws Throwable {
List<DegradeRule> rules = DegradeRuleManager.getRules(resource.getName());
for (DegradeRule rule : rules) {
rule.passCheck(context, resource, ...);
}
fireEntry(context, resource, ...); // 向下传递
}
读取所有与资源匹配的降级规则
执行
rule.passCheck()
进行判断若不满足 → 抛出
DegradeException
6. DegradeRule.passCheck(): 降级判断核心逻辑
类路径:com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule
public boolean passCheck(Context context, ResourceWrapper resource, ...) {
if (cut) {
if (currentTime - cutTime < timeWindow) {
throw new DegradeException(...); // 降级中,直接拒绝
} else {
cut = false; // 时间窗结束,恢复
}
}
// 根据 grade 选择不同策略
switch (grade) {
case DEGRADE_GRADE_RT: // 平均响应时间
if (rt > count) && requestQps > minRequestAmount
cut(); throw DegradeException;
case DEGRADE_GRADE_EXCEPTION_RATIO: // 异常比例
if (exceptionQps / totalQps > count) && totalQps > minRequestAmount
cut(); throw DegradeException;
case DEGRADE_GRADE_EXCEPTION_COUNT:
if (exceptionQps > count)
cut(); throw DegradeException;
}
return true;
}
7. 降级三种策略详解
类型 | grade 常量 | 触发条件 |
---|---|---|
慢调用比例降级 | DEGRADE_GRADE_RT |
最近统计窗口内,RT 超过阈值,且请求数达标 |
异常比例降级 | DEGRADE_GRADE_EXCEPTION_RATIO |
异常率 > 阈值,且总请求数达标 |
异常数降级 | DEGRADE_GRADE_EXCEPTION_COUNT |
统计窗口内,异常数大于阈值 |
示例:异常比例降级
if (exceptionQps / totalQps > count) {
cut(); // 设置 cut = true, 进入熔断状态
throw new DegradeException();
}
方法:cut()
this.cut = true;
this.cutTime = currentTime;
进入熔断状态,passCheck()
中将直接抛出异常。
8. 降级状态与恢复机制
设置了
cut = true
时进入熔断状态每次请求会判断当前时间是否超过
cutTime + timeWindow
若是:自动恢复
否则:仍然抛出
DegradeException
Sentinel 不需要人工干预,自动判断恢复时机。
9. 上层 fallback 降级处理
手动处理:
try (Entry entry = SphU.entry("myService")) {
return myRealCall();
} catch (DegradeException ex) {
return "服务降级";
}
Spring 注解方式:
@SentinelResource(value = "myService", blockHandler = "handleBlock")
public String myService() {
...
}
public String handleBlock(BlockException ex) {
return "降级返回";
}
10. 降级统计数据来源:Node + Metric
每个资源的 Node
中包含指标统计结构:
Metric metric = ClusterNode.metric;
metric.passQps();
metric.exceptionQps();
metric.avgRt();
底层使用 LeapArray
实现滑动窗口:
将统计周期切分为 N 个窗口(如 1s 被分成 5 个 200ms 窗口)
实时更新每个小窗口的统计值
基于窗口聚合得出当前
avgRt
,exceptionQps
11. 降级规则配置方式
代码方式配置:
DegradeRule rule = new DegradeRule();
rule.setResource("myService");
rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);
rule.setCount(0.5); // 异常率 50%
rule.setTimeWindow(10); // 熔断 10s
rule.setMinRequestAmount(5); // 最小请求量
DegradeRuleManager.loadRules(Collections.singletonList(rule));
也可通过 Sentinel Dashboard / Nacos 推送 JSON 规则。
12. 全流程调用链总结
用户请求
↓
SphU.entry("资源名")
↓
SlotChain → DegradeSlot
↓
DegradeRuleManager.getRules()
↓
执行每条 rule.passCheck()
↓
是否 cut=true?
↓ ↓
是 否
↓ 继续策略判断
抛异常 是否满足降级条件?
↓ ↓
是 否
↓ ↓
cut() 正常放行
抛出异常
13. 关键类汇总
类 / 组件 | 作用 |
---|---|
SphU.entry() |
Sentinel 拦截入口 |
DegradeSlot |
降级判断插槽 |
DegradeRule |
单条降级规则 |
DegradeRuleManager |
管理和下发所有规则 |
ClusterNode |
指标统计器 |
LeapArray |
滑动窗口统计结构 |
DegradeException |
被降级时抛出的异常 |
SentinelResource |
注解式降级入口 |
14. 总结
Sentinel 降级机制通过:
客户端请求拦截(SphU.entry)
Slot 链中的
DegradeSlot
执行降级判断根据配置的
DegradeRule
判断是否进入熔断状态若触发熔断,设置
cut=true
,在timeWindow
时间内拒绝所有请求抛出
DegradeException
,由上层 fallback 处理熔断窗口过期后,自动恢复
四、深入剖析 Sentinel 如何完成限流
从客户端请求到限流生效的完整流程,包括:
请求入口(如 Feign、RestTemplate)
核心执行链(SlotChain)
限流核心类(FlowSlot、FlowRule)
令牌桶算法与统计结构
异常处理与 fallback
限流规则配置
限流后的恢复机制
1. 总体流程图
客户端请求
↓
Sentinel Resource Entry(SphU.entry("资源名"))
↓
SlotChain(插槽链)执行
↓
FlowSlot → FlowRuleManager
↓
Token 校验(判断是否通过)
↓ ↓
通过 不通过
↓ ↓
正常执行 抛出 FlowException → fallback
2. 请求入口:SphU.entry()
Sentinel 使用 SphU.entry("resourceName")
作为资源调用的拦截入口。
例如:
try (Entry entry = SphU.entry("orderService")) {
// 执行业务逻辑
} catch (BlockException e) {
// 被限流
}
核心方法路径:
com.alibaba.csp.sentinel.SphU.entry()
→ CtSph#entry()
→ SlotChain.entry() ← 进入责任链执行
3. SlotChain 执行链
Sentinel 内部有一条 ProcessorSlotChain
,每个资源调用会依次通过这些插槽。
NodeSelectorSlot → ClusterBuilderSlot → StatisticSlot → FlowSlot → ...
限流控制核心插槽是:FlowSlot
4. FlowSlot:限流执行核心
类路径:com.alibaba.csp.sentinel.slots.block.flow.FlowSlot
方法:
@Override
public void entry(Context context, ResourceWrapper resource, ...)
throws Throwable {
List<FlowRule> rules = FlowRuleManager.getRules(resource.getName());
for (FlowRule rule : rules) {
if (!rule.passCheck(...)) {
throw new FlowException(...); // 被限流
}
}
fireEntry(...); // 继续传递给下一个 slot
}
即:
遍历所有限流规则(支持多个)
调用
rule.passCheck(...)
判断是否允许通过
5. FlowRule.passCheck(): 判断是否限流
类路径:com.alibaba.csp.sentinel.slots.block.flow.FlowRule
public boolean passCheck(...) {
Node node = selectNodeByStrategy(...); // 根据限流策略选择 Node(统计节点)
return controller.canPass(node, acquireCount);
}
限流控制核心接口:
FlowRule.setControlBehavior()
支持几种限流方式:
controlBehavior | 限流方式 | 描述 |
---|---|---|
0 | 快速失败(默认) | 超过阈值立即拒绝 |
1 | 排队等待 | 类似漏桶算法,匀速通过 |
2 | WarmUp(预热) | 限流阈值逐步提升(冷启动) |
6. FlowController.canPass(): 限流判断核心
每种限流行为都由一个 TrafficShapingController
实现,比如:
1. DefaultController
(快速失败)
public boolean canPass(Node node, int acquireCount) {
double curQps = node.passQps();
return (curQps + acquireCount) <= count;
}
node.passQps()
:获取当前每秒通过的请求数(滑动窗口统计)如果超过设置的 QPS 阈值
count
→ 拒绝
2. RateLimiterController
(排队等待)
public boolean canPass(...) {
long waitTime = ...; // 计算等待时间
if (waitTime > maxQueueingTimeMs) {
return false; // 超过最大等待时间,拒绝
}
sleep(waitTime);
return true;
}
7. 节点统计机制:如何知道 QPS?
Sentinel 中的 Node
是统计的核心:
每个资源都有一个
ClusterNode
和DefaultNode
Node.passQps()
是基于滑动时间窗口统计的:
class Metric {
private long[] pass; // 每个时间窗口内通过请求数
private long windowLengthInMs = 1000;
}
Sentinel 使用 滑动窗口(LeapArray) 实现:
将 1s 分成若干小窗口(如 200ms × 5)
统计每个小窗口的请求数
实时计算 QPS
8. 被限流后如何处理?
如果 FlowSlot
抛出 FlowException
,调用方可自定义 fallback。
示例(Spring Cloud):
@SentinelResource(value = "orderService", blockHandler = "handleBlock")
public String order() {
return restTemplate.getForObject(...);
}
public String handleBlock(BlockException ex) {
return "系统繁忙,请稍后重试";
}
9. FlowRule 配置方式
可通过代码动态加载:
FlowRule rule = new FlowRule();
rule.setResource("orderService");
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
rule.setCount(100); // 100 QPS
FlowRuleManager.loadRules(Collections.singletonList(rule));
或通过 Dashboard / Nacos 推送 JSON 配置。
10. 限流恢复机制
限流并不持久存在,而是实时动态判断:
每秒重新计算统计窗口(滑动时间窗)
当前 QPS 低于阈值 → 自动放行
11. 全流程调用图
1. 客户端请求
2. 调用 SphU.entry("orderService")
3. 进入 SlotChain
4. 到达 FlowSlot
5. 读取 FlowRuleManager 中的规则
6. 执行 rule.passCheck()
→ 获取当前 QPS(passQps)
→ 判断是否超过 count
7. 如果超限:
→ 抛出 FlowException
→ 上层 fallback
8. 如果未超限:
→ fireEntry() 执行后续逻辑
12. 总结对照表
模块 | 说明 |
---|---|
SphU.entry() |
请求入口 |
SlotChain |
插槽责任链 |
FlowSlot |
限流判断插槽 |
FlowRuleManager |
规则持有者 |
FlowRule |
每条规则定义(阈值、策略) |
TrafficShapingController |
限流算法策略(令牌桶、漏桶等) |
Node/ClusterNode |
QPS 统计结构(滑动时间窗) |
FlowException |
限流触发异常 |
fallback |
限流后的兜底处理 |
五、Sentinel 整合 Spring Boot 的完整案例
案例涵盖:
✅ 基本接入 Sentinel
✅ 定义资源并实现 限流
✅ 配置 熔断降级(异常比例、慢调用)
✅ 自定义 fallback 处理
✅ 支持通过 Sentinel Dashboard 管理规则
1. 引入依赖(Maven)
<dependencies>
<!-- Sentinel 核心依赖 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
<version>1.8.6</version>
</dependency>
<!-- Sentinel 与 Spring Boot 集成适配 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>2021.1</version>
</dependency>
<!-- 可选:用于 feign 支持 sentinel(如用 openFeign) -->
<!--
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel</artifactId>
<version>2021.1</version>
</dependency>
-->
</dependencies>
💡 Sentinel 与 Spring Cloud Alibaba 的版本必须匹配你的 Spring Boot 版本。
2. application.yml 配置
server:
port: 8080
spring:
application:
name: sentinel-demo
# Sentinel 配置
spring:
cloud:
sentinel:
transport:
dashboard: localhost:8080 # Sentinel Dashboard 地址
port: 8719 # 与 Dashboard 通信的端口(需开放)
eager: true # 应用启动即注册资源(非懒加载)
3. 创建控制器并定义资源(限流 & 熔断)
@RestController
public class DemoController {
/**
* 示例 1:限流 + fallback
*/
@GetMapping("/hello")
@SentinelResource(value = "hello", blockHandler = "handleHelloBlock")
public String hello(@RequestParam(required = false) String name) {
return "Hello " + name;
}
public String handleHelloBlock(String name, BlockException ex) {
return "【限流】服务繁忙,请稍后再试";
}
/**
* 示例 2:模拟异常触发降级
*/
@GetMapping("/degrade")
@SentinelResource(value = "degradeTest", fallback = "degradeFallback")
public String degradeTest(@RequestParam(required = false) Integer code) {
if (code != null && code == 1) {
throw new RuntimeException("模拟异常");
}
return "降级接口:正常访问";
}
public String degradeFallback(Integer code, Throwable ex) {
return "【熔断降级】系统异常,请稍后再试";
}
}
4. 启动 Sentinel Dashboard(可选)
如果你未运行 Dashboard:
java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -jar sentinel-dashboard-1.8.6.jar
打开控制台:
访问 http://localhost:8080,登录账号密码:sentinel/sentinel
添加你的应用:
输入名称如sentinel-demo
,点击“新增应用”
5. 手动配置限流规则(代码方式)
@PostConstruct
public void initFlowRules() {
// 限流规则
FlowRule rule = new FlowRule();
rule.setResource("hello"); // 资源名
rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // QPS模式
rule.setCount(2); // 每秒最多 2 次访问
FlowRuleManager.loadRules(Collections.singletonList(rule));
// 熔断规则(异常比例)
DegradeRule degradeRule = new DegradeRule();
degradeRule.setResource("degradeTest");
degradeRule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);
degradeRule.setCount(0.5); // 异常比例阈值
degradeRule.setTimeWindow(10); // 熔断时间窗(秒)
degradeRule.setMinRequestAmount(5); // 最小请求数
DegradeRuleManager.loadRules(Collections.singletonList(degradeRule));
}
✅ 可以用
DegradeRule.setGrade(DEGRADE_GRADE_RT)
实现慢调用降级。
6. 测试验证
测试限流:连续访问
/hello?name=jeer
超过 QPS 限制 → 返回限流 fallback测试熔断:访问
/degrade?code=1
多次抛出异常 → 触发熔断控制台中可以查看 QPS、异常统计、规则配置
7. 项目结构清单(示例)
src
└── main
├── java
│ └── com.example.sentinel
│ ├── SentinelDemoApplication.java
│ └── controller
│ └── DemoController.java
└── resources
└── application.yml
8. Sentinel 注解能力小结
注解 | 说明 |
---|---|
@SentinelResource |
定义资源名、异常处理方法 |
blockHandler |
限流、熔断、系统负载时的处理方法 |
fallback |
调用异常时的兜底方法 |
defaultFallback |
全局 fallback |
9. 可扩展项(进阶建议)
✅ 限流支持:热点参数限流、URL 分组限流
✅ 降级策略:支持异常数、响应时间等
✅ 整合 Feign:FeignClient + Sentinel 支持 fallback
✅ 支持动态规则推送:基于 Nacos、Apollo
六、Sentinel + Nacos 实现动态规则配置的完整案例
案例包括:
✅ Spring Boot 整合 Sentinel
✅ Sentinel Dashboard 配置说明
✅ Sentinel 与 Nacos 的动态规则持久化集成
✅ 在 Nacos 中维护限流、降级等规则
✅ 动态推送规则实时生效
1. 技术栈版本要求
技术组件 | 版本建议 |
---|---|
Spring Boot | 2.3.x / 2.6.x 等 |
Sentinel | 1.8.6+ |
Sentinel Dashboard | 1.8.6+ |
Nacos | 2.x |
Spring Cloud Alibaba | 2021.x 或 2022.x |
2. Maven 依赖
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2021.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- Sentinel Starter -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- Sentinel Nacos DataSource 支持 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
<version>1.8.6</version>
</dependency>
</dependencies>
3. application.yml 配置
spring:
application:
name: sentinel-nacos-demo
cloud:
nacos:
server-addr: 127.0.0.1:8848
config:
namespace: public
discovery:
namespace: public
sentinel:
transport:
dashboard: localhost:8080 # Sentinel Dashboard 地址
port: 8719 # 与 Dashboard 通讯端口
datasource:
flow:
nacos:
server-addr: ${spring.cloud.nacos.server-addr}
data-id: sentinel-demo-flow-rules
group-id: DEFAULT_GROUP
data-type: json
rule-type: flow
4. 控制器示例(定义限流资源)
@RestController
public class DemoController {
@GetMapping("/hello")
@SentinelResource(value = "hello", blockHandler = "handleHello")
public String hello() {
return "Hello Sentinel + Nacos";
}
public String handleHello(BlockException ex) {
return "限流啦~";
}
}
5. 配置中心:Nacos 中创建限流规则
打开 Nacos 控制台:
地址:http://localhost:8848/nacos
新建配置项:
Data ID:
sentinel-demo-flow-rules
Group:
DEFAULT_GROUP
内容格式:JSON
示例内容(限流规则):
[
{
"resource": "hello",
"limitApp": "default",
"grade": 1,
"count": 1.0,
"strategy": 0,
"controlBehavior": 0
}
]
字段说明:
字段 | 含义 |
---|---|
resource |
资源名,对应 @SentinelResource(value) |
grade |
阈值类型:1=QPS,0=并发 |
count |
阈值(如 QPS = 1) |
controlBehavior |
控制行为:0=直接拒绝 |
limitApp |
限制来源:default = 所有 |
strategy |
流控模式:0=直接 |
✅ 支持流控、降级、热点参数、系统规则等类型的配置(rule-type 决定)
6. Dashboard 配置 Sentinel 动态规则数据源(可选)
如果你需要 Sentinel 控制台推送规则到 Nacos:
修改 sentinel-dashboard 的 application.properties
:
# 配置控制台自身访问地址
server.port=8080
# 配置 Nacos 数据源
sentinel.datasource.ds1.nacos.server-addr=127.0.0.1:8848
sentinel.datasource.ds1.nacos.data-id=sentinel-demo-flow-rules
sentinel.datasource.ds1.nacos.group-id=DEFAULT_GROUP
sentinel.datasource.ds1.nacos.data-type=json
sentinel.datasource.ds1.nacos.rule-type=flow
启动 dashboard:
java -Dserver.port=8080 -jar sentinel-dashboard-1.8.6.jar
7. 结果验证
1. 启动 nacos → dashboard → spring boot 应用
确保:
nacos: http://localhost:8848
dashboard: http://localhost:8080
2. 压测访问 /hello
超过 1 QPS 之后返回:
限流啦~
说明配置从 Nacos 下发并生效。
8. 支持的动态规则类型
rule-type | 功能 | 示例配置(data-id 可配) |
---|---|---|
flow |
流控限流 | sentinel-demo-flow-rules |
degrade |
熔断降级 | sentinel-demo-degrade-rules |
param-flow |
热点参数 | sentinel-demo-param-rules |
system |
系统规则 | sentinel-demo-system-rules |
authority |
黑白名单 | sentinel-demo-authority-rules |
每种类型都支持通过 spring.cloud.sentinel.datasource.XXX
进行接入。
9. 完整项目结构(参考)
sentinel-nacos-demo
├── src
│ ├── main
│ │ ├── java
│ │ │ └── com.example.sentinel
│ │ │ ├── SentinelNacosDemoApplication.java
│ │ │ └── controller
│ │ │ └── DemoController.java
│ │ └── resources
│ │ └── application.yml