ToB企服应用市场:ToB评测及商务社交产业平台
标题:
Sentinel
[打印本页]
作者:
守听
时间:
2025-2-18 10:51
标题:
Sentinel
一、Sentinel 简介
Sentinel 是阿里巴巴开源的分布式体系流量防卫组件,提供
流量控制
、
熔断降级
、
体系自顺应保护
等功能。作为 Spring Cloud Alibaba 核心组件,广泛应用于电商秒杀、直播等高并发场景,防止体系因突发流量瓦解。
核心特性
流量控制
:基于 QPS/并发数/调用关系多维度限流
熔断降级
:自动检测慢调用/异常比例触发熔断
热门防护
:针对高频参数自动限流
体系保护
:根据体系负载动态调整流量
实时监控
:秒级监控数据可视化
二、环境预备
1. 控制台安装
# 下载最新版本(以 1.8.5 为例)
wget https://github.com/alibaba/Sentinel/releases/download/1.8.5/sentinel-dashboard-1.8.5.jar
# 启动控制台(默认端口 8080)
java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -jar sentinel-dashboard-1.8.5.jar
复制代码
访问 http://localhost:8080(默认账号暗码:sentinel/sentinel)
2. Spring Boot 集成
<!-- pom.xml -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>2022.0.0.0</version>
</dependency>
复制代码
# application.yml
spring:
cloud:
sentinel:
transport:
dashboard: localhost:8080
eager: true # 立即注册到控制台
复制代码
三、核心功能实战
1. 流量控制
定义资源
:
@GetMapping("/order")
@SentinelResource(value = "createOrder", blockHandler = "handleFlowLimit")
public String createOrder() {
return "订单创建成功";
}
// 流控处理函数
public String handleFlowLimit(BlockException ex) {
return "系统繁忙,请稍后再试!";
}
复制代码
控制台配置
:
在控制台找到对应资源
新增流控规则:QPS=2(阈值类型选QPS,单机阈值=2)
使用 JMeter 压测验证效果
2. 熔断降级
@SentinelResource(value = "paymentService",
fallback = "paymentFallback",
exceptionsToIgnore = {IllegalArgumentException.class})
public String processPayment(String orderId) {
// 业务逻辑
}
// 降级处理函数
public String paymentFallback(String orderId, Throwable t) {
return "支付服务暂时不可用,请稍后重试";
}
复制代码
熔断规则配置
:
熔断战略:慢调用比例
最大 RT:500ms
比例阈值:0.5(50%)
熔断时长:5秒
最小哀求数:5
3. 热门参数限流
@GetMapping("/product")
@SentinelResource(value = "queryProduct", blockHandler = "paramFlowHandler")
public String getProduct(@RequestParam("pid") String productId) {
return "商品详情";
}
// 热点参数处理
public String paramFlowHandler(String productId, BlockException ex) {
return "当前商品访问火爆,请稍后再试";
}
复制代码
参数规则配置
:
ParamFlowRule rule = new ParamFlowRule("queryProduct")
.setParamIdx(0) // 参数索引
.setCount(10); // 阈值
ParamFlowRuleManager.loadRules(Collections.singletonList(rule));
复制代码
四、高级配置
1. 规则持久化(Nacos 集成)
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
复制代码
spring:
cloud:
sentinel:
datasource:
ds1:
nacos:
server-addr: localhost:8848
dataId: sentinel-rules
groupId: DEFAULT_GROUP
rule-type: flow
复制代码
2. 集群流控
// 启动 Token Server
ClusterServerConfigManager.loadServerNamespaceSet(Collections.singleton("App-Cluster"));
复制代码
# token-server 配置
spring:
cloud:
sentinel:
transport:
client-ip: 192.168.1.10
cluster-server:
port: 18730
复制代码
五、生产实践发起
压测基准
:通过 curl http://localhost:8719/tree?type=root 获取资源树
监控集成
:对接 Prometheus + Grafana
动态调整
:使用 Sentinel 的 HTTP API 实时修改规则
异常处理
:同一实现 BlockExceptionHandler 接口
完整示例代码:Sentinel Demo 项目
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/)
Powered by Discuz! X3.4