当前位置:  开发笔记 > 编程语言 > 正文

番石榴Ratelimiter tryAcquire仅在第一次调用(任意数量的许可)时返回true?

如何解决《番石榴RatelimitertryAcquire仅在第一次调用(任意数量的许可)时返回true?》经验,为你挑选了1个好方法。

我正在使用Guava 18.0 RateLimiter:

public static void simpleTst() throws Exception{
    RateLimiter lt = RateLimiter.create(2);
    _log.info("Acquired one " + lt.tryAcquire());
    _log.info("Acquired two " + lt.tryAcquire());
}

输出是:

: 08 16:22:10 PST.INFO1*RateLimiterTst~simpleTst@37: Acquired one true
: 08 16:22:10 PST.INFO1*RateLimiterTst~simpleTst@38: Acquired two false

指定许可证数量12:

public static void simpleTst() throws Exception{
    RateLimiter lt = RateLimiter.create(2);
    _log.info("Acquired one " + lt.tryAcquire(12));
    _log.info("Acquired two " + lt.tryAcquire());
}

输出是:

: 08 16:22:36 PST.INFO1*RateLimiterTst~simpleTst@37: Acquired one true
: 08 16:22:36 PST.INFO1*RateLimiterTst~simpleTst@38: Acquired two false

为什么会这样?



1> Filippo Vita..:

预期第一个示例的行为是因为:

// we request 2 permit per seconds
RateLimiter lt = RateLimiter.create(2);
_log.info("Acquired one " + lt.tryAcquire());

// waiting 1/2 second we will be able to get the second permit
Thread.sleep(500);
_log.info("Acquired two " + lt.tryAcquire());

输出是:

Acquired one true
Acquired two true

来自番石榴文档:

返回的RateLimiter确保在任何给定的秒内平均不超过permitPerSecond,持续请求在每秒平滑分布.

第二个例子的行为也是预期的,因为要成功获得第二个"获取"的单一许可我们需要等待大约6秒(= 12/2)

// we request 2 permit per seconds
RateLimiter lt = RateLimiter.create(2);

// trying to acquire 12 permits
_log.info("Acquired one " + lt.tryAcquire(12));

// waiting 12 / 2 seconds in order to be able to get the second permit
Thread.sleep(6000);
_log.info("Acquired two " + lt.tryAcquire());

输出是:

Acquired one true
Acquired two true

尝试获取等待时间少于6秒的最后一个许可证将失败,这就是为什么lt.tryAcquire()在您的示例中返回false.

推荐阅读
黄晓敏3023
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有