RateLimiter 是guava 用于限流的工具类,是限制每秒能有多少个请求放行的意思java
原理大体是这样的:计算出多少us 内能够放行多少请求工具
为了提高效率,它是会计算下一次要执行的时间点,若是到了这个时间点才执行,不然会进行sleep 等待ui
public double acquire(int permits) { long microsToWait = reserve(permits); stopwatch.sleepMicrosUninterruptibly(microsToWait); return 1.0 * microsToWait / SECONDS.toMicros(1L); } sleep 等待逻辑在stopwatch.sleepMicrosUninterruptibly(microsToWait); public static void sleepUninterruptibly(long sleepFor, TimeUnit unit) { boolean interrupted = false; try { long remainingNanos = unit.toNanos(sleepFor); long end = System.nanoTime() + remainingNanos; while (true) { try { // TimeUnit.sleep() treats negative timeouts just like zero. NANOSECONDS.sleep(remainingNanos); return; } catch (InterruptedException e) { interrupted = true; remainingNanos = end - System.nanoTime(); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } }