Java速率限制器内部for循环,acquire调用外部api(具有节流功能)后不限制速率
请参考下面的代码片段。RateLimiter用于限制每秒对外部api的调用超过10次。在rateLimiter.acquire()行之后,调用async方法(核心异步任务执行器线程池为80,最大核心池大小为100->无法更改)。根据我的理解,速率限制器获取行不应允许超过10个项转到editItemAsync方法,这样externalApi.editItemProps行每秒执行的次数不会超过10次Java速率限制器内部for循环,acquire调用外部api(具有节流功能)后不限制速率,java,spring-boot,guava,throttling,rate-limiting,Java,Spring Boot,Guava,Throttling,Rate Limiting,请参考下面的代码片段。RateLimiter用于限制每秒对外部api的调用超过10次。在rateLimiter.acquire()行之后,调用async方法(核心异步任务执行器线程池为80,最大核心池大小为100->无法更改)。根据我的理解,速率限制器获取行不应允许超过10个项转到editItemAsync方法,这样externalApi.editItemProps行每秒执行的次数不会超过10次 但在测试过程中,情况并非如此&因为异步externalApi.editItemProps在一秒钟内
import com.google.common.util.concurrent.RateLimiter;
类ItemProcess{
私有最终RateLimiter RateLimiter=RateLimiter.create(10.0);
作废项目检查(列出项目){
试一试{
List completableFutures=新建ArrayList();
用于(项目:项目){
如果(item.isExpired()){//print
}否则{
rateLimiter.acquire();
completableFutures.add(service.editItemAsync(item));
}
}//为了目的
CompletableFuture.allOf(completableFutures.toArray(新的completableFutures[completableFutures.size())).get();
}捕获(例外e){
}
}
}
//这两个类都是不同的层,所以async可以工作
班级服务{
@异步的
公共CompletableFuture editItemAsync(项){
编辑项目(项目);
返回CompletableFuture.completedFuture(项目);
}
无效编辑项(项){
//调用外部api&它每秒限制10个请求。
externalApi.editItemProps(项目);
}
}
已经很晚了,但是你有测试结果吗?已经很晚了,但是你有测试结果吗?
import com.google.common.util.concurrent.RateLimiter;
class ItemProcess {
private final RateLimiter rateLimiter = RateLimiter.create(10.0);
void itemChecking(List<Item> items) {
try {
List<CompletableFuture<Item>> completableFutures = new ArrayList<>();
for (Item item : items) {
if (item.isExpired()) { // print
} else {
rateLimiter.acquire();
completableFutures.add(service.editItemAsync(item));
}
}// for ends
CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[completableFutures.size()])).get();
} catch(Exception e) {
}
}
}
// Both classes are different layer, so async is working
class Service {
@Async
public CompletableFuture<Item> editItemAsync(Item item) {
editItem(item);
return CompletableFuture.completedFuture(item);
}
void editItem(Item item) {
// calling external api & it has throttling of 10 requests per seconds.
externalApi.editItemProps(item);
}
}