限流系列之RateLimiter解析(一):SmoothBursty
限流系列之RateLimiter解析(二):SmoothWarmingUp
限流系列之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存在着一定的数学关系
- 令牌数storedPermits有两个关键值:threshold和max,interval也有两个关键值:stable和cold。当storedPermits介于0–threshold之间时,interval固定为stable;当storePermits介于threshold–max之间时,interval均匀增大。
- perimits从max到threshold的过程称之为warm up,permits从0到max的过程则为cool down。warm up是令牌的消耗过程,cool dowm是令牌的生成。
- 根据微积分计算可以得到,warming up阶段需要的时间就是上图中梯形部分的面积,称之为warm up period。warmUpPeriod = (stable+cold) * (max-threshold) / 2
- 该类中存在两处硬编码:分别为
(1)coldInterval = 3 * stableInterval,那么warmUpPeriod = 2 * stable * (max-threshold)
(2)矩形面积(速率不变期间)是梯形的一半,即stable * threshold = warmUpPeriod/2,可以得到 max = 2 * threshold。所以上图中用halfPermits来表示threshold。
最终得到,warmUpPeriod = stable * max。 - 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