温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Sentinel中冷启动限流原理WarmUpController是什么

发布时间:2023-04-26 17:15:13 来源:亿速云 阅读:101 作者:iii 栏目:开发技术

本篇内容介绍了“Sentinel中冷启动限流原理WarmUpController是什么”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

冷启动

所谓冷启动,或预热是指,系统长时间处理低水平请求状态,当大量请求突然到来时,并非所有请求都放行,而是慢慢的增加请求,目的时防止大量请求冲垮应用,达到保护应用的目的。

Sentinel中冷启动是采用令牌桶算法实现。

令牌桶算法图例如下:

Sentinel中冷启动限流原理WarmUpController是什么

预热模型

Sentinel中的令牌桶算法,是参照Google Guava中的RateLimiter,在学习Sentinel中预热算法之前,先了解下整个预热模型,如下图:

Sentinel中冷启动限流原理WarmUpController是什么

Guava中预热是通过控制令牌的生成时间,而Sentinel中实现不同:

  • 不控制每个请求通过的时间间隔,而是控制每秒通过的请求数。

  • 在Guava中,冷却因子coldFactor固定为3,上图中②是①的两倍

  • Sentinel增加冷却因子coldFactor的作用,在Sentinel模型中,②是①的(coldFactor-1)倍,coldFactor默认为3,可以通过csp.sentinel.flow.cold.factor参数修改

原理分析

Sentinel中冷启动对应的FlowRule配置为RuleConstant.CONTROL_BEHAVIOR_WARM_UP,对应的Controller为WarmUpController,首先了解其中的属性和构造方法:

  • count:FlowRule中设定的阈值

  • warmUpPeriodSec:系统预热时间,代表上图中的②

  • coldFactor:冷却因子,默认为3,表示倍数,即系统最"冷"时(令牌桶饱和时),令牌生成时间间隔是正常情况下的多少倍

  • warningToken:预警值,表示进入预热或预热完毕

  • maxToken:最大可用token值,计算公式:warningToken+(2*时间*阈值)/(1+因子),默认情况下为warningToken的2倍

  • slope:斜度,(coldFactor-1)/count/(maxToken-warningToken),用于计算token生成的时间间隔,进而计算当前token生成速度,最终比较token生成速度与消费速度,决定是否限流

  • storedTokens:姑且可以理解为令牌桶中令牌的数量

public class WarmUpController implements TrafficShapingController {
	// FlowRule中设置的阈值
    protected double count;
    // 冷却因子,默认为3,通过SentinelConfig加载,可以修改
    private int coldFactor;
    // 预警token数量
    protected int warningToken = 0;
    // 最大token数量
    private int maxToken;
    // 斜率,用于计算当前生成token的时间间隔,即生成速率
    protected double slope;
	// 令牌桶中剩余令牌数
    protected AtomicLong storedTokens = new AtomicLong(0);
    // 最后一次添加令牌的时间戳
    protected AtomicLong lastFilledTime = new AtomicLong(0);
    public WarmUpController(double count, int warmUpPeriodInSec, int coldFactor) {
        construct(count, warmUpPeriodInSec, coldFactor);
    }
    public WarmUpController(double count, int warmUpPeriodInSec) {
        construct(count, warmUpPeriodInSec, 3);
    }
    private void construct(double count, int warmUpPeriodInSec, int coldFactor) {
        if (coldFactor <= 1) {
            throw new IllegalArgumentException("Cold factor should be larger than 1");
        }
        this.count = count;
		// 默认为3
        this.coldFactor = coldFactor;
        // thresholdPermits = 0.5 * warmupPeriod / stableInterval.
        // warningToken = 100;
        // 计算预警token数量
        // 例如 count=5,warmUpPeriodInSec=10,coldFactor=3,则waringToken=5*10/2=25
        warningToken = (int)(warmUpPeriodInSec * count) / (coldFactor - 1);
        // / maxPermits = thresholdPermits + 2 * warmupPeriod / (stableInterval + coldInterval)
        // maxToken = 200
        // 最大token数量=25+2*10*5/4=50
        maxToken = warningToken + (int)(2 * warmUpPeriodInSec * count / (1.0 + coldFactor));
        // slope
        // slope = (coldIntervalMicros - stableIntervalMicros) / (maxPermits- thresholdPermits);
        // 倾斜度=(3-1)/5/(50-25) = 0.016
        slope = (coldFactor - 1.0) / count / (maxToken - warningToken);
    }
}

举例说明:

FlowRule设定阈值count=5,即1s内QPS阈值为5,设置的预热时间默认为10s,即warmUpPeriodSec=10,冷却因子coldFactor默认为3,即count = 5,coldFactor=3,warmUpPeriodSec=10,则

stableInterval=1/count=200ms,coldInterval=coldFactor*stableInterval=600ms
warningToken=warmUpPeriodSec/(coldFactor-1)/stableInterval=(warmUpPeriodSec*count)/(coldFactor-1)=25
maxToken=2warmUpPeriodSec/(stableInterval+coldInterval)+warningToken=warningToken+2warmUpPeriodSeccount/(coldFactor+1)=50
slope=(coldInterval-stableInterval)/(maxToken-warningToken)=(coldFactor-1)/count/(maxToken-warningToken)=0.016

接下来学习,WarmUpController是如何进行限流的,进入canPass()方法:

public boolean canPass(Node node, int acquireCount, boolean prioritized) {
    // 获取当前1s的QPS
    long passQps = (long) node.passQps();
    // 获取上一窗口通过的qps
    long previousQps = (long) node.previousPassQps();
    // 生成和滑落token
    syncToken(previousQps);
    // 如果进入了警戒线,开始调整他的qps
    long restToken = storedTokens.get();
    // 如果令牌桶中的token数量大于警戒值,说明还未预热结束,需要判断token的生成速度和消费速度
    if (restToken >= warningToken) {
        long aboveToken = restToken - warningToken;
        // 消耗的速度要比warning快,但是要比慢
        // y轴,当前token生成时间 current interval = restToken*slope+stableInterval
        // 计算此时1s内能够生成token的数量
        double warningQps = Math.nextUp(1.0 / (aboveToken * slope + 1.0 / count));
        // 判断token消费速度是否小于生成速度,如果是则正常请求,否则限流
        if (passQps + acquireCount <= warningQps) {
            return true;
        }
    } else {
        // 预热结束,直接判断是否超过设置的阈值
        if (passQps + acquireCount <= count) {
            return true;
        }
    }

    return false;
}

canPass()方法分为3个阶段:

syncToken():负责令牌的生产和滑落

判断令牌桶中剩余令牌数

  • 如果剩余令牌数大于警戒值,说明处于预热阶段,需要比较令牌的生产速率与令牌的消耗速率。若消耗速率大,则限流;否则请求正常通行

仍然以count=5进行举例,警戒线warningToken=25,maxToken=50

假设令牌桶中剩余令牌数storedTokens=30,即在预热范围内,此时restToken=30,slope=0.016,则aboveToken=30-25=5

由斜率slope推导当前token生成时间间隔:(restToken-warningToken)*slope+stableInterval=5*0.016+1/5=0.28,即280ms生成一个token

此时1s内生成token的数量=1/0.28&asymp;4,即1s内生成4个token

假设当前窗口通过的请求数量passQps=4,acquiredCount=1,此时passQps+acquiredCount=5>4,即令牌消耗速度大于生产速度,则限流

  • 如果剩余令牌数小于警戒值,说明系统已经处于高水位,请求稳定,则直接判断QPS与阈值,超过阈值则限流

接下来分析Sentinel是如何生产及滑落token的,进入到syncToken()方法:

获取当前时间秒数currentTime,与lastFilledTime进行比较,之所以取秒数,是因为时间窗口的设定为1s,若两个时间相等,说明还处于同一秒内,不进行token填充和滑落,避免重复问题

令牌桶中添加token

  • 当流量极大,令牌桶中剩余token远低于预警值时,添加token

  • 处于预热节点,单令牌的消耗速度小于系统最冷时令牌的生成速度,则添加令牌

通过CAS操作,修改storedToken,并进行令牌扣减

protected void syncToken(long passQps) {
    long currentTime = TimeUtil.currentTimeMillis();
    // 获取整秒数
    currentTime = currentTime - currentTime % 1000;
    // 上一次的操作时间
    long oldLastFillTime = lastFilledTime.get();
    // 判断成立,如果小于,说明可能出现了时钟回拨
    // 如果等于,说明当前请求都处于同一秒内,则不进行token添加和滑落操作,避免的重复扣减
    // 时间窗口的跨度为1s
    if (currentTime <= oldLastFillTime) {
        return;
    }
    // token数量
    long oldValue = storedTokens.get();
    long newValue = coolDownTokens(currentTime, passQps);
    // 重置token数量
    if (storedTokens.compareAndSet(oldValue, newValue)) {
        // token滑落,即token消费
        // 减去上一个时间窗口的通过请求数
        long currentValue = storedTokens.addAndGet(0 - passQps);
        if (currentValue < 0) {
            storedTokens.set(0L);
        }
        // 设置最后添加令牌时间
        lastFilledTime.set(currentTime);
    }

}
private long coolDownTokens(long currentTime, long passQps) {
    long oldValue = storedTokens.get();
    long newValue = oldValue;

    // 添加令牌的判断前提条件:
    // 当令牌的消耗程度远远低于警戒线的时候
    if (oldValue < warningToken) {
        // 计算过去一段时间内,可以通过的QPS总量
        // 初始加载时,令牌数量达到maxToken
        newValue = (long)(oldValue + (currentTime - lastFilledTime.get()) * count / 1000);
    } else if (oldValue > warningToken) {
        // 处于预热过程,且消费速度低于冷却速度,则补充令牌
        if (passQps < (int)count / coldFactor) {
            newValue = (long)(oldValue + (currentTime - lastFilledTime.get()) * count / 1000);
        }
    }
    // 当令牌桶满了之后,抛弃多余的令牌
    return Math.min(newValue, maxToken);
}

“Sentinel中冷启动限流原理WarmUpController是什么”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI