1. sentinel简介
随着微服务的流行,服务和服务之间的稳定性变得越来越重要。Sentinel 以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。
2.包引入和配置
本次方案是不引入控制台的限流应用
maven包的引入
1 2 3 4 | <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> </dependency> |
application.yml加一个qps限制
1 2 | qps: limit: 2 |
3.接口限流代码
1.接口代码
1 2 3 4 5 6 7 8 | @RestController public class MyController { @RequestMapping ( "/hello" ) @SentinelResource (value = SentinelRuleConfig.QPS_LIMIT) public String hello(){ return "hello" ; } } |
2.单机全局限流配置类SentinelRuleConfig.class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | @Component public class SentinelRuleConfig implements InitializingBean { @Value ( "${qps.limit}" ) private Integer limit; public final static String QPS_LIMIT = "concurrent_qps_limit" ; @Override public void afterPropertiesSet() { initFlowQpsRule(QPS_LIMIT); } private void initFlowQpsRule(String resource) { List<FlowRule> rules = new ArrayList<>(); FlowRule rule1 = new FlowRule(); rule1.setResource(resource); rule1.setCount(limit); rule1.setGrade(RuleConstant.FLOW_GRADE_QPS); rules.add(rule1); FlowRuleManager.loadRules(rules); } } |
3.拒绝策略
支持自定义异常处理通过blockHandler来定义处理类,我采用的是全局异常处理统一返回固定信息
1 2 3 4 5 6 7 8 9 10 11 | @RestControllerAdvice public class GlobalExceptionHandler{ /** * 限流异常 */ @ExceptionHandler (FlowException. class ) public Result flowExceptionHandler(FlowException ex) { return Result.failed(ex.msg); } } |
4.接口限流测试
已经用jemter或者postman等工具手动测试,发现每秒接口并发超过2的时候会返回我们定义的提示信息。
5. 总结
本文介绍的是sentinel的单机使用场景,不支持集群,不需要引入控制台。目前demo中介绍了一种qps限制策略。可以有其它多种策略可用,根据业务需要自行选定。