demo系列-限流算法-简单实现

demo系列-限流算法-简单实现

策略

  1. 计数器
  2. 漏桶算法
  3. 令牌桶算法

使用(guava)

        RateLimiter limiter = RateLimiter.create(10);

        ThreadFactory factory = ThreadFactoryBuilder.create()
            .setNamePrefix("limit-")
            .build();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(30, 30, 0L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10000));
        for (int i = 0; i < 30; ++i) {
            executor.execute(() -> {
                limiter.acquire();
                System.out.println(Thread.currentThread().getName() + " 请求成功");
            });
        }
        Thread.sleep(2000);
        executor.shutdown();

实现:ReentrantLock

Limiter
@NoArgsConstructor
@AllArgsConstructor
public abstract class Limiter {
    /**
     * 每秒请求次数
     */
    protected int rate = 1;

    /**
     * 非阻塞
     *
     * @return 成功
     */
    public abstract boolean tryAcquire();

    /**
     * 阻塞
     */
    public void acquire() {
        do {
            if (tryAcquire()) {
                return;
            }

            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } while (true);
    }
}
计数器
public class CountLimiter extends Limiter {
    private volatile int counter = 0;

    private volatile long lastTime = 0L;

    private Lock lock = new ReentrantLock();

    public CountLimiter(int rate) {
        super(rate);
    }

    @Override
    public boolean tryAcquire() {
        try {
            lock.lock();
            if (System.currentTimeMillis() - lastTime > 1000L) {
                counter = 0;
                lastTime = System.currentTimeMillis();
            }

            counter++;
            if (counter <= rate) {
                return true;
            }
        } finally {
            lock.unlock();
        }
        return false;
    }
}
LeakyBucketLimiter
public class LeakyBucketLimiter extends Limiter {
    /*
    最大容量
    当前剩余:匀速出去
    上次时间
     */
    private int capacity;

    private volatile int water = 0;

    private volatile long lastTime = 0L;

    private Lock lock = new ReentrantLock();

    public LeakyBucketLimiter(int rate) {
        super(rate);
        this.capacity = rate;
    }

    @Override
    public boolean tryAcquire() {
        try {
            lock.lock();
            long now = System.currentTimeMillis();
            // 匀速漏出
            int outWater = Math.round((now - lastTime) / 1000L * rate);
            if (outWater > 0) {
                lastTime = now;
            }

            water = Math.max(0, water - outWater);
            if (water < capacity) {
                water++;
                return true;
            }
        } finally {
            lock.unlock();
        }

        return false;
    }
}

TokenBucketLimiter
public class TokenBucketLimiter extends Limiter {
    /*
    最大容量
    当前剩余:匀速进来
    上次时间
     */
    private int capacity;

    private volatile int token = 0;

    private volatile long lastTime = 0L;

    private Lock lock = new ReentrantLock();

    public TokenBucketLimiter(int rate) {
        super(rate);
        this.capacity = rate;
    }

    @Override
    public boolean tryAcquire() {
        try {
            lock.lock();
            long now = System.currentTimeMillis();
            // 匀速增加令牌
            int inToken = Math.round((now - lastTime) / 1000L * rate);
            if (inToken > 0) {
                lastTime = now;
            }

            token = Math.min(capacity, token + inToken);
            if (token > 0) {
                token--;
                return true;
            }
        } finally {
            lock.unlock();
        }

        return false;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值