gpt4 book ai didi

具有节流/吞吐量控制的 Java Executor

转载 作者:IT老高 更新时间:2023-10-28 20:22:25 25 4
gpt4 key购买 nike

我正在寻找一个 Java Executor,它允许我指定节流/吞吐量/步调限制,例如,一秒钟内最多可以处理 100 个任务——如果提交了更多任务,它们应该排队并且后执行。这样做的主要目的是避免在访问外部 API 或服务器时遇到限制。

我想知道是否是基础 Java(我怀疑,因为我检查过)或其他可靠的地方(例如 Apache Commons)提供了这个,或者我是否必须自己编写。最好是轻量级的。我不介意自己写,但如果有一个“标准”版本,我至少想先看看它。

最佳答案

看看 Guava RateLimiter :

A rate limiter. Conceptually, a rate limiter distributes permits at a configurable rate. Each acquire() blocks if necessary until a permit is available, and then takes it. Once acquired, permits need not be released. Rate limiters are often used to restrict the rate at which some physical or logical resource is accessed. This is in contrast to Semaphore which restricts the number of concurrent accesses instead of the rate (note though that concurrency and rate are closely related, e.g. see Little's Law).

它是线程安全的,但仍然是 @Beta。无论如何可能值得一试。

您必须根据速率限制器包装对 Executor 的每个调用。对于更干净的解决方案,您可以为 ExecutorService 创建某种包装器。

来自 javadoc:

 final RateLimiter rateLimiter = RateLimiter.create(2.0); // rate is "2 permits per second"
void submitTasks(List<Runnable> tasks, Executor executor) {
for (Runnable task : tasks) {
rateLimiter.acquire(); // may wait
executor.execute(task);
}
}

关于具有节流/吞吐量控制的 Java Executor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19819837/

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