跳到主要内容

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_QPS1QPS 限流
FLOW_GRADE_THREAD0线程数限流

流控策略

常量说明
STRATEGY_DIRECT0直接限流
STRATEGY_RELATE1关联限流
STRATEGY_CHAIN2链路限流

流控效果

常量说明
CONTROL_BEHAVIOR_DEFAULT0直接拒绝
CONTROL_BEHAVIOR_WARM_UP1预热模式
CONTROL_BEHAVIOR_RATE_LIMITER2匀速排队
CONTROL_BEHAVIOR_WARM_UP_RATE_LIMITER3预热+匀速排队

熔断降级规则

规则配置

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_WHITE0白名单
AUTHORITY_BLACK1黑名单

集群限流

依赖

<!-- 集群限流客户端 -->
<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_LOCAL0单机均摊:总阈值 = 配置值 × client 数量
FLOW_THRESHOLD_GLOBAL1全局阈值:配置值即为总阈值

客户端配置

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

规则优先级(从高到低)

  1. 系统保护规则
  2. 授权规则
  3. 流量控制规则
  4. 熔断降级规则
  5. 热点参数限流规则

生产环境检查清单

  • 规则持久化配置(Nacos/Apollo)
  • 控制台鉴权配置
  • 降级逻辑实现
  • 监控告警配置
  • 日志输出配置
  • 压测验证

参考资料