Sentinel 深度剖析 之 流量控制中算法
- 排队等待 -
匀速排队方式会严格控制请求通过的间隔时间,也即是让请求以均匀的速度通过;对应的是漏桶算法。
这效果只针对QPS流控,并发线程流控不支持。
1. 匀速排队
有超时等待时间,一旦超过这个预定设置的时间将会被限流。
2. 漏桶算法(leakyBucket)
随机突发流量通过漏桶以后稳定的速率流出,起到流量控制和平滑作用。
3. 实现类
RateLimiterController:通过控制请求通过的时间间隔来实现达到匀速目的。
public boolean canPass(Node node, int acquireCount, boolean prioritized) {
// Pass when acquire count is less or equal than 0.
if (acquireCount <= 0) {
return true;
}
// Reject when count is less or equal than 0.
// Otherwise,the costTime will be max of long and waitTime will overflow in some cases.
if (count <= 0) {
return false;
}
long currentTime = TimeUtil.currentTimeMillis();
// Calculate the interval between every two requests.
// 1) 两次请求的时间间隔
long costTime = Math.round(1.0 * (acquireCount) / count * 1000);
// Expected pass time of this request.
// 2)计算这次请求的通过预留时间 = 上次请求通过时间+时间间隔
long expectedTime = costTime + latestPassedTime.get();
// 3)当预期时间 <= 当前时间, 则允许通过并更新上次请求时间戳
if (expectedTime <= currentTime) {
// Contention may exist here, but it's okay.
latestPassedTime.set(currentTime);
return true;
} else {
// Calculate the time to wait.
// 4)当预期时间 > 当前时间, 则需要等待; 计算需要等待时间
long waitTime = costTime + latestPassedTime.get() - TimeUtil.currentTimeMillis();
// 5)需要等待的时间> 最⼤队列时间, 则拒绝 默认超时时间500毫秒
if (waitTime > maxQueueingTimeMs) {
return false;
} else {
long oldTime =
latestPassedTime.addAndGet(costTime);
try {
waitTime = oldTime -
TimeUtil.currentTimeMillis();
// 6)
if (waitTime > maxQueueingTimeMs) {
latestPassedTime.addAndGet(-costTime);
return false;
}
// in race condition waitTime may <= 0
// 7)
if (waitTime > 0) {
Thread.sleep(waitTime);
}
return true;
} catch (InterruptedException e) {
}
}
}
return false;
}
说明:假设设置的阈值count=100即每秒允许100个请求,每次通过一个请求acquireCount=1,套入公式costTime=10,即两次请求的时间间隔为10秒。
若水
架构师一枚,现就职于小米小爱开放平台,一个才貌双全的美女码农,平常喜欢总结知识和刷算法题,经常参加LeetCode算法周赛。
林淮川
毕业于西安交通大学;奈学教育首席架构师,教学教研负责人;前大树金融高级架构师、技术委员会开创者、技术总监;前天阳宏业交易事业部技术主管;多年互联网金融行业(ToB)经验。