使用Guava RateLimiter类调用限制方法 [英] Throttling method calls using Guava RateLimiter class

查看:517
本文介绍了使用Guava RateLimiter类调用限制方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图限制每秒调用一个方法的次数。
我试图用Guava RateLimiter实现这个目的。

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

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

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

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

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

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

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

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.

推荐答案

您需要在每次调用中在相同的 RateLimiter 上调用 acquire(),例如通过在 performOperation()中提供它:

You need to call acquire() on the same RateLimiter in every invocation, e.g. by making it available in 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");
    }
}

结果


Fri Aug 07 19:00:10 BST 2015:Beep
Fri Aug 07 19:00:11 BST 2015:Beep

Fri 8月07日19:00:12 BST 2015:Beep
7月7日星期五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 07 19:00:17 BST 2015:Beep

Fri Aug 07 19:00:18 BST 2015:Beep
Fri Aug 07 07:00:19 BST 2015:Beep

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

这篇关于使用Guava RateLimiter类调用限制方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆