Sentinel 是阿里巴巴开源的一款 流量控制和熔断降级 框架,主要用于:
概念 | 说明 |
---|---|
资源 (Resource) | 需要保护的代码逻辑(如方法、API) |
规则 (Rule) | 限流、熔断等策略 |
流控 (Flow Control) | 限制 QPS、线程数等 |
熔断 (Circuit Breaker) | 基于响应时间或错误比率触发熔断 |
热点限流 (Hot Param Flow) | 针对特定参数进行限流 |
系统规则 (System Rule) | 保护系统整体资源 |
授权规则 (Authority Rule) | 根据请求来源控制访问 |
在 pom.xml
中添加 Sentinel 依赖:
com.alibaba.cloud
spring-cloud-starter-alibaba-sentinel
Spring Boot 自动整合 Sentinel,无需额外配置。
wget https://github.com/alibaba/Sentinel/releases/download/1.8.6/sentinel-dashboard-1.8.6.jar
java -jar sentinel-dashboard-1.8.6.jar
http://localhost:8080
sentinel
sentinel
在 application.yml
添加 Sentinel 连接控制台:
spring:
application:
name: sentinel-demo
cloud:
sentinel:
transport:
dashboard: localhost:8080
port: 8719 # 本地 Sentinel 客户端通信端口
这样,Sentinel 客户端会自动向控制台注册。
流控规则可以基于 QPS、线程数 等方式进行限流。
在 SentinelController.java
创建受保护的接口:
@RestController
public class SentinelController {
@GetMapping("/test")
@SentinelResource(value = "testResource", blockHandler = "handleBlock")
public String test() {
return "Hello Sentinel";
}
// 限流时的处理方法
public String handleBlock(BlockException ex) {
return "请求被限流";
}
}
在 Sentinel 控制台 添加流控规则:
testResource
测试:
ab -n 10 -c 2 http://localhost:8080/test
如果请求过多,就会返回 "请求被限流"
。
Sentinel 支持基于:
@RestController
public class CircuitBreakerController {
@GetMapping("/slow")
@SentinelResource(value = "slowService", fallback = "fallbackMethod")
public String slowService() throws InterruptedException {
Thread.sleep(2000);
return "Slow Service";
}
// 降级处理
public String fallbackMethod(Throwable t) {
return "降级:服务不可用";
}
}
slowService
针对某个 URL 参数进行限流,例如:
@RestController
public class HotParamController {
@GetMapping("/paramLimit")
@SentinelResource(value = "hotParam", blockHandler = "handleHotParam")
public String hotParam(@RequestParam String type) {
return "Access type: " + type;
}
public String handleHotParam(String type, BlockException ex) {
return "请求被限流:" + type;
}
}
Sentinel 控制台配置
hotParam
type=vip
,QPS 限制 1测试:
curl "http://localhost:8080/paramLimit?type=vip"
在 application.yml
配置:
spring:
cloud:
sentinel:
datasource:
flow:
nacos:
server-addr: localhost:8848
data-id: sentinel-rules
group-id: DEFAULT_GROUP
rule-type: flow
在 Nacos 配置 sentinel-rules
:
[
{
"resource": "testResource",
"limitApp": "default",
"grade": 1,
"count": 2,
"strategy": 0,
"controlBehavior": 0
}
]
这样 Sentinel 规则可以动态调整,无需重启服务。
Sentinel 结合 Spring Cloud Gateway 保护 API 网关:
spring:
cloud:
gateway:
routes:
- id: service1
uri: lb://service1
predicates:
- Path=/service1/**
filters:
- name: Sentinel
在 Sentinel 控制台可以查看 API 访问流量。
功能 | 说明 |
---|---|
流量控制 | 限制 QPS、线程数,防止瞬时流量过载 |
熔断降级 | 避免错误扩散,提高系统稳定性 |
热点限流 | 只对特定参数进行限流 |
动态规则 | 结合 Nacos 实现规则热更新 |
API 网关保护 | 结合 Spring Cloud Gateway 保护微服务 |
如果这篇文章有帮助,欢迎 点赞、收藏、评论,你的支持是我持续更新的动力!