Java 实现漏桶算法 - 限流器示例
下面是用 Java 实现漏桶算法的代码:
import java.util.concurrent.TimeUnit;
public class LeakyBucket {
private final int capacity; // 桶的容量
private final int rate; // 流出速率
private long water; // 当前桶内的水量
private long lastLeakTime; // 上一次漏水时间
public LeakyBucket(int capacity, int rate) {
this.capacity = capacity;
this.rate = rate;
this.water = 0;
this.lastLeakTime = System.nanoTime();
}
public synchronized boolean tryAcquire() {
// 计算当前桶内的水量
long now = System.nanoTime();
water = Math.max(0, water - (now - lastLeakTime) * rate / TimeUnit.SECONDS.toNanos(1));
lastLeakTime = now;
// 判断是否能够放入请求
if (water < capacity) {
water++;
return true;
}
return false;
}
}
使用方法如下:
LeakyBucket bucket = new LeakyBucket(10, 1); // 桶的容量为10,流出速率为1/s
for (int i = 0; i < 20; i++) {
if (bucket.tryAcquire()) {
System.out.println('处理请求 ' + i);
} else {
System.out.println('请求 ' + i + ' 被限流');
}
Thread.sleep(100); // 每隔100ms发送一个请求
}
在上面的例子中,桶的容量为10,流出速率为1/s,每隔100ms发送一个请求,如果桶内的水量未满则可以处理请求,否则被限流。
原文地址: https://www.cveoy.top/t/topic/nVoE 著作权归作者所有。请勿转载和采集!