首先导入工具包:
<!-- https://mvnrepository.com/artifact/com.google.guava/guava --> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>29.0-jre</version> </dependency>
工具类:
public class TokenDemo { RateLimiter rateLimiter = RateLimiter.create(10);//设定qps 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 TokenDemo tokenDemo = new TokenDemo(); CountDownLatch countDownLatch = new CountDownLatch(1); final Random random = new Random(10); for (int i = 0; i < 20; i++) { new Thread(() -> { try { countDownLatch.await(); Thread.sleep(random.nextInt(1000)); tokenDemo.doRequest(); } catch (InterruptedException e) { e.printStackTrace(); } }, "t" + i).start(); } countDownLatch.countDown(); System.in.read(); } }