返回
Sentinel 实现智能流控之 @SentinelResource 注解
后端
2023-12-27 15:31:01
Sentinel 简介
Sentinel 是一个轻量级、高性能、可扩展的流量控制组件,用于保护系统和服务的可用性。Sentinel 提供了丰富的流控规则,可以实现基于 QPS、并发线程数、热点参数等维度的流控。Sentinel 还支持降级、系统保护等功能,可以帮助系统在出现故障或异常时,进行自我保护,避免系统崩溃。
Sentinel 的核心流控规则包括:
- QPS 限流:对接口的每秒请求数进行限制。
- 并发线程数限流:对接口同时并发处理的线程数进行限制。
- 热点参数限流:对接口的请求参数进行限制,当请求参数中的某个值超过一定阈值时,进行限流。
- 降级:当某个服务出现故障或异常时,自动将流量切到其他正常的服务上。
- 系统保护:当系统负载过高时,自动熔断部分服务,避免系统崩溃。
使用 Sentinel 实现流控
- 导入 Sentinel 依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel</artifactId>
<version>2.2.8.RELEASE</version>
</dependency>
- 配置 Sentinel 规则
@Configuration
public class SentinelConfiguration {
@Bean
public SentinelResourceAspect sentinelResourceAspect() {
return new SentinelResourceAspect();
}
@Bean
public FlowRuleManager flowRuleManager() {
List<FlowRule> flowRules = new ArrayList<>();
// QPS 限流规则
FlowRule qpsFlowRule = new FlowRule();
qpsFlowRule.setResource("hello");
qpsFlowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
qpsFlowRule.setCount(10);
flowRules.add(qpsFlowRule);
// 并发线程数限流规则
FlowRule threadFlowRule = new FlowRule();
threadFlowRule.setResource("hello");
threadFlowRule.setGrade(RuleConstant.FLOW_GRADE_THREAD);
threadFlowRule.setCount(10);
flowRules.add(threadFlowRule);
// 热点参数限流规则
FlowRule paramFlowRule = new FlowRule();
paramFlowRule.setResource("hello");
paramFlowRule.setGrade(RuleConstant.FLOW_GRADE_PARAM);
paramFlowRule.setParamIdx(0);
paramFlowRule.setParamFlowItemList(Arrays.asList(new ParamFlowItem("user-1", 10), new ParamFlowItem("user-2", 20)));
flowRules.add(paramFlowRule);
return new FlowRuleManager(flowRules);
}
}
- 使用 @SentinelResource 注解
@RestController
public class HelloController {
@SentinelResource(value = "hello", blockHandler = "helloBlockHandler")
@GetMapping("/hello")
public String hello(@RequestParam String name) {
return "Hello, " + name + "!";
}
public String helloBlockHandler(String name, BlockException e) {
return "Sorry, " + name + ", the system is busy now. Please try again later.";
}
}
使用 Sentinel 实现降级
- 导入 Sentinel 依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel</artifactId>
<version>2.2.8.RELEASE</version>
</dependency>
- 配置 Sentinel 规则
@Configuration
public class SentinelConfiguration {
@Bean
public SentinelResourceAspect sentinelResourceAspect() {
return new SentinelResourceAspect();
}
@Bean
public DegradeRuleManager degradeRuleManager() {
List<DegradeRule> degradeRules = new ArrayList<>();
// 降级规则
DegradeRule degradeRule = new DegradeRule();
degradeRule.setResource("hello");
degradeRule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
degradeRule.setCount(10);
degradeRule.setTimeWindow(10);
degradeRules.add(degradeRule);
return new DegradeRuleManager(degradeRules);
}
}
- 使用 @SentinelResource 注