限流之令牌桶

限流之令牌桶,第1张

限流之令牌
	
      com.google.guava
      guava
      23.0
    
public class TokenBucketDemo {

    //QPS=10
    RateLimiter rateLimiter = RateLimiter.create(10);

    public void doRequest() {
        if (rateLimiter.tryAcquire()) { //获得令牌成功
            System.out.println(Thread.currentThread().getName() + "->请求成功");
        } else {
            System.out.println(Thread.currentThread().getName() + "请求失败");
        }
    }

    public static void main(String[] args) throws IOException {
        final TokenBucketDemo tokenBucketDemo = new TokenBucketDemo();
        final CountDownLatch latch = new CountDownLatch(1);
        final Random random = new Random(10);
        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                try {
                    latch.await();
                    Thread.sleep(random.nextInt(1000));
                    tokenBucketDemo.doRequest();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }, "t" + i).start();
        }
        latch.countDown();
        System.in.read();
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5563207.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存