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(); } }