聊聊leaky bucket算法的實現

本文主要研究一下leaky bucket算法的實現算法

leaky bucket算法

  • bucket以必定速率滴水,至關於增長桶容量
  • bucket有其容量限制,請求過來時bucket滿,則直接被拋棄
  • 請求到來時,若是bucket不滿,則放入bucket,至關於放行

簡單實現

public class LeakyBucket {

    private final long capacity;
    private final long leaksIntervalInMillis;

    private double used;
    private long lastLeakTimestamp;

    public LeakyBucket(long capacity, long leaksIntervalInMillis) {
        this.capacity = capacity;
        this.leaksIntervalInMillis = leaksIntervalInMillis;

        this.used = 0;
        this.lastLeakTimestamp = System.currentTimeMillis();
    }

    synchronized public boolean tryConsume(int drop) {
        leak();

        if (used + drop > capacity) {
           return false;
        }

        used = used + drop;
        return true;
    }

    private void leak() {
        long currentTimeMillis = System.currentTimeMillis();
        if (currentTimeMillis > lastLeakTimestamp) {
            long millisSinceLastLeak = currentTimeMillis - lastLeakTimestamp;
            long leaks = millisSinceLastLeak / leaksIntervalInMillis;
            if(leaks > 0){
                if(used <= leaks){
                    used = 0;
                }else{
                    used -= (int)leaks;
                }
                this.lastLeakTimestamp = currentTimeMillis;
            }
        }
    }
}
  • 這個實現設計了lastLeakTimestamp字段,用於計算時間差,以及在這個時間段內須要漏水的數量
  • 每次tryConsume的時候,方法內部首先調用leak,根據設定的速度以及時間差計算這個時間段須要漏水的數量,更新桶的當前使用量以及lastLeakTimestamp
  • 以後限流判斷,就是判斷used與請求的drop是否會超過桶容量,超出則限流,不然放入桶中,更新桶容量

小結

  • leaky bucket與token bucket算法相反,前者是漏水,後者是添加token
  • leaky bucket因爲是漏水算法,因此不能像token bucket添加token那種能夠累積,所以leaky bucket不能支持burst突發流量

doc

相關文章
相關標籤/搜索