dledger 的 quota

目的:统计每秒的字节数,超过了阈值则 sleep

// window 默认为 5
// 2 个数组,数组下标 = 当前秒数 % window
// samples 存放累加值
// timeVec 存放时间的秒数
private final int[] samples;
private final long[] timeVec;

采样

// io.openmessaging.storage.dledger.utils.Quota#sample
public void sample(int value) {
    // 当前毫秒数
    long timeMs = System.currentTimeMillis();
    // 当前秒数 % 5
    int index = index(timeMs);
    // 当前秒数
    long second = second(timeMs);
    if (timeVec[index] != second) {
        // 下标对应的时间不等于当前时间,表示时间过了 5, 10, 15 ...
        // 重新赋值
        timeVec[index] = second;
        samples[index] = value;
    } else {
        // 直接累加
        samples[index] += value;
    }
}

判断是否超过阈值

// io.openmessaging.storage.dledger.utils.Quota#validateNow
public boolean validateNow() {
    // 当前毫秒数
    long timeMs = System.currentTimeMillis();
    // 当前秒数 % 5
    int index = index(timeMs);
    // 当前秒数
    long second = second(timeMs);
    if (timeVec[index] == second) {
        // 超过配额
        return samples[index] >= max;
    }
    return false;
}

猜你喜欢

转载自www.cnblogs.com/allenwas3/p/12522193.html