voidresync(long nowMicros) { // if nextFreeTicket is in the past, resync to now if (nowMicros > nextFreeTicketMicros) { doublenewPermits= (nowMicros - nextFreeTicketMicros) / coolDownIntervalMicros(); storedPermits = min(maxPermits, storedPermits + newPermits); nextFreeTicketMicros = nowMicros; } }
nowMicros:当前时间戳(毫秒)
nextFreeTicketMicros:下一次可以取令牌的时间戳
newPermits:新产生的令牌数
maxPermits:最大容积(也就是1秒产生的令牌数)
storedPermit:桶内的令牌数
设置最大容积和已有令牌数
第一次创建或修改限流
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
@Override voiddoSetRate(double permitsPerSecond, double stableIntervalMicros) { doubleoldMaxPermits=this.maxPermits; maxPermits = maxBurstSeconds * permitsPerSecond; if (oldMaxPermits == Double.POSITIVE_INFINITY) { // if we don't special-case this, we would get storedPermits == NaN, below storedPermits = maxPermits; } else { // oldMaxPermits 为 0,说明第一次创建,storedPermits = 0 // oldMaxPermit 不为 0,说明已创建过,本次是修改限流,做等比例缩放 storedPermits = (oldMaxPermits == 0.0) ? 0.0// initial state : storedPermits * maxPermits / oldMaxPermits; } }
@Override longstoredPermitsToWaitTime(double storedPermits, double permitsToTake) { doubleavailablePermitsAboveThreshold= storedPermits - thresholdPermits; longmicros=0; // measuring the integral on the right part of the function (the climbing line) // 大于 thresholdPermits,需要预热,计算梯形面积 if (availablePermitsAboveThreshold > 0.0) { doublepermitsAboveThresholdToTake= min(availablePermitsAboveThreshold, permitsToTake); // TODO(cpovirk): Figure out a good name for this variable. doublelength= permitsToTime(availablePermitsAboveThreshold) + permitsToTime(availablePermitsAboveThreshold - permitsAboveThresholdToTake); // 梯形面积 micros = (long) (permitsAboveThresholdToTake * length / 2.0); // 矩形x轴边长 permitsToTake -= permitsAboveThresholdToTake; } // measuring the integral on the left part of the function (the horizontal line) // 总时间 = 梯形面积 + 矩形面积 micros += (stableIntervalMicros * permitsToTake); return micros; }