限流算法

发布时间 2023-05-31 17:46:45作者: 猥琐熊花子酱

固定窗口

缺陷:最简单,但是不能精确限制,由于是计算的时间差,比如每10秒只能10个请求,8-10秒请求了10个,那么10-18秒就也无法请求了


import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

public class MyFixedWindow {

    private final    int maxCount= 10; //限制次数
    private final   int  windowUnit= 10 * 1000; // 单位时间 (毫秒)

    private AtomicInteger nowCount  ; //当前次数
    private AtomicLong lastTime; // 最后一次请求的时间

    public MyFixedWindow() {
            this.nowCount=new AtomicInteger(1);
            this.lastTime=new AtomicLong(0);
    }

    public synchronized boolean tryAcquire() {
        System.out.println("-----"+nowCount.get());
        long currentTime = System.currentTimeMillis();  //获取系统当前时间
        if(currentTime-lastTime.get()>windowUnit){// 如果当前时间减去上次请求的时间大于目标设置的时间,就重置
            nowCount.set(1);
            lastTime.set(currentTime);
            return true;
        }else {
            if(nowCount.get()>=maxCount){ //超过目标次数直接限流
                return false;
            }else{
                nowCount.incrementAndGet(); //否则自增1
                return true;
            }

        }
    }


}


   MyFixedWindow myFixedWindow= new MyFixedWindow();
    /**
     * 10 秒之内只能请求10次
     *
     * @return
     */
    @GetMapping("/test")
    public String test() {
        if(myFixedWindow.tryAcquire()){
                return "ok";
        }else {
            //执行降级
            return "请稍后再重试";
           // throw new RuntimeException();
        }
    }

可以看到限制没问题