com.google.guava guava23.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(); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)