import java.util.concurrent.atomic.AtomicLong;
public class RateLimiter {
private final long capacity; // 令牌桶容量
private final double rate; // 令牌生成速率
private AtomicLong tokens; // 当前令牌数量
private long lastRefillTime; // 上次令牌生成时间
public RateLimiter(long capacity, double rate) {
this.capacity = capacity;
this.rate = rate;
this.tokens = new AtomicLong(capacity);
this.lastRefillTime = System.currentTimeMillis();
}
private void refillTokens() {
long now = System.currentTimeMillis();
long timePassed = now - lastRefillTime;
long tokensToAdd = (long) (timePassed * rate / 1000);
tokens.set(Math.min(capacity, tokens.get() + tokensToAdd));
lastRefillTime = now;
}
public boolean allowRequest() {
refillTokens();
if (tokens.get() >= 1) {
tokens.decrementAndGet();
return true;
} else {
return false;
}
}
}