1.添加依赖
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-annotation-aspectj</artifactId>
<version>1.8.1</version>
</dependency>
2.限流规则配置
application.yml
sentinel:
flow-rules:
resource: RESOURCE_NAME
grade: 0
count: 50
controlBehavior: 0
@Configuration
public class SentinelAspectConfiguration {
@Bean
public SentinelResourceAspect sentinelResourceAspect() {
return new SentinelResourceAspect();
}
}
/**
* 设置流控规则
*/
@PostConstruct
public static void initFlowRules() {
List<FlowRule> flowRules = new ArrayList<>();
FlowRule flowRule = new FlowRule();
flowRule.setResource(RESOURCE_NAME);
flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
flowRule.setCount(10);
flowRules.add(flowRule);
FlowRuleManager.loadRules(flowRules);
}
3.接口限流
@SentinelResource(value = "RESOURCE_NAME",
blockHandler = "blockHandler", // 指定触发限流等规则时执行的方法名
fallback = "fallback" // 指定fallback降级执行的方法名
//blockHandlerClass = ExceptionUtil.class, // 指定blockHandler函数的所在类,如果在当前类可以忽略
//fallbackClass = ExceptionUtil.class, 指定fallback函数所在类,如果在当前类可以忽略
)
@RequestMapping(value = "/test")
public CommonResponse test(@RequestParam String param) {
return new CommonResponse(param);
}
// blockHandler 函数/原方法调用被限流/降级/系统保护的时候调用
public CommonResponse blockHandler(String param, BlockException ex) {
return new CommonResponse("blockHandler");
}
// fallback 函数/原方法调用报错的时候调用
public CommonResponse fallback(String param, Throwable e) {
return new CommonResponse("fallback");
}