本文介绍了使用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");
    }
}

结果

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

10-25 00:13