【限流算法】java实现漏桶算法

本文实现了一种基本的漏桶算法

漏桶算法思想:以固定速率消费请求,漏桶容量固定,每次用户请求都得放入桶中,桶满则拒绝请求或等待。达到平滑网络请求的效果。

代码逻辑:线程池每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) {
                // 若桶满,则拒绝
                log.info("限流了");
            } else {
                // 还有容量
                water += permits;
                log.info("剩余容量=" + (capacity - water));
            }
        }, 0, 500, TimeUnit.MILLISECONDS);
    }

    public static void main(String[] args) {
        LeakyBucketLimiter limiter = new LeakyBucketLimiter();
        limiter.acquire();
    }
}

输出结果:

19:55:52.565 [pool-1-thread-1] INFO com.example.demo.limit.LeakyBucketLimiter - 请求数:2,当前桶余量:10
19:55:52.567 [pool-1-thread-1] INFO com.example.demo.limit.LeakyBucketLimiter - 剩余容量=8
19:55:53.068 [pool-1-thread-1] INFO com.example.demo.limit.LeakyBucketLimiter - 请求数:4,当前桶余量:10
19:55:53.068 [pool-1-thread-1] INFO com.example.demo.limit.LeakyBucketLimiter - 剩余容量=6
19:55:53.571 [pool-1-thread-2] INFO com.example.demo.limit.LeakyBucketLimiter - 请求数:8,当前桶余量:8
19:55:53.571 [pool-1-thread-2] INFO com.example.demo.limit.LeakyBucketLimiter - 剩余容量=0
19:55:54.075 [pool-1-thread-1] INFO com.example.demo.limit.LeakyBucketLimiter - 请求数:8,当前桶余量:2
19:55:54.075 [pool-1-thread-1] INFO com.example.demo.limit.LeakyBucketLimiter - 限流了
19:55:54.581 [pool-1-thread-3] INFO com.example.demo.limit.LeakyBucketLimiter - 请求数:3,当前桶余量:4
19:55:54.581 [pool-1-thread-3] INFO com.example.demo.limit.LeakyBucketLimiter - 剩余容量=1
19:55:55.083 [pool-1-thread-3] INFO com.example.demo.limit.LeakyBucketLimiter - 请求数:2,当前桶余量:3
19:55:55.084 [pool-1-thread-3] INFO com.example.demo.limit.LeakyBucketLimiter - 剩余容量=1
19:55:55.588 [pool-1-thread-3] INFO com.example.demo.limit.LeakyBucketLimiter - 请求数:6,当前桶余量:3
19:55:55.588 [pool-1-thread-3] INFO com.example.demo.limit.LeakyBucketLimiter - 限流了
19:55:56.094 [pool-1-thread-3] INFO com.example.demo.limit.LeakyBucketLimiter - 请求数:1,当前桶余量:5

你可能感兴趣的:(java,算法)