Sentinel 速查表
本章提供 Sentinel 常用配置、API 和命令的快速参考,方便开发者在实际工作中快速查找所需信息。
核心依赖
<!-- Sentinel 核心 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
<version>1.8.8</version>
</dependency>
<!-- 注解支持 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-annotation-cdi-interceptor</artifactId>
<version>1.8.8</version>
</dependency>
<!-- 热点参数限流 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-parameter-flow-control</artifactId>
<version>1.8.8</version>
</dependency>
<!-- 控制台通信 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-transport-simple-http</artifactId>
<version>1.8.8</version>
</dependency>
<!-- Nacos 数据源 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
<version>1.8.8</version>
</dependency>
<!-- Spring Cloud Alibaba Sentinel -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>2022.0.0.0</version>
</dependency>
资源定义方式
API 方式
// 基本方式
Entry entry = null;
try {
entry = SphU.entry("resourceName");
// 业务逻辑
} catch (BlockException e) {
// 限流或降级处理
} finally {
if (entry != null) {
entry.exit();
}
}
// 带参数(用于热点参数限流)
Entry entry = SphU.entry("resourceName", EntryType.IN, 1, param1, param2);
// 异步资源
AsyncEntry asyncEntry = SphU.asyncEntry("resourceName");
try {
// 异步业务逻辑
} finally {
asyncEntry.exit();
}
注解方式
@SentinelResource(value = "resourceName",
blockHandler = "handleBlock",
fallback = "handleFallback",
exceptionsToIgnore = {IllegalArgumentException.class})
public String doSomething(String param) {
return "result";
}
// 限流或熔断时的处理方法
public String handleBlock(String param, BlockException e) {
return "blocked";
}
// 业务异常时的降级方法
public String handleFallback(String param, Throwable t) {
return "fallback";
}
注解属性说明:
| 属性 | 说明 |
|---|---|
value | 资源名称 |
blockHandler | 限流/熔断时的处理方法名 |
blockHandlerClass | 处理方法所在的类 |
fallback | 业务异常时的降级方法名 |
fallbackClass | 降级方法所在的类 |
defaultFallback | 默认降级方法名 |
exceptionsToTrace | 需要追踪的异常类型 |
exceptionsToIgnore | 需要忽略的异常类型 |
流量控制规则
规则配置
FlowRule rule = new FlowRule();
rule.setResource("resourceName"); // 资源名
rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // 限流类型:QPS
rule.setCount(100); // 阈值
rule.setStrategy(RuleConstant.STRATEGY_DIRECT); // 策略:直接
rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT); // 效果:直接拒绝
rule.setLimitApp("default"); // 来源
FlowRuleManager.loadRules(Collections.singletonList(rule));
限流类型
| 常量 | 值 | 说明 |
|---|---|---|
FLOW_GRADE_QPS | 1 | QPS 限流 |
FLOW_GRADE_THREAD | 0 | 线程数限流 |
流控策略
| 常量 | 值 | 说明 |
|---|---|---|
STRATEGY_DIRECT | 0 | 直接限流 |
STRATEGY_RELATE | 1 | 关联限流 |
STRATEGY_CHAIN | 2 | 链路限流 |
流控效果
| 常量 | 值 | 说明 |
|---|---|---|
CONTROL_BEHAVIOR_DEFAULT | 0 | 直接拒绝 |
CONTROL_BEHAVIOR_WARM_UP | 1 | 预热模式 |
CONTROL_BEHAVIOR_RATE_LIMITER | 2 | 匀速排队 |
CONTROL_BEHAVIOR_WARM_UP_RATE_LIMITER | 3 | 预热+匀速排队 |
熔断降级规则
规则配置
DegradeRule rule = new DegradeRule("resourceName");
rule.setGrade(CircuitBreakerStrategy.SLOW_REQUEST_RATIO.getType()); // 熔断策略
rule.setCount(500); // 慢调用阈值(ms)或异常比例
rule.setSlowRatioThreshold(0.5); // 慢调用比例阈值
rule.setMinRequestAmount(10); // 最小请求数
rule.setStatIntervalMs(10000); // 统计时长(ms)
rule.setTimeWindow(30); // 熔断时长(秒)
DegradeRuleManager.loadRules(Collections.singletonList(rule));
熔断策略
| 策略 | 说明 |
|---|---|
SLOW_REQUEST_RATIO | 慢调用比例 |
ERROR_RATIO | 异常比例 |
ERROR_COUNT | 异常数 |
热点参数限流
ParamFlowRule rule = new ParamFlowRule();
rule.setResource("resourceName");
rule.setParamIdx(0); // 参数索引(从 0 开始)
rule.setCount(10); // 阈值
rule.setDurationInSec(1); // 统计窗口(秒)
// 参数例外项
ParamFlowItem item = new ParamFlowItem();
item.setObject("vip_user"); // 参数值
item.setClassType(String.class.getName()); // 参数类型
item.setCount(100); // 该值的阈值
rule.setParamFlowItemList(Collections.singletonList(item));
ParamFlowRuleManager.loadRules(Collections.singletonList(rule));
系统保护规则
SystemRule rule = new SystemRule();
rule.setHighestSystemLoad(10.0); // Load1 阈值(仅 Linux/Unix)
rule.setHighestCpuUsage(0.8); // CPU 使用率阈值(0.0-1.0)
rule.setAvgRt(500); // 平均 RT 阈值(ms)
rule.setMaxThread(100); // 最大并发线程数
rule.setQps(1000); // 入口总 QPS 阈值
SystemRuleManager.loadRules(Collections.singletonList(rule));
授权规则
AuthorityRule rule = new AuthorityRule();
rule.setResource("resourceName");
rule.setStrategy(RuleConstant.AUTHORITY_WHITE); // 白名单模式
rule.setLimitApp("app1,app2"); // 来源应用(逗号分隔)
AuthorityRuleManager.loadRules(Collections.singletonList(rule));
| 常量 | 值 | 说明 |
|---|---|---|
AUTHORITY_WHITE | 0 | 白名单 |
AUTHORITY_BLACK | 1 | 黑名单 |
集群限流
依赖
<!-- 集群限流客户端 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-cluster-client-default</artifactId>
<version>1.8.8</version>
</dependency>
<!-- 集群限流服务端 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-cluster-server-default</artifactId>
<version>1.8.8</version>
</dependency>
规则配置
FlowRule rule = new FlowRule();
rule.setResource("resourceName");
rule.setCount(100);
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
rule.setClusterMode(true); // 开启集群限流
ClusterFlowConfig clusterConfig = new ClusterFlowConfig();
clusterConfig.setFlowId(1001L); // 规则 ID
clusterConfig.setThresholdType(ClusterRuleConstant.FLOW_THRESHOLD_AVG_LOCAL); // 阈值模式
clusterConfig.setFallbackToLocalWhenFail(true); // 失败降级
rule.setClusterConfig(clusterConfig);
FlowRuleManager.loadRules(Collections.singletonList(rule));
阈值模式
| 模式 | 值 | 说明 |
|---|---|---|
FLOW_THRESHOLD_AVG_LOCAL | 0 | 单机均摊:总阈值 = 配置值 × client 数量 |
FLOW_THRESHOLD_GLOBAL | 1 | 全局阈值:配置值即为总阈值 |
客户端配置
ClusterClientConfig config = new ClusterClientConfig();
config.setServerHost("192.168.1.100"); // Token Server 地址
config.setServerPort(18730); // Token Server 端口
config.setRequestTimeout(20); // 请求超时(ms)
ClusterClientConfigManager.applyConfig(config);
ClusterStateManager.applyState(ClusterStateManager.CLUSTER_CLIENT);
异步调用
AsyncEntry 基本用法
try {
AsyncEntry entry = SphU.asyncEntry("asyncResource");
doAsync(result -> {
try {
// 处理结果
} finally {
entry.exit(); // 必须在回调中 exit
}
});
} catch (BlockException e) {
// 限流处理
}
异步上下文切换
try {
AsyncEntry entry = SphU.asyncEntry("asyncResource");
doAsync(result -> {
// 切换到异步 Context,用于嵌套资源调用
ContextUtil.runOnContext(entry.getAsyncContext(), () -> {
try {
Entry nested = SphU.entry("nestedResource");
try {
// 业务逻辑
} finally {
nested.exit();
}
} finally {
entry.exit();
}
});
});
} catch (BlockException e) {
// 限流处理
}
Reactor 适配
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-reactor-adapter</artifactId>
<version>1.8.8</version>
</dependency>
return Mono.fromCallable(() -> {
// 业务逻辑
return result;
}).transform(new SentinelReactorTransformer<>("resourceName"));
控制台命令
启动控制台
java -Dserver.port=8080 \
-Dcsp.sentinel.dashboard.server=localhost:8080 \
-Dproject.name=sentinel-dashboard \
-jar sentinel-dashboard-1.8.8.jar
客户端启动参数
-Dcsp.sentinel.dashboard.server=localhost:8080 # 控制台地址
-Dcsp.sentinel.api.port=8719 # 客户端 API 端口
-Dproject.name=my-app # 应用名称
HTTP API
监控数据
# 实时监控数据
curl http://localhost:8719/metric?startTime=1609459200000&endTime=1609459260000
# 资源统计
curl http://localhost:8719/cnode?id=resourceName
# 调用来源统计
curl http://localhost:8719/origin?id=resourceName
规则管理
# 获取规则
curl http://localhost:8719/getRules?type=flow # 流控规则
curl http://localhost:8719/getRules?type=degrade # 熔断规则
curl http://localhost:8719/getRules?type=system # 系统规则
# 设置流控规则
curl -X POST http://localhost:8719/setRules?type=flow -d '[
{"resource":"test","grade":1,"count":10}
]'
其他接口
curl http://localhost:8719/health # 健康检查
curl http://localhost:8719/version # 版本信息
curl http://localhost:8719/tree?type=root # 资源树
Spring Cloud 配置
基础配置
spring:
application:
name: my-service
cloud:
sentinel:
transport:
dashboard: localhost:8080
port: 8719
eager: true # 饥饿加载
web-context-unify: true # Web 上下文统一
filter:
enabled: true
url-patterns: /**
Nacos 数据源
spring:
cloud:
sentinel:
datasource:
flow:
nacos:
server-addr: localhost:8848
dataId: ${spring.application.name}-flow-rules
groupId: SENTINEL_GROUP
rule-type: flow
degrade:
nacos:
server-addr: localhost:8848
dataId: ${spring.application.name}-degrade-rules
groupId: SENTINEL_GROUP
rule-type: degrade
Feign 整合
feign:
sentinel:
enabled: true
常用工具类
Tracer 记录异常
try {
// 业务逻辑
} catch (Exception e) {
Tracer.trace(e); // 记录业务异常,用于异常比例统计
}
ContextUtil 上下文
// 设置上下文和来源
ContextUtil.enter("contextName", "origin");
try {
Entry entry = SphU.entry("resourceName");
// 业务逻辑
entry.exit();
} finally {
ContextUtil.exit();
}
规则管理器
// 获取规则
List<FlowRule> rules = FlowRuleManager.getRules();
// 加载规则
FlowRuleManager.loadRules(rules);
// 注册动态规则源
FlowRuleManager.register2Property(property);
异常类型
| 异常 | 说明 |
|---|---|
FlowException | 流量控制异常 |
DegradeException | 熔断降级异常 |
ParamFlowException | 热点参数限流异常 |
SystemBlockException | 系统保护异常 |
AuthorityException | 授权异常 |
监控指标
| 指标 | 说明 |
|---|---|
passQps | 通过的 QPS |
blockQps | 被拒绝的 QPS |
successQps | 成功的 QPS |
exceptionQps | 异常的 QPS |
rt | 平均响应时间 |
concurrency | 并发线程数 |
最佳实践速查
阈值设置建议
| 场景 | 建议阈值 |
|---|---|
| QPS 限流 | 系统最大 QPS × 0.7-0.8 |
| 线程数限流 | 线程池大小 × 0.7-0.8 |
| 慢调用阈值 | P99 响应时间 × 2-3 |
| 熔断时长 | 30-60 秒 |
| 最小请求数 | 5-10 |
规则优先级(从高到低)
- 系统保护规则
- 授权规则
- 流量控制规则
- 熔断降级规则
- 热点参数限流规则
生产环境检查清单
- 规则持久化配置(Nacos/Apollo)
- 控制台鉴权配置
- 降级逻辑实现
- 监控告警配置
- 日志输出配置
- 压测验证