一、Sentinel概述
Sentinel是阿里巴巴开源的流量控制组件,提供流量控制、熔断降级、系统负载保护等功能,是保障微服务稳定性的重要工具。
1.1 Sentinel核心概念
- 资源:Sentinel保护的基本单位,可以是方法、代码块或API接口
- 规则:定义如何保护资源的策略,包括流控规则、降级规则、热点规则等
- 上下文:资源调用的上下文环境,包含调用链信息
- Entry:资源访问的入口,用于创建和销毁资源调用上下文
1.2 Sentinel架构
Sentinel架构组件:
┌─────────────────────────────────────────┐
│ Sentinel Dashboard │
├─────────────────────────────────────────┤
│ 规则管理 │ 监控展示 │ 集群流控 │
├─────────────────────────────────────────┤
│ Sentinel Core │
├─────────────────────────────────────────┤
│ Slot Chain │ Statistic │ Rule │
└─────────────────────────────────────────┘
二、Sentinel安装部署
2.1 Dashboard部署
# 下载Sentinel Dashboard
wget https://github.com/alibaba/Sentinel/releases/download/1.8.6/sentinel-dashboard-1.8.6.jar
# 启动Dashboard
java -Dserver.port=8080 \
-Dcsp.sentinel.dashboard.server=fgedudb:8080 \
-Dproject.name=sentinel-dashboard \
-jar sentinel-dashboard-1.8.6.jar
# 后台启动
nohup java -Dserver.port=8080 \
-Dcsp.sentinel.dashboard.server=fgedudb:8080 \
-Dproject.name=sentinel-dashboard \
-jar sentinel-dashboard-1.8.6.jar > sentinel.log 2>&1 &
# 访问Dashboard
# http://fgedudb:8080
# 默认账号:sentinel/sentinel
# 输出示例
INFO: Starting Sentinel Dashboard…
INFO: Dashboard server started at port 8080
INFO: Login page: http://fgedudb:8080
INFO: Starting Sentinel Dashboard…
INFO: Dashboard server started at port 8080
INFO: Login page: http://fgedudb:8080
2.2 客户端集成
<!-- Maven依赖 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
<version>1.8.6</version>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-transport-simple-http</artifactId>
<version>1.8.6</version>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-annotation-aspectj</artifactId>
<version>1.8.6</version>
</dependency>
# 启动参数配置
-Dcsp.sentinel.dashboard.server=192.168.1.100:8080
-Dproject.name=order-service
-Dcsp.sentinel.api.port=8719
三、流量控制
3.1 QPS流量控制
// 定义QPS流控规则
List<FlowRule> rules = new ArrayList<>();
FlowRule rule = new FlowRule();
rule.setResource("getUserInfo");
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
rule.setCount(100); // QPS限制为100
rules.add(rule);
FlowRuleManager.loadRules(rules);
// 使用Sentinel保护资源
Entry entry = null;
try {
entry = SphU.entry("getUserInfo");
// 业务逻辑
return userService.getUserInfo(userId);
} catch (BlockException e) {
// 被限流处理
return "系统繁忙,请稍后重试";
} finally {
if (entry != null) {
entry.exit();
}
}
// 使用注解方式
@SentinelResource(value = "getUserInfo", blockHandler = "handleBlock")
public UserInfo getUserInfo(Long userId) {
return userService.getUserInfo(userId);
}
public UserInfo handleBlock(Long userId, BlockException e) {
return new UserInfo(-1L, "系统繁忙");
}
3.2 线程数流量控制
// 线程数流控规则
FlowRule threadRule = new FlowRule();
threadRule.setResource("processOrder");
threadRule.setGrade(RuleConstant.FLOW_GRADE_THREAD);
threadRule.setCount(50); // 最大并发线程数50
FlowRuleManager.loadRules(Collections.singletonList(threadRule));
// 查看当前线程数
curl "http://fgedudb:8719/tree"
# 输出示例
EntranceNode: machine-root
|-EntranceNode: order-service
|-Node: processOrder
|-thread: 45, qps: 120.0
3.3 流控效果
// 直接拒绝(默认)
FlowRule directRule = new FlowRule();
directRule.setResource("api");
directRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
directRule.setCount(100);
directRule.setStrategy(RuleConstant.STRATEGY_DIRECT);
// 冷启动(Warm Up)
FlowRule warmUpRule = new FlowRule();
warmUpRule.setResource("api");
warmUpRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
warmUpRule.setCount(100);
warmUpRule.setWarmUpPeriodSec(10); // 预热时间10秒
// 匀速排队
FlowRule rateLimiterRule = new FlowRule();
rateLimiterRule.setResource("api");
rateLimiterRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
rateLimiterRule.setCount(100);
rateLimiterRule.setRater(RateLimiterStrategy.RATE_LIMITER);
rateLimiterRule.setMaxQueueingTimeMs(500); // 最大排队时间500ms
FlowRuleManager.loadRules(Arrays.asList(directRule, warmUpRule, rateLimiterRule));
四、熔断降级
4.1 慢调用比例熔断
// 慢调用比例熔断规则
DegradeRule slowCallRule = new DegradeRule("slowApi");
slowCallRule.setGrade(CircuitBreakerStrategy.SLOW_REQUEST_RATIO.getType());
slowCallRule.setCount(500); // 慢调用阈值500ms
slowCallRule.setSlowRatioThreshold(0.5); // 慢调用比例阈值50%
slowCallRule.setMinRequestAmount(10); // 最小请求数
slowCallRule.setStatIntervalMs(10000); // 统计时长10秒
slowCallRule.setTimeWindow(30); // 熔断时长30秒
DegradeRuleManager.loadRules(Collections.singletonList(slowCallRule));
// 使用注解
@SentinelResource(value = "slowApi",
blockHandler = "handleDegrade",
fallback = "handleFallback")
public Result slowApi(Request request) {
return processRequest(request);
}
public Result handleDegrade(Request request, BlockException e) {
return Result.fail("服务熔断,请稍后重试");
}
public Result handleFallback(Request request, Throwable t) {
return Result.fail("服务异常: " + t.getMessage());
}
4.2 异常比例熔断
// 异常比例熔断规则
DegradeRule errorRatioRule = new DegradeRule("errorApi");
errorRatioRule.setGrade(CircuitBreakerStrategy.ERROR_RATIO.getType());
errorRatioRule.setCount(0.3); // 异常比例阈值30%
errorRatioRule.setMinRequestAmount(20); // 最小请求数
errorRatioRule.setStatIntervalMs(10000); // 统计时长
errorRatioRule.setTimeWindow(60); // 熔断时长60秒
DegradeRuleManager.loadRules(Collections.singletonList(errorRatioRule));
// 查看熔断状态
curl "http://fgedudb:8719/cnode?id=errorApi"
# 输出示例
id: errorApi
idx: 0
curThreadNum: 0
passQps: 0.0
blockQps: 100.0
totalQps: 100.0
exceptionQps: 30.0
avgRt: 150.0
circuitBreakerStatus: OPEN
id: errorApi
idx: 0
curThreadNum: 0
passQps: 0.0
blockQps: 100.0
totalQps: 100.0
exceptionQps: 30.0
avgRt: 150.0
circuitBreakerStatus: OPEN
4.3 异常数熔断
// 异常数熔断规则
DegradeRule errorCountRule = new DegradeRule("criticalApi");
errorCountRule.setGrade(CircuitBreakerStrategy.ERROR_COUNT.getType());
errorCountRule.setCount(10); // 异常数阈值
errorCountRule.setMinRequestAmount(50); // 最小请求数
errorCountRule.setStatIntervalMs(10000);
errorCountRule.setTimeWindow(120); // 熔断时长120秒
DegradeRuleManager.loadRules(Collections.singletonList(errorCountRule));
五、热点参数限流
5.1 热点参数规则配置
// 热点参数限流规则
ParamFlowRule hotRule = new ParamFlowRule();
hotRule.setResource("getProduct");
hotRule.setParamIdx(0); // 第一个参数
hotRule.setCount(100); // 每秒最多100次
hotRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
// 针对特定参数值设置例外
ParamFlowItem item1 = new ParamFlowItem();
item1.setObject("1001"); // 商品ID为1001
item1.setClassType(int.class.getName());
item1.setCount(500); // 该商品限流500
ParamFlowItem item2 = new ParamFlowItem();
item2.setObject("1002");
item2.setClassType(int.class.getName());
item2.setCount(200);
hotRule.setParamFlowItemList(Arrays.asList(item1, item2));
ParamFlowRuleManager.loadRules(Collections.singletonList(hotRule));
// 使用注解
@SentinelResource(value = "getProduct", blockHandler = "handleHotBlock")
public Product getProduct(@PathVariable Integer productId) {
return productService.getById(productId);
}
public Product handleHotBlock(Integer productId, BlockException e) {
return Product.builder()
.id(productId)
.name("热门商品,请稍后访问")
.build();
}
5.2 热点参数统计
// 查看热点参数统计
curl "http://fgedudb:8719/param?id=getProduct"
# 输出示例
Parameter flow statistics for resource: getProduct
Top parameters:
1001: 450 hits
1002: 180 hits
1003: 95 hits
1004: 88 hits
1005: 76 hits
六、系统自适应保护
6.1 系统规则配置
// 系统自适应保护规则
List<SystemRule> systemRules = new ArrayList<>();
// CPU使用率保护
SystemRule cpuRule = new SystemRule();
cpuRule.setHighestSystemLoad(0.8); // CPU使用率不超过80%
// 系统平均负载保护
SystemRule loadRule = new SystemRule();
loadRule.setHighestSystemLoad(10.0); // 系统负载不超过10
// 平均响应时间保护
SystemRule rtRule = new SystemRule();
rtRule.setAvgRt(500); // 平均响应时间不超过500ms
// 并发线程数保护
SystemRule threadRule = new SystemRule();
threadRule.setMaxThread(500); // 最大并发线程数500
// 入口QPS保护
SystemRule qpsRule = new SystemRule();
qpsRule.setQps(10000); // 入口QPS不超过10000
systemRules.add(cpuRule);
systemRules.add(loadRule);
systemRules.add(rtRule);
systemRules.add(threadRule);
systemRules.add(qpsRule);
SystemRuleManager.loadRules(systemRules);
6.2 系统状态监控
// 获取系统状态
curl "http://fgedudb:8719/systemStatus"
# 输出示例
System Status:
load: 2.5
cpuUsage: 45.2%
totalThread: 150
avgRt: 120ms
qps: 5000
concurrency: 80
七、集群流控
7.1 集群流控配置
// 集群流控规则
FlowRule clusterRule = new FlowRule();
clusterRule.setResource("clusterApi");
clusterRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
clusterRule.setCount(1000); // 集群总QPS限制1000
clusterRule.setClusterMode(true); // 开启集群模式
clusterRule.setClusterConfig(new ClusterFlowConfig()
.setFlowId(1001L) // 规则ID
.setThresholdType(ClusterRuleConfig.FLOW_THRESHOLD_GLOBAL) // 全局阈值
.setFallbackToLocalWhenFail(true) // 降级到本地模式
);
FlowRuleManager.loadRules(Collections.singletonList(clusterRule));
// Token Server配置
ClusterServerConfigManager.loadServerConfig(
new ClusterServerConfig()
.setPort(18730)
.setTransportMode(TransportMode.SOCKET)
.setNamespaceSet(Collections.singleton("app1"))
);
// Token Client配置
ClusterClientConfigManager.loadConfig(
new ClusterClientConfig()
.setServerHost("192.168.1.100")
.setServerPort(18730)
.setRequestTimeout(50)
);
八、规则持久化
8.1 Nacos持久化
<!-- Maven依赖 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
<version>1.8.6</version>
</dependency>
// Nacos数据源配置
String serverAddr = "192.168.1.100:8848";
String groupId = "SENTINEL_GROUP";
String dataId = "order-service-flow-rules";
ReadableDataSource<String, List<FlowRule>> flowRuleDataSource =
new NacosDataSource<>(serverAddr, groupId, dataId,
source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {}));
FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
// 在Nacos中配置规则
curl -X POST "http://192.168.1.100:8848/nacos/v1/cs/configs" \
-d "dataId=order-service-flow-rules" \
-d "group=SENTINEL_GROUP" \
-d "content=[
{
\"resource\": \"getUserInfo\",
\"grade\": 1,
\"count\": 100,
\"strategy\": 0
}
]"
8.2 Apollo持久化
<!-- Maven依赖 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-apollo</artifactId>
<version>1.8.6</version>
</dependency>
// Apollo数据源配置
String namespaceName = "application";
String flowRuleKey = "flow_rules";
ReadableDataSource<String, List<FlowRule>> apolloDataSource =
new ApolloDataSource<>(namespaceName, flowRuleKey, "",
source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {}));
FlowRuleManager.register2Property(apolloDataSource.getProperty());
九、监控与告警
9.1 Prometheus监控集成
<!-- Maven依赖 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-exporter-micrometer</artifactId>
<version>1.8.6</version>
</dependency>
// 配置Micrometer
MeterRegistry meterRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
SentinelMetricsExporter exporter = new SentinelMetricsExporter(meterRegistry);
exporter.start();
// prometheus.yml配置
scrape_configs:
- job_name: 'sentinel'
metrics_path: '/actuator/prometheus'
static_configs:
- targets: ['192.168.1.100:8080']
# 关键监控指标
sentinel_pass_qps # 通过QPS
sentinel_block_qps # 拦截QPS
sentinel_exception_qps # 异常QPS
sentinel_avg_rt # 平均响应时间
sentinel_concurrency # 并发数
9.2 告警规则配置
# Prometheus告警规则
groups:
- name: sentinel_alerts
rules:
- alert: HighBlockQPS
expr: rate(sentinel_block_qps[5m]) > 100
for: 2m
labels:
severity: warning
annotations:
summary: "高拦截QPS告警"
description: "资源 {{ $labels.resource }} 拦截QPS超过100"
- alert: CircuitBreakerOpen
expr: sentinel_circuit_breaker_status == 1
for: 1m
labels:
severity: critical
annotations:
summary: "熔断器打开告警"
description: "资源 {{ $labels.resource }} 熔断器已打开"
- alert: HighAvgRT
expr: sentinel_avg_rt > 1000
for: 3m
labels:
severity: warning
annotations:
summary: "高响应时间告警"
description: "资源 {{ $labels.resource }} 平均响应时间超过1秒"
十、最佳实践
10.1 规则配置建议
| 场景 | 推荐配置 | 说明 |
|---|---|---|
| 核心API | QPS限流 + 熔断降级 | 双重保护 |
| 热点商品 | 热点参数限流 | 精准控制热点 |
| 外部依赖 | 慢调用熔断 | 防止级联故障 |
| 系统保护 | 系统自适应 | 整体保护 |
10.2 常见问题排查
# 查看实时监控数据
curl "http://fgedudb:8719/metric?startTime=1648569600000&endTime=1648573200000"
# 查看规则列表
curl "http://fgedudb:8719/getRules?type=flow"
curl "http://fgedudb:8719/getRules?type=degrade"
# 重置规则
curl "http://fgedudb:8719/clearRules?type=flow"
# 查看调用链
curl "http://fgedudb:8719/tree"
# 查看资源详情
curl "http://fgedudb:8719/cnode?id=getUserInfo"
注意事项:
- 生产环境必须配置规则持久化
- 合理设置熔断恢复时间
- 监控告警及时响应
- 避免过度限流影响业务
十一、总结
Sentinel是微服务架构中保障系统稳定性的重要组件。通过本培训文档,您应该掌握了:
更多视频教程www.fgedu.net.cn
- Sentinel Dashboard的部署和使用
- 流量控制(QPS/线程数)的配置方法
- 熔断降级(慢调用/异常比例/异常数)的实现
- 热点参数限流的使用场景
- 系统自适应保护的配置
- 集群流控和规则持久化
- 监控告警的最佳实践
IT运维培训文档系列 | 第249篇 | Sentinel流量控制培训
本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html
