【发布时间】:2022-10-15 22:34:22
【问题描述】:
目前我有一个要求:为 API 应用速率限制器。如果此 API 每 5 秒调用超过 100 次,则该 API 将被阻塞 10 分钟。 我不知道是否有任何java lib可以满足这个要求。如果要求是“每 5 秒允许 100 个调用”或“每 10 分钟允许 100 个调用”,那么我可以使用 Bucket4j:
Bandwidth b = Bandwidth.classic(100, Refill.intervally(100, Duration.ofSeconds(5)));
//Bandwidth b = Bandwidth.classic(100, Refill.intervally(100, Duration.ofMinutes(10)));
Bucket bk = Bucket.builder().addLimit(b).build();
//then
if(bk.tryConsume(1)) {
//stuff
} else {
throw
}
或 Resilence4j:
RateLimiterConfig config = RateLimiterConfig.custom()
.limitRefreshPeriod(Duration.ofSeconds(5))
.limitForPeriod(100)
.timeoutDuration(Duration.ofSeconds(1))
.build();
RateLimiterRegistry rateLimiterRegistry = RateLimiterRegistry.of(config);
RateLimiter rateLimiterWithCustomConfig = rateLimiterRegistry
.rateLimiter("name2", config);
CheckedRunnable restrictedCall = RateLimiter
.decorateCheckedRunnable(rateLimiterWithCustomConfig, this::doStuff);
//then
Try.run(restrictedCall).onFailure(throwable -> throw new RuntimeException());
但要求是“每 5 秒允许 100 个调用,如果更多,则阻止 10 分钟”。有什么lib可以工作吗?请建议我为这种情况提供解决方案。谢谢
【问题讨论】:
标签: java spring rate-limiting resilience4j bucket4j