import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 限流器
*/
public class RateLimiter {
/**
* 时间窗口,单位毫秒
*/
private final long timeWindow;
/**
* 窗口时间内最大请求数
*/
private final int maxRequests;
private final AtomicInteger requestCount = new AtomicInteger(0);
private long startTime = System.currentTimeMillis();
public RateLimiter(int maxRequests, long timeWindow, TimeUnit unit) {
this.maxRequests = maxRequests;
this.timeWindow = unit.toMillis(timeWindow);
}
/**
* @return true 继续向下执行,false 阻断执行
*/
public synchronized boolean tryAcquire() {
long now = System.currentTimeMillis();
if (now - startTime > timeWindow) {
// 重置计数器
requestCount.set(0);
startTime = now;
}
if (requestCount.incrementAndGet() <= maxRequests) {
return true;
} else {
return false;
}
}
}