本文实现了一种基本的漏桶算法
漏桶算法思想:以固定速率消费请求,漏桶容量固定,每次用户请求都得放入桶中,桶满则拒绝请求或等待。达到平滑网络请求的效果。
代码逻辑:线程池每0.5s发送随机数量的请求,每次请求计算当前桶内的水量及剩余容量,请求数量超出当前桶容量,则产生限流。
@Slf4j
public class LeakyBucketLimiter {
private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
// 桶的容量
public int capacity = 10;
// 当前水量
public int water = 0;
//水流速度/s
public int rate = 4;
// 最后一次加水时间
public long lastTime = System.currentTimeMillis();
public void acquire() {
scheduledExecutorService.scheduleWithFixedDelay(() -> {
long now = System.currentTimeMillis();
//计算当前水量
water = Math.max(0, (int) (water - (now - lastTime) * rate /1000));
int permits = (int) (Math.random() * 8) + 1;
log.info("请求数:" + permits + ",当前桶余量:" + (capacity - water));
lastTime = now;
if (capacity - water < permits) {


1010

被折叠的 条评论
为什么被折叠?



