java 使用 Guava RateLimiter 类限制方法调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31883739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:18:05  来源:igfitidea点击:

Throttling method calls using Guava RateLimiter class

javaguavathrottling

提问by sujith

I am trying to throttle the number of calls to a method per second. I tried to achieve this using Guava RateLimiter.

我试图限制每秒调用方法的次数。我尝试使用 Guava RateLimiter 来实现这一点。

RateLimiter rateLimiter = RateLimiter.create(1.0);//Max 1 call per sec
rateLimiter.acquire();
performOperation();//The method whose calls are to be throttled.

However the methods to the call are not limited to 1 per second but are continuous.

然而,调用的方法不限于每秒 1 次,而是连续的。

The throttling can be achieved using Thread.sleep() but i wish to use Guava rather that sleep().

可以使用 Thread.sleep() 实现节流,但我希望使用 Guava 而不是 sleep()。

I would like to know the right way to achieve the method call trottling using Guava RateLimiter. I have checked the documentation for RateLimiter and tried to use the same but could not achieve the desired result.

我想知道使用 Guava RateLimiter 实现方法调用 trottling 的正确方法。我检查了 RateLimiter 的文档并尝试使用相同的但无法达到预期的结果。

回答by Jens Hoffmann

You need to call acquire()on the same RateLimiterin every invocation, e.g. by making it available in performOperation():

您需要在每次调用中调用acquire()相同的内容RateLimiter,例如通过使其在performOperation()以下位置可用:

public class RateLimiterTest {
    public static void main(String[] args) {
        RateLimiter limiter = RateLimiter.create(1.0);
        for (int i = 0; i < 10; i++) {
            performOperation(limiter);
        }
    }

    private static void performOperation(RateLimiter limiter) {
        limiter.acquire();
        System.out.println(new Date() + ": Beep");
    }
}

results in

结果是

Fri Aug 07 19:00:10 BST 2015: Beep
Fri Aug 07 19:00:11 BST 2015: Beep
Fri Aug 07 19:00:12 BST 2015: Beep
Fri Aug 07 19:00:13 BST 2015: Beep
Fri Aug 07 19:00:14 BST 2015: Beep
Fri Aug 07 19:00:15 BST 2015: Beep
Fri Aug 07 19:00:16 BST 2015: Beep
Fri Aug 07 19:00:17 BST 2015: Beep
Fri Aug 07 19:00:18 BST 2015: Beep
Fri Aug 07 19:00:19 BST 2015: Beep

2015 年 8 月 7 日
星期五 19:00:10 BST 2015:哔哔 2015 年 8 月 7 日
星期五 19:00:11 BST 2015 年 8 月 7 日
星期五 19:00:12 BST 2015:哔哔 2015 年 8 月 7 日
星期五19:00:13 BST 2015 年8 月星期五:哔哔07 19:00:14 BST 2015:BST
周五 8 月 07 19:00:15 BST 2015:BST
周五 8 月 07 19:00:16 BST 2015:BST
周五 8 月 07 19:00:17 BST 2015:BST
8 月 1 日:00:18 BST 2015: Beep
周五 8 月 7 日 19:00:19 BST 2015: Beep