限流系列之RateLimiter解析(二):SmoothWarmingUp

限流系列之RateLimiter解析(一):SmoothBursty
限流系列之RateLimiter解析(二):SmoothWarmingUp


一、简介

SmoothWarmingUp是guava提供的另一个限流工具类,与SmoothBursty不同的是,SmoothWarmingUp在固定速度的基础上增加了预热流程,可以更好的应对突发流量。另外,在初始化和小流量时更慢得进行流量得提供也符合实际的应用场景。

This implements the following function:
         ^ throttling
         |
3*stable +                  /
interval |                 /.
 (cold)  |                / .
         |               /  .   <-- "warmup period" is the area of the trapezoid between
2*stable +              /   .       halfPermits and maxPermits
interval |             /    .
         |            /     .
         |           /      .
  stable +----------/  WARM . }
interval |          .   UP  . } <-- this rectangle (from 0 to maxPermits, and
         |          . PERIOD. }     height == stableInterval) defines the cooldown period,
         |          .       . }     and we want cooldownPeriod == warmupPeriod
         |---------------------------------> storedPermits
             (halfPermits) (maxPermits)

在SmoothWarmingUp类的注释中,也针对原理进行的描述,如上图,流量的速度控制interval 和库存令牌数storedPermits存在着一定的数学关系

  1. 令牌数storedPermits有两个关键值:threshold和max,interval也有两个关键值:stable和cold。当storedPermits介于0–threshold之间时,interval固定为stable;当storePermits介于threshold–max之间时,interval均匀增大。
  2. perimits从max到threshold的过程称之为warm up,permits从0到max的过程则为cool down。warm up是令牌的消耗过程,cool dowm是令牌的生成。
  3. 根据微积分计算可以得到,warming up阶段需要的时间就是上图中梯形部分的面积,称之为warm up period。warmUpPeriod = (stable+cold) * (max-threshold) / 2
  4. 该类中存在两处硬编码:分别为
    (1)coldInterval = 3 * stableInterval,那么warmUpPeriod = 2 * stable * (max-threshold)
    (2)矩形面积(速率不变期间)是梯形的一半,即stable * threshold = warmUpPeriod/2,可以得到 max = 2 * threshold。所以上图中用halfPermits来表示threshold。
    最终得到,warmUpPeriod = stable * max。
  5. cooldown的时间是矩形面积(from 0 to maxPermits, and height == stableInterval,这时候coolDownPeriod=warmUpPeriod。这也是上述硬编码的目的。

二、创建和初始化

1. 成员变量

private final long warmupPeriodMicros;
private double slope;
private double halfPermits;

本篇只介绍在SmoothWarmingUp里定义的成员变量,从父类继承的成员变量在上一篇对SmoothBursty的介绍里已经提到,不了解的可以回顾。
warmupPeriodMicros如简介中所说warmingUp过程的所需时间,即简介图中的梯形面积。
halfPermits如简介里提到的,是流量速度控制的一个阈值
slope代表令牌从halfPermits到maxPermits期间的interval的变化率,即简介图中的梯形斜边的斜率。slope 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值