限流-令牌桶算法

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

/**
 * 限流器
 */
public class RateLimiter {
    /**
     * 时间窗口,单位毫秒
     */
    private final long timeWindow;
    /**
     * 窗口时间内最大请求数
     */
    private final int maxRequests;

    private final AtomicInteger requestCount = new AtomicInteger(0);

    private long startTime = System.currentTimeMillis();


    public RateLimiter(int maxRequests, long timeWindow, TimeUnit unit) {
        this.maxRequests = maxRequests;
        this.timeWindow = unit.toMillis(timeWindow);
    }


    /**
     * @return true 继续向下执行,false 阻断执行
     */
    public synchronized boolean tryAcquire() {
        long now = System.currentTimeMillis();
        if (now - startTime > timeWindow) {
            // 重置计数器
            requestCount.set(0);
            startTime = now;
        }
        if (requestCount.incrementAndGet() <= maxRequests) {
            return true;
        } else {
            return false;
        }
    }
}
posted @     阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2021-09-14 SpringBoot监听器的使用方法
2021-09-14 spring-常用扩展接口收集
2021-09-14 JVM常用命令参数
点击右上角即可分享
微信分享提示