package cn.reghao.tnb.sb.ratelimiter;

import java.time.LocalTime;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 固定时间窗口算法
 *
 * @author reghao
 * @date 2025-07-15 13:49:22
 */
public class SimpleWindowRateLimiter {
    // 阈值
    private static Integer qps = 2;
    // 时间窗口(毫秒)
    private static long timeWindow = 1000;
    // 计数器
    private static AtomicInteger reqCount = new AtomicInteger();
    private static long startTime = System.currentTimeMillis();

    public synchronized static boolean tryAcquire() {
        if ((System.currentTimeMillis() - startTime) > timeWindow) {
            reqCount.set(0);
            startTime = System.currentTimeMillis();
        }
        return reqCount.incrementAndGet() <= qps;
    }

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            Thread.sleep(250);
            LocalTime now = LocalTime.now();
            if (!tryAcquire()) {
                System.out.println(now + " 被限流");
            } else {
                System.out.println(now + " 做点什么");
            }
        }
    }
}
