滑动窗口Java实现

最近在看限流相关的技术,看到几种主流的实现限流功能的思想,但刚开始看的时候对令牌桶,漏桶和滑动窗口搞懵逼了,感觉它们的思想好像都是一样的,但为什么又叫不同的名字呢?看别人的代码又看不进去,那么就根据它们的思想自己实现一遍吧
不废话,直接上代码:
public class RealSlidingWindows {

    /**
     * 总窗口大小
     */
    private Long window;

    /**
     * 总窗口流量
     */
    private Long totalPassCount;

    /**
     * 单位窗口数量
     */
    private Integer unitWindowCount;

    private ConcurrentLinkedDeque<UnitWindows> linkedDeque;

    private Long unitWindow;

    private AtomicLong windowPassedCount;

    private static Lock lock = new ReentrantLock();

    public static void main(String[] args) {

        long startTime = System.currentTimeMillis();

        AtomicLong passCount = new AtomicLong(0);

        AtomicLong refuseCount = new AtomicLong(0);

        RealSlidingWindows rsw = new RealSlidingWindows(100000L, 100L, 10);

        ExecutorService executorService = Executors.newFixedThreadPool(100);

        for(int i=0;i<100_000;++i){

            //单线程测试
//            if(rsw.isPass()){
//                passCount.incrementAndGet();
//            }else{
//                refuseCount.incrementAndGet();
//            }

            Runnable r = () -> {
                if(rsw.isPass()){
                    passCount.incrementAndGet();
                }else{
                    refuseCount.incrementAndGet();
                }
            };

            executorService.execute(r);
        }
        try {
            Thread.sleep(10_000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("耗时:"+(System.currentTimeMillis() - startTime)
                + " passed: "+passCount.get() +" refused: "+refuseCount.get());

        executorService.shutdown();
    }


    public RealSlidingWindows(Long window, Long totalPassCount, Integer unitWindowCount){
        this.window = window;
        this.totalPassCount = totalPassCount;
        this.unitWindowCount = unitWindowCount;
        this.linkedDeque = new ConcurrentLinkedDeque();
        this.unitWindow = window / unitWindowCount;
        this.windowPassedCount = new AtomicLong(0);
    }

    /**
     * 判断是否通过
     * @return
     */
    public  boolean isPass(){
        long now = System.currentTimeMillis();
        UnitWindows unitWindows = new UnitWindows(now);
        if(!linkedDeque.isEmpty()){
            UnitWindows first = linkedDeque.peekFirst();
            if(now - first.getStart() < unitWindow){
                //如果第一个小单元窗口还未结束
                //获取第一个单元小窗口
                unitWindows = first;
            }else{
                //第一个小窗口已经结束了
                //窗口已完成的总流量减去最后一个窗口的已完成流量即为当前窗口总流量
                windowPassedCount.addAndGet(-linkedDeque.peekLast().count.get());
                //将最后一个节点(最老的一个单元窗口)去掉
                linkedDeque.removeLast();
                //将新构建的单元窗口放到队头
                linkedDeque.addFirst(unitWindows);
            }
        } else {
            //将新构建的单元窗口放到队头
            linkedDeque.addFirst(unitWindows);
        }
        if(windowPassedCount.incrementAndGet() <= totalPassCount){
            //如果窗口已完成的流量数小于窗口允许的总流量数
            //更新窗口已完成的流量数并返回true
            unitWindows.count.incrementAndGet();
            return true;
        }
        return false;
    }

    /**
     * 放到
     */
    public static class UnitWindows {

        public UnitWindows(Long start){
            this.start = start;
            this.count = new AtomicLong(0);
        }

        private Long start;
        private AtomicLong count;

        public Long getStart() {
            return start;
        }

        public void setStart(Long start) {
            this.start = start;
        }

        public Long getCount() {
            return count.get();
        }

        public void increment(){
            count.incrementAndGet();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值