美文网首页Spring专题
Alibaba Sentinel限流功能

Alibaba Sentinel限流功能

作者: 北交吴志炜 | 来源:发表于2020-04-03 20:33 被阅读0次

    前言

    上周经历了合作方未按照约定在客户端进行缓存,以高QPS调用我这边某个接口的问题,当时带来的影响是接口RT变高,当时如果QPS继续增加,将会导致整个应用级别的服务不可用。那么有没有办法,来限制系统的某个服务被调用的QPS,以保护系统不会过载呢?Alibaba Sentinel就是这样的一个产品。本文只介绍限流的功能,Sentinel本身是极其强大的,支持流量控制、熔断降级、系统负载保护,详见官方文档。https://github.com/alibaba/Sentinel/wiki/%E4%BB%8B%E7%BB%8D

    Sentinel如何使用

    引入maven依赖

    <dependency>
                <groupId>com.alibaba.csp</groupId>
                <artifactId>sentinel-core</artifactId>
            </dependency>
            <dependency>
                <groupId>com.alibaba.csp</groupId>
                <artifactId>sentinel-annotation-aspectj</artifactId>
            </dependency>
            <dependency>
                <groupId>com.alibaba.csp</groupId>
                <artifactId>sentinel-transport-simple-http</artifactId>
            </dependency>
    
    1. 若希望在代码块级别限流,使用SphU#entry和Entry#exit将代码块包住即可,这跟很多打点的工具是一样的。
    Entry entry = SphU.entry(resourceName);
    businessCode();
    entry.exit();
    

    初始化流控规则配置见下,流控规则里面的resourceName和Entry初始化的时候一致即可。(Sentinel也支持控制台的方式来配置限流规则)

    private static void initFlowQpsRule() {
            List<FlowRule> rules = new ArrayList<FlowRule>();
            FlowRule rule1 = new FlowRule();
            rule1.setResource(resourceName);
            // set limit qps to 20
            rule1.setCount(20);
            rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
            rule1.setLimitApp("default");
            rules.add(rule1);
            FlowRuleManager.loadRules(rules);
        }
    

    这种在代码块级别硬编码的方式并不是我们的主要场景,更多的时候,我们希望在某个服务,或者某个接口级别进行限流,Sentinel支持注解的方式来配置限流。

    @GetMapping("/hello")
        @SentinelResource("resourceName")
        public String hello() {
            return "Hello";
        }
    

    只需要一个注解,即可添加限流功能。

    Sentinel执行过程

    使用注解来引入限流,其实就是使用了一个aop切面自动帮你初始化一个Entry,执行完毕之后exit。
    详见SentinelResourceAspect

    @Around("sentinelResourceAnnotationPointcut()")
        public Object invokeResourceWithSentinel(ProceedingJoinPoint pjp) throws Throwable {
            Method originMethod = resolveMethod(pjp);
    
            SentinelResource annotation = originMethod.getAnnotation(SentinelResource.class);
            if (annotation == null) {
                // Should not go through here.
                throw new IllegalStateException("Wrong state for SentinelResource annotation");
            }
            String resourceName = getResourceName(annotation.value(), originMethod);
            EntryType entryType = annotation.entryType();
            int resourceType = annotation.resourceType();
            Entry entry = null;
            try {
                entry = SphU.entry(resourceName, resourceType, entryType, pjp.getArgs());
                Object result = pjp.proceed();
                return result;
            } catch (BlockException ex) {
                return handleBlockException(pjp, annotation, ex);
            }finally {
                if (entry != null) {
                    entry.exit(1, pjp.getArgs());
                }
            }
    

    整个限流的核心就在SphU#entry方法,如果被限流拦截,就抛出异常BlockException,不再执行业务代码。
    如果让我们自己实现一套针对服务的限流逻辑,会有两个关键点需要考虑,一个点是,请求进来了,需要去检查当前服务qps,判断是否需要进行拦截;另一个点是统计当前服务的QPS,每处理一个请求,去更新当前服务QPS值。
    SphU#entry方法主要就是做这两个事情。Sentinel对每一个限流的Resouce维护了一个基于滑动窗口的计数器rollingCounterInSecond。

    public class StatisticNode implements Node {
        private transient volatile Metric rollingCounterInSecond;
    }
    

    请求进来之后,先进行canPassCheck,判断是否拦截,判断的逻辑
    curCount 为当前qps,通过滑动窗口计数器rollingCounterInSecond计算得出
    acquireCount 为请求个数,这个数写死的是1
    this.count为限流配置
    如果curCount+1>this.count则返回false,进行拦截,然后抛出FlowException。
    否则通过,去更新计数器rollingCounterInSecond

    public boolean canPass(Node node, int acquireCount, boolean prioritized) {
            int curCount = this.avgUsedTokens(node);
            if ((double)(curCount + acquireCount) > this.count) {
                if (prioritized && this.grade == 1) {
                    long currentTime = TimeUtil.currentTimeMillis();
                    long waitInMs = node.tryOccupyNext(currentTime, acquireCount, this.count);
                    if (waitInMs < (long)OccupyTimeoutProperty.getOccupyTimeout()) {
                        node.addWaitingRequest(currentTime + waitInMs, acquireCount);
                        node.addOccupiedPass(acquireCount);
                        this.sleep(waitInMs);
                        throw new PriorityWaitException(waitInMs);
                    }
                }
    
                return false;
            } else {
                return true;
            }
        }
    

    总结

    Sentinel限流的本质是为每个resource(限流单元)维护一个基于滑动窗口的计数器,当请求进来,先检查计数器,校验是否需要拦截,通过后,更新这个计数器。限流功能可以保证我们的接口在一个可控的负载范围内。不至于因为某一个接口的过载导致整个应用级别的不可用。

    相关文章

      网友评论

        本文标题:Alibaba Sentinel限流功能

        本文链接:https://www.haomeiwen.com/subject/bkxlphtx.html