RateLimiter 是guava 用于限流的工具类,是限制每秒能有多少个请求放行的意思
原理大致是这样的:计算出多少us 内可以放行多少请求
为了提升效率,它是会计算下一次要执行的时间点,如果到了这个时间点才执行,否则会进行sleep 等待
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();
}
}