计数器实现限流(单机)

实现时需要注意,用于计数的变量,自增操作应该为原子操作。

import java.util.concurrent.atomic.AtomicLong;

public class RateLimiter {

    private final static AtomicLong ZERO = new AtomicLong(0);
    private AtomicLong counter = ZERO;
    private static long timestamp = System.currentTimeMillis();
    private long permitsPerSecond;

    public RateLimiter(long permitsPerSecond) {
        this.permitsPerSecond = permitsPerSecond;
    }

    public boolean tryAcquire() {
        long now = System.currentTimeMillis();
        if (now - timestamp < 1000) {
            if (counter.get() < permitsPerSecond) {
                counter.incrementAndGet();
                return true;
            } else {
                return false;
            }
        } else {
            counter = ZERO;
            timestamp = now;
            return false;
        }
    }

}

用计数器来做限流,实现简单,并且很容易的扩展到分布式场景中,用redis保存计数值,并设置自动过期时间。缺点就是,在计数器置0前后的极短时间里,可能会有 2*permitsPerSecond 的突发流量。


猜你喜欢

转载自blog.csdn.net/mrokayan/article/details/79797255