dubbo如何做限流?


public boolean isAllowable() {
long now = System.currentTimeMillis();
if (now > lastResetTime + interval) {
token.set(rate);
lastResetTime = now;
}

int value = token.get();
boolean flag = false;
while (value > 0 && !flag) {
flag = token.compareAndSet(value, value - 1);
value = token.get();
}

return flag;
}


token是一個AtomicInteger類型。rate表示超過一定時間以后,給你放了多次調用機會,如果這段時間token次數用完,那么只能等時間超過interval。

對於comareAndSet的注釋:
/**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
*
* @param expect the expected value
* @param update the new value
* @return {@code true} if successful. False return indicates that
* the actual value was not equal to the expected value.
*/
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
也就是返回true說明你更新成功了,false你的這次更新失敗了,那么也就是非阻塞、非重試的方法。

while (value > 0 && !flag 這個循環退出有兩種情況:要不就是自己更新成功flag=true,要不就是別人把token用完了,導致token=0。



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM