简单时间窗口限流

public class SlidingWindowRateLimiter {
    private final int windowSize; // 窗口大小(秒)
    private final int limit; // 窗口内允许的请求数
    private final AtomicInteger[] window; // 窗口内请求计数
    private int currentIndex; // 当前窗口索引
    private final ScheduledExecutorService scheduler;

    public SlidingWindowRateLimiter(int windowSize, int limit) {
        this.windowSize = windowSize;
        this.limit = limit;
        this.window = new AtomicInteger[windowSize];
        for (int i = 0; i < windowSize; i++) {
            window[i] = new AtomicInteger(0);
        }
        this.currentIndex = 0;
        this.scheduler = Executors.newScheduledThreadPool(1);
        startWindowSliding();
    }

    private void startWindowSliding() {
        scheduler.scheduleAtFixedRate(this::slideWindow, 1, 1, TimeUnit.SECONDS);
    }

    private void slideWindow() {
        currentIndex = (currentIndex + 1) % windowSize; // 移动窗口
        window[currentIndex].set(0); // 清空新位置的计数
    }
//方法用于检查当前窗口内的请求次数是否超过了限制。如果未超过限制,则允许新的请求并在当前位置增加计数;否则,拒绝请求。
    public boolean allowRequest() {
        int totalRequests = 0;
        for (AtomicInteger count : window) {
            totalRequests += count.get(); // 计算窗口内总请求数
        }
        if (totalRequests < limit) {
            window[currentIndex].incrementAndGet(); // 在当前位置增加计数
            return true; // 允许请求
        }
        return false; // 请求超限
    }

    public void stop() {
        scheduler.shutdown();
    }

    public static void main(String[] args) {
        SlidingWindowRateLimiter rateLimiter = new SlidingWindowRateLimiter(10, 10); // 窗口大小为 10 秒,限制为每秒最多 10个请求
        for (int i = 0; i < 20; i++) {
            if (rateLimiter.allowRequest()) {
                System.out.println("Request " + (i + 1) + " is allowed.");
            } else {
                System.out.println("Request " + (i + 1) + " is rejected.");
            }
            try {
                Thread.sleep(300); // 模拟请求到达间隔
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        rateLimiter.stop(); // 停止限流器
    }
}
  • 22
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值