添加限流工具,修改模板onlyIf

This commit is contained in:
2025-01-23 15:10:29 +08:00
parent 1aa1ae5e2b
commit 7bd9a7507f
10 changed files with 64 additions and 32 deletions

View File

@ -0,0 +1,26 @@
package com.ycwl.basic.ratelimiter;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class SlidingWindowRateLimiter {
private final Semaphore semaphore;
private final ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1);
public SlidingWindowRateLimiter(int maxRequestsPerSecond) {
this.semaphore = new Semaphore(maxRequestsPerSecond);
// Schedule a task to release all permits every second
scheduler.scheduleAtFixedRate(() -> semaphore.release(maxRequestsPerSecond - semaphore.availablePermits()), 1, 1, TimeUnit.SECONDS);
}
public void allowRequest() throws InterruptedException {
semaphore.acquire();
}
public void shutdown() {
scheduler.shutdown();
}
}