gpt4 book ai didi

java - Guava RateLimiter 预热说明

转载 作者:行者123 更新时间:2023-11-30 07:36:41 24 4
gpt4 key购买 nike

鉴于我正在使用 Guava 速率限制器和预热,我正在尝试找出一种方法来计算在特定时间会发生多少 QPS。我看了评论here ,但我仍然不清楚。希望这里有人可以为我澄清。

我的用例:

我调用了一个具有 50 TPS 限制的外部服务。需要注意的是,我们调用它们的前 500 次必须远低于 50 TPS,之后我们可以恢复 50TPS。 (如果有比使用速率限制器更好的解决方案,我很想听听!)

伪代码:

RateLimiter rateLimiter = RateLimiter.create(50.0, 10, minutes);
for (String customerId : customerList) {
rateLimiter.acquire();
// call external service
}

假设我们仅使用一个线程执行此操作。有没有办法计算给定时间的 TPS(QPS)? 3分钟后? 5分钟后?等等

最佳答案

具有 warmupPeriodRateLimiter 的冷(最小)速率是稳定(最大)速率的 1/3(这源自 coldFactor 硬编码为 RateLimiter.java:147-184 中的 3.0 )。在饱和需求(即不间断的许可证请求)下,速率将以恒定速率增加,直到达到稳定(最大)速率。

因为这是 linear equation我们可以将其写成 y = m * x + b 的形式,其中

  • y(又名 y(x))或 qps(t))是给定饱和周期(例如3分钟内),
  • m 是从冷(最小)速率到稳定(最大)速率的变化率,
  • x(或t)是饱和需求下耗时,
  • b 是我们的冷(最小)速率(稳定(最大)速率的 1/3)。

总而言之,我们有 qps(t) = (stableRate - ColdRate)/WarmupPeriod * saturatedPeriod + ColdRate,其中 coldRate = stableRate/3

因此,对于您的示例,我们可以在 3 分钟内获得预期的 QPS:

qps(3) = (50.0 - 50.0/3.0) / 10.0 * 3.0 + 50.0/3.0 ~= 26.6666

这是 Java 中的实现:

/**
* Calculates the expected QPS given a stableRate, a warmupPeriod, and a saturatedPeriod.
* <p>
* Both specified periods must use the same time unit.
*
* @param stableRate how many permits become available per second once stable
* @param warmupPeriod the duration of the period where the {@code RateLimiter} ramps up
* its rate, before reaching its stable (maximum) rate
* @param saturatedPeriod the duration of the period for which the {@code RateLimiter} has
* been under saturated demand starting from a cold state
* @return The expected QPS assuming saturated demand starting from a cold state
*/
public static double qps(double stableRate, double warmupPeriod, double saturatedPeriod) {
if (saturatedPeriod >= warmupPeriod) {
return stableRate;
}
double coldRate = stableRate / 3.0;
return (stableRate - coldRate) * saturatedPeriod / warmupPeriod + coldRate;
}

请注意,在实践中使用单个线程,您将无法满足 RateLimiter 的需求,因此您的实际 QPS 将略低于预期,并且很少(如果有的话)实际达到稳定(最大)速率。但是,使用多个线程将允许您始终有待处理的许可请求并满足需求。

关于java - Guava RateLimiter 预热说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35298991/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com