<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<scope>23.0</scope>
</dependency>
public class TokenBucketDemo {
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();
}
}