Maven依赖
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>20.0</version> </dependency>
核心方法
RateLimiter.create(2)
RateLimiter.acquire())
Demo: 基础入门
public class Application2 { public static void main(String[] args) { // create方法参数permitsPerSecond RateLimiter rateLimiter = RateLimiter.create(2); System.out.println(rateLimiter.toString()); List<Runnable> tasks = new ArrayList<Runnable>(); for (int i = 0; i < 10; i++) { tasks.add(new UserRequest(i)); } ExecutorService threadPool = Executors.newCachedThreadPool(); for (Runnable runnable : tasks) { System.out.println("等待时间:" + rateLimiter.acquire()); threadPool.execute(runnable); } } private static class UserRequest implements Runnable { private int id; public UserRequest(int id) { this.id = id; } public void run() { System.out.println(id); } } }
执行效果
RateLimiter[stableRate=2.0qps] 等待时间:0.0 0 等待时间:0.485271 1 等待时间:0.498734 2 等待时间:0.499003 3 等待时间:0.499248 4 等待时间:0.499308 5 等待时间:0.49971 6 等待时间:0.49874 7 等待时间:0.499551 8 等待时间:0.495876 9