过载保护设计
过载保护是防止系统崩溃的重要机制。
📋 限流算法
限流算法对比:
🎯 令牌桶限流器实现
java
/**
* 令牌桶限流器
*/
public class TokenBucketRateLimiter {
private final long capacity; // 桶容量
private final double refillRate; // 令牌生成速率(每秒)
private AtomicLong tokens; // 当前令牌数
private long lastRefillTime; // 上次填充时间
public TokenBucketRateLimiter(long capacity, double refillRate) {
this.capacity = capacity;
this.refillRate = refillRate;
this.tokens = new AtomicLong(capacity);
this.lastRefillTime = System.currentTimeMillis();
}
/**
* 尝试获取令牌
* @return true 如果获取成功,false 如果限流
*/
public synchronized boolean tryAcquire() {
refill();
long currentTokens = tokens.get();
if (currentTokens > 0) {
tokens.decrementAndGet();
return true;
}
return false;
}
/**
* 填充令牌
*/
private void refill() {
long now = System.currentTimeMillis();
long elapsed = now - lastRefillTime;
// 计算应该生成的令牌数
long tokensToAdd = (long) (elapsed * refillRate / 1000.0);
if (tokensToAdd > 0) {
long currentTokens = tokens.get();
long newTokens = Math.min(capacity, currentTokens + tokensToAdd);
tokens.set(newTokens);
lastRefillTime = now;
}
}
}