基于注解的Sentinel限流熔断
依赖
<dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-annotation-aspectj</artifactId><version>1.8.8</version><exclusions><exclusion><groupId>com.alibaba.csp</groupId><artifactId>sentinel-core</artifactId></exclusion></exclusions>
</dependency>
<dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-core</artifactId><version>1.8.8</version>
</dependency>
配置
全局配置
@Configuration
public class SentinelAspectConfiguration {@Beanpublic SentinelResourceAspect sentinelResourceAspect() {return new SentinelResourceAspect();}
}
注入限流熔断规则
@Component
public class SentinelConfig {/* 只需要在nacos中配置flowRule,也可以根据nacos配置动态刷新配置,看情况 */@PostConstructpublic void initFlowRules() {List<FlowRule> flowRules = new ArrayList<>();FlowRule rule = new FlowRule();rule.setResource(SentinelResourceConstant.TEST_API); // 资源名要与 @SentinelResource 的 value 一致rule.setGrade(RuleConstant.FLOW_GRADE_QPS);rule.setCount(1); // QPS 限流阈值FlowRule rul2 = new FlowRule();rul2.setResource(SentinelResourceConstant.HELLO_API); // 资源名要与 @SentinelResource 的 value 一致rul2.setGrade(RuleConstant.FLOW_GRADE_QPS);rul2.setCount(2); // QPS 限流阈值flowRules.add(rule);flowRules.add(rul2);FlowRuleManager.loadRules(flowRules);}
}
服务
@Service
@Slf4j
public class TestService {@Resourceprivate HelloClient helloClient;@SentinelResource(value = SentinelResourceConstant.TEST_API, blockHandler = "blockHandler", blockHandlerClass = ExceptionUtil.class)public String chain(String pa) {return pa + "OKK";}@SentinelResource(value = SentinelResourceConstant.HELLO_API, blockHandler = "blockHandlerForHello", blockHandlerClass = ExceptionUtil.class)public String hello() {return helloClient.hello();}
}
异常
@Slf4j
public class ExceptionUtil {public static String blockHandler(String pa, BlockException ex) {log.error("限流:{}", String.valueOf(ex));return "限流";}public static String blockHandlerForHello(BlockException ex) {log.error("限流:{}", String.valueOf(ex));return "限流";}
}
注意事项
- SentinelResource注解中的value必须和SentinelConfig 中rule的resource保持完全一致
- FlowRule的具体限流指标有多种,可以参考官方文档选择