限流算法-Java

2022-12-29  本文已影响0人  zianL

单机版滑动窗口

package com.trade.common;


import java.util.LinkedList;


public class SlideWindow {

    /**
     * 定义窗口 链表
     */
    private LinkedList<Long> linkedList;

    /**
     * 单位窗口限流次数
     */
    private Integer count;
    /**
     * 窗口时间 单位毫秒
     */
    private Long timeWindow;

    public SlideWindow(Integer count, Long timeWindow) {
        this.count = count;
        this.timeWindow = timeWindow;
        linkedList = new LinkedList<>();
    }


    public synchronized boolean tryAcquire() {
        // 获取到当前系统时间
        long currentTimeMillis = System.currentTimeMillis();
        if (linkedList.size() < count) {
            // 最新的 node 节点存放 在最前面
            linkedList.add(0, currentTimeMillis);
            System.out.println(Thread.currentThread().getName() + "true," + currentTimeMillis);
            return true;// 放行
        }
        // 判断是否在窗口个数范围内
        int farIndex = count - 1;
        // 取出尾结点
        Long farTime = linkedList.get(farIndex);
        if (currentTimeMillis - farTime < timeWindow) {
            System.out.println(Thread.currentThread().getName() + "false," + currentTimeMillis);
            return false;
        }
        //已经超过窗口时间范围内,删除尾结点
        linkedList.remove(farIndex);
        //追加节点到链表头,保持窗口节点数
        linkedList.add(0, currentTimeMillis);
        System.out.println(Thread.currentThread().getName() + "true," + currentTimeMillis);
        return true;
    }

    public static void main(String[] args) throws InterruptedException {
        SlideWindow SlideWindow = new SlideWindow(2, 1000l);
        for (int i = 1; i <= 100; i++) {
            new Thread(() -> {
                boolean result = SlideWindow.tryAcquire();
            }).start();
            Thread.sleep(10);
        }
        Thread.sleep(10000);
    }

}

上一篇 下一篇

猜你喜欢

热点阅读