1. 程式人生 > 程式設計 >Dubbo原始碼解析(三十八)叢集——LoadBalance

Dubbo原始碼解析(三十八)叢集——LoadBalance

叢集——LoadBalance

目標:介紹dubbo中叢集的負載均衡,介紹dubbo-cluster下loadBalance包的原始碼。

前言

負載均衡,說的通俗點就是要一碗水端平。在這個時代,公平是很重要的,在網路請求的時候同樣是這個道理,我們有很多機器,但是請求老是到某個伺服器上,而某些伺服器又常年空閒,導致了資源的浪費,也增加了伺服器因為壓力過載而宕機的風險。這個時候就需要負載均衡的出現。它就相當於是一個天秤,通過各種策略,可以讓每臺伺服器獲取到適合自己處理能力的負載,這樣既能夠為高負載的伺服器分流,還能避免資源浪費。負載均衡分為軟體的負載均衡和硬體負載均衡,我們這裡講到的是軟體負載均衡,在dubbo中,需要對消費者的呼叫請求進行分配,避免少數服務提供者負載過大,其他服務空閒的情況,因為負載過大會導致服務請求超時。這個時候就需要負載均衡起作用了。Dubbo 提供了4種負載均衡實現:

  1. RandomLoadBalance:基於權重隨機演演算法
  2. LeastActiveLoadBalance:基於最少活躍呼叫數演演算法
  3. ConsistentHashLoadBalance:基於 hash 一致性
  4. RoundRobinLoadBalance:基於加權輪詢演演算法

具體的實現看下面解析。

原始碼分析

(一)AbstractLoadBalance

該類實現了LoadBalance介面,是負載均衡的抽象類,提供了權重計算的功能。

1.select

@Override
public <T> Invoker<T> select(List<Invoker<T>> invokers,URL url,Invocation invocation)
{ // 如果invokers為空則返回空 if (invokers == null || invokers.isEmpty()) return null; // 如果invokers只有一個服務提供者,則返回一個 if (invokers.size() == 1) return invokers.get(0); // 呼叫doSelect進行選擇 return doSelect(invokers,url,invocation); } 複製程式碼

該方法是選擇一個invoker,關鍵的選擇還是呼叫了doSelect方法,不過doSelect是一個抽象方法,由上述四種負載均衡策略來各自實現。

2.getWeight

protected int getWeight(Invoker<?> invoker,Invocation invocation) {
    // 獲得 weight 配置,即服務權重。預設為 100
    int weight = invoker.getUrl().getMethodParameter(invocation.getMethodName(),Constants.WEIGHT_KEY,Constants.DEFAULT_WEIGHT);
    if (weight > 0) {
        // 獲得啟動時間戳
        long timestamp = invoker.getUrl().getParameter(Constants.REMOTE_TIMESTAMP_KEY,0L);
        if (timestamp > 0L) {
            // 獲得啟動總時長
            int uptime = (int) (System.currentTimeMillis() - timestamp);
            // 獲得預熱需要總時長。預設為10分鐘
            int warmup = invoker.getUrl().getParameter(Constants.WARMUP_KEY,Constants.DEFAULT_WARMUP);
            // 如果服務執行時間小於預熱時間,則重新計算服務權重,即降權
            if (uptime > 0 && uptime < warmup) {
                weight = calculateWarmupWeight(uptime,warmup,weight);
            }
        }
    }
    return weight;
}
複製程式碼

該方法是獲得權重的方法,計算權重在calculateWarmupWeight方法中實現,該方法考慮到了jvm預熱的過程。

3.calculateWarmupWeight

static int calculateWarmupWeight(int uptime,int warmup,int weight) {
    // 計算權重 (uptime / warmup) * weight,進度百分比 * 權重
    int ww = (int) ((float) uptime / ((float) warmup / (float) weight));
    // 權重範圍為 [0,weight] 之間
    return ww < 1 ? 1 : (ww > weight ? weight : ww);
}
複製程式碼

該方法是計算權重的方法,其中計算公式是(uptime / warmup) * weight,含義就是進度百分比 * 權重值。

(二)RandomLoadBalance

該類是基於權重隨機演演算法的負載均衡實現類,我們先來講講原理,比如我有有一組伺服器 servers = [A,B,C],他們他們對應的權重為 weights = [6,3,1],權重總和為10,現在把這些權重值平鋪在一維座標值上,分別出現三個區域,A區域為[0,6),B區域為[6,9),C區域為[9,10),然後產生一個[0,10)的隨機數,看該數字落在哪個區間內,就用哪臺伺服器,這樣權重越大的,被擊中的概率就越大。

public class RandomLoadBalance extends AbstractLoadBalance {

    public static final String NAME = "random";

    /**
     * 隨機數產生器
     */
    private final Random random = new Random();

    @Override
    protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers,Invocation invocation) {
        // 獲得服務長度
        int length = invokers.size(); // Number of invokers
        // 總的權重
        int totalWeight = 0; // The sum of weights
        // 是否有相同的權重
        boolean sameWeight = true; // Every invoker has the same weight?
        // 遍歷每個服務,計算相應權重
        for (int i = 0; i < length; i++) {
            int weight = getWeight(invokers.get(i),invocation);
            // 計算總的權重值
            totalWeight += weight; // Sum
            // 如果前一個服務的權重值不等於後一個則sameWeight為false
            if (sameWeight && i > 0
                    && weight != getWeight(invokers.get(i - 1),invocation)) {
                sameWeight = false;
            }
        }
        // 如果每個服務權重都不同,並且總的權重值不為0
        if (totalWeight > 0 && !sameWeight) {
            // If (not every invoker has the same weight & at least one invoker's weight>0),select randomly based on totalWeight.
            int offset = random.nextInt(totalWeight);
            // Return a invoker based on the random value.
            // 迴圈讓 offset 數減去服務提供者權重值,當 offset 小於0時,返回相應的 Invoker。
            // 舉例說明一下,我們有 servers = [A,C],weights = [6,1],offset = 7。
            // 第一次迴圈,offset - 6 = 1 > 0,即 offset > 6,
            // 表明其不會落在伺服器 A 對應的區間上。
            // 第二次迴圈,offset - 3 = -2 < 0,即 6 < offset < 9,
            // 表明其會落在伺服器 B 對應的區間上
            for (int i = 0; i < length; i++) {
                offset -= getWeight(invokers.get(i),invocation);
                if (offset < 0) {
                    return invokers.get(i);
                }
            }
        }
        // If all invokers have the same weight value or totalWeight=0,return evenly.
        // 如果所有服務提供者權重值相同,此時直接隨機返回一個即可
        return invokers.get(random.nextInt(length));
    }

}
複製程式碼

該演演算法比較好理解,當然 RandomLoadBalance 也存在一定的缺點,當呼叫次數比較少時,Random 產生的隨機數可能會比較集中,此時多數請求會落到同一臺伺服器上,不過影響不大。

(三)LeastActiveLoadBalance

該負載均衡策略基於最少活躍呼叫數演演算法,某個服務活躍呼叫數越小,表明該服務提供者效率越高,也就表明單位時間內能夠處理的請求更多。此時應該選擇該類伺服器。實現很簡單,就是每一個服務都有一個活躍數active來記錄該服務的活躍值,每收到一個請求,該active就會加1,,沒完成一個請求,active就會減1。在服務執行一段時間後,效能好的服務提供者處理請求的速度更快,因此活躍數下降的也越快,此時這樣的服務提供者能夠優先獲取到新的服務請求。除了最小活躍數,還引入了權重值,也就是當活躍數一樣的時候,選擇利用權重法來進行選擇,如果權重也一樣,那麼隨機選擇一個。

public class LeastActiveLoadBalance extends AbstractLoadBalance {

    public static final String NAME = "leastactive";

    /**
     * 隨機器
     */
    private final Random random = new Random();

    @Override
    protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers,Invocation invocation) {
        // 獲得服務長度
        int length = invokers.size(); // Number of invokers
        // 最小的活躍數
        int leastActive = -1; // The least active value of all invokers
        // 具有相同“最小活躍數”的服務者提供者(以下用 Invoker 代稱)數量
        int leastCount = 0; // The number of invokers having the same least active value (leastActive)
        // leastIndexs 用於記錄具有相同“最小活躍數”的 Invoker 在 invokers 列表中的下標資訊
        int[] leastIndexs = new int[length]; // The index of invokers having the same least active value (leastActive)
        // 總的權重
        int totalWeight = 0; // The sum of with warmup weights
        // 第一個最小活躍數的 Invoker 權重值,用於與其他具有相同最小活躍數的 Invoker 的權重進行對比,
        // 以檢測是否“所有具有相同最小活躍數的 Invoker 的權重”均相等
        int firstWeight = 0; // Initial value,used for comparision
        // 是否權重相同
        boolean sameWeight = true; // Every invoker has the same weight value?
        for (int i = 0; i < length; i++) {
            Invoker<T> invoker = invokers.get(i);
            // 獲取 Invoker 對應的活躍數
            int active = RpcStatus.getStatus(invoker.getUrl(),invocation.getMethodName()).getActive(); // Active number
            // 獲得該服務的權重
            int afterWarmup = getWeight(invoker,invocation); // Weight
            // 發現更小的活躍數,重新開始
            if (leastActive == -1 || active < leastActive) { // Restart,when find a invoker having smaller least active value.
                // 記錄當前最小的活躍數
                leastActive = active; // Record the current least active value
                // 更新 leastCount 為 1
                leastCount = 1; // Reset leastCount,count again based on current leastCount
                // 記錄當前下標值到 leastIndexs 中
                leastIndexs[0] = i; // Reset
                totalWeight = afterWarmup; // Reset
                firstWeight = afterWarmup; // Record the weight the first invoker
                sameWeight = true; // Reset,every invoker has the same weight value?
                // 如果當前 Invoker 的活躍數 active 與最小活躍數 leastActive 相同
            } else if (active == leastActive) { // If current invoker's active value equals with leaseActive,then accumulating.
                // 在 leastIndexs 中記錄下當前 Invoker 在 invokers 集合中的下標
                leastIndexs[leastCount++] = i; // Record index number of this invoker
                // 累加權重
                totalWeight += afterWarmup; // Add this invoker's weight to totalWeight.
                // If every invoker has the same weight?
                if (sameWeight && i > 0
                        && afterWarmup != firstWeight) {
                    sameWeight = false;
                }
            }
        }
        // assert(leastCount > 0)
        // 當只有一個 Invoker 具有最小活躍數,此時直接返回該 Invoker 即可
        if (leastCount == 1) {
            // If we got exactly one invoker having the least active value,return this invoker directly.
            return invokers.get(leastIndexs[0]);
        }
        // 有多個 Invoker 具有相同的最小活躍數,但它們之間的權重不同
        if (!sameWeight && totalWeight > 0) {
            // If (not every invoker has the same weight & at least one invoker's weight>0),select randomly based on totalWeight.
            // 隨機生成一個數字
            int offsetWeight = random.nextInt(totalWeight) + 1;
            // Return a invoker based on the random value.
            // 相關演演算法可以參考RandomLoadBalance
            for (int i = 0; i < leastCount; i++) {
                int leastIndex = leastIndexs[i];
                offsetWeight -= getWeight(invokers.get(leastIndex),invocation);
                if (offsetWeight <= 0)
                    return invokers.get(leastIndex);
            }
        }
        // If all invokers have the same weight value or totalWeight=0,return evenly.
        // 如果權重一樣,則隨機取一個
        return invokers.get(leastIndexs[random.nextInt(leastCount)]);
    }
}
複製程式碼

前半部分在進行最小活躍數的策略,後半部分在進行權重的隨機策略,可以參見RandomLoadBalance。

(四)ConsistentHashLoadBalance

該類是負載均衡基於 hash 一致性的邏輯實現。一致性雜湊演演算法由麻省理工學院的 Karger 及其合作者於1997年提供出的,一開始被大量運用於快取系統的負載均衡。它的工作原理是這樣的:首先根據 ip 或其他的資訊為快取節點生成一個 hash,在dubbo中使用引數進行計算hash。並將這個 hash 投射到 [0,232 - 1] 的圓環上,當有查詢或寫入請求時,則生成一個 hash 值。然後查詢第一個大於或等於該 hash 值的快取節點,併到這個節點中查詢或寫入快取項。如果當前節點掛了,則在下一次查詢或寫入快取時,為快取項查詢另一個大於其 hash 值的快取節點即可。大致效果如下圖所示(引用一下官網的圖)

每個快取節點在圓環上佔據一個位置。如果快取項的 key 的 hash 值小於快取節點 hash 值,則到該快取節點中儲存或讀取快取項,這裡有兩個概念不要弄混,快取節點就好比dubbo中的服務提供者,會有很多的服務提供者,而快取項就好比是服務引用的消費者。比如下面綠色點對應的快取項也就是服務消費者將會被儲存到 cache-2 節點中。由於 cache-3 掛了,原本應該存到該節點中的快取項也就是服務消費者最終會儲存到 cache-4 節點中,也就是呼叫cache-4 這個服務提供者。

consistent-hash

但是在hash一致性演演算法並不能夠保證hash演演算法的平衡性,就拿上面的例子來看,cache-3掛掉了,那該節點下的所有快取項都要儲存到 cache-4 節點中,這就導致hash值低的一直往高的儲存,會面臨一個不平衡的現象,見下圖:

consistent-hash-data-incline

可以看到最後會變成類似不平衡的現象,那我們應該怎麼避免這樣的事情,做到平衡性,那就需要引入虛擬節點,虛擬節點是實際節點在 hash 空間的複製品,“虛擬節點”在 hash 空間中以hash值排列。比如下圖:

consistent-hash-invoker

可以看到各個節點都被均勻分佈在圓環上,而某一個服務提供者居然有多個節點存在,分別跟其他節點交錯排列,這樣做的目的就是避免資料傾斜問題,也就是由於節點不夠分散,導致大量請求落到了同一個節點上,而其他節點只會接收到了少量請求的情況。類似第二張圖的情況。

看完原理,接下來我們來看看程式碼

1.doSelect

protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers,Invocation invocation) {
    // 獲得方法名
    String methodName = RpcUtils.getMethodName(invocation);
    // 獲得key
    String key = invokers.get(0).getUrl().getServiceKey() + "." + methodName;
    // 獲取 invokers 原始的 hashcode
    int identityHashCode = System.identityHashCode(invokers);
    // 從一致性 hash 選擇器集合中獲得一致性 hash 選擇器
    ConsistentHashSelector<T> selector = (ConsistentHashSelector<T>) selectors.get(key);
    // 如果等於空或者選擇器的hash值不等於原始的值,則新建一個一致性 hash 選擇器,並且加入到集合
    if (selector == null || selector.identityHashCode != identityHashCode) {
        selectors.put(key,new ConsistentHashSelector<T>(invokers,methodName,identityHashCode));
        selector = (ConsistentHashSelector<T>) selectors.get(key);
    }
    // 選擇器選擇一個invoker
    return selector.select(invocation);
}
複製程式碼

該方法也做了一些invokers 列表是不是變動過,以及建立 ConsistentHashSelector等工作,然後呼叫selector.select來進行選擇。

2.ConsistentHashSelector

private static final class ConsistentHashSelector<T> {

    /**
     * 儲存 Invoker 虛擬節點
     */
    private final TreeMap<Long,Invoker<T>> virtualInvokers;

    /**
     * 每個Invoker 對應的虛擬節點數
     */
    private final int replicaNumber;

    /**
     * 原始雜湊值
     */
    private final int identityHashCode;

    /**
     * 取值引數位置陣列
     */
    private final int[] argumentIndex;

    ConsistentHashSelector(List<Invoker<T>> invokers,String methodName,int identityHashCode) {
        this.virtualInvokers = new TreeMap<Long,Invoker<T>>();
        this.identityHashCode = identityHashCode;
        URL url = invokers.get(0).getUrl();
        // 獲取虛擬節點數,預設為160
        this.replicaNumber = url.getMethodParameter(methodName,"hash.nodes",160);
        // 獲取參與 hash 計算的引數下標值,預設對第一個引數進行 hash 運算
        String[] index = Constants.COMMA_SPLIT_PATTERN.split(url.getMethodParameter(methodName,"hash.arguments","0"));
        // 建立下標陣列
        argumentIndex = new int[index.length];
        // 遍歷
        for (int i = 0; i < index.length; i++) {
            // 記錄下標
            argumentIndex[i] = Integer.parseInt(index[i]);
        }
        // 遍歷invokers
        for (Invoker<T> invoker : invokers) {
            String address = invoker.getUrl().getAddress();
            for (int i = 0; i < replicaNumber / 4; i++) {
                // 對 address + i 進行 md5 運算,得到一個長度為16的位元組陣列
                byte[] digest = md5(address + i);
                // // 對 digest 部分位元組進行4次 hash 運算,得到四個不同的 long 型正整數
                for (int h = 0; h < 4; h++) {
                    // h = 0 時,取 digest 中下標為 0 ~ 3 的4個位元組進行位運算
                    // h = 1 時,取 digest 中下標為 4 ~ 7 的4個位元組進行位運算
                    // h = 2,h = 3 時過程同上
                    long m = hash(digest,h);
                    // 將 hash 到 invoker 的對映關係儲存到 virtualInvokers 中,
                    // virtualInvokers 需要提供高效的查詢操作,因此選用 TreeMap 作為儲存結構
                    virtualInvokers.put(m,invoker);
                }
            }
        }
    }

    /**
     * 選擇一個invoker
     * @param invocation
     * @return
     */
    public Invoker<T> select(Invocation invocation) {
        // 將引數轉為 key
        String key = toKey(invocation.getArguments());
        // 對引數 key 進行 md5 運算
        byte[] digest = md5(key);
        // 取 digest 陣列的前四個位元組進行 hash 運算,再將 hash 值傳給 selectForKey 方法,
        // 尋找合適的 Invoker
        return selectForKey(hash(digest,0));
    }

    /**
     * 將引數轉為 key
     * @param args
     * @return
     */
    private String toKey(Object[] args) {
        StringBuilder buf = new StringBuilder();
        // 遍歷引數下標
        for (int i : argumentIndex) {
            if (i >= 0 && i < args.length) {
                // 拼接引數,生成key
                buf.append(args[i]);
            }
        }
        return buf.toString();
    }

    /**
     * 通過hash選擇invoker
     * @param hash
     * @return
     */
    private Invoker<T> selectForKey(long hash) {
        // 到 TreeMap 中查詢第一個節點值大於或等於當前 hash 的 Invoker
        Map.Entry<Long,Invoker<T>> entry = virtualInvokers.tailMap(hash,true).firstEntry();
        // 如果 hash 大於 Invoker 在圓環上最大的位置,此時 entry = null,
        // 需要將 TreeMap 的頭節點賦值給 entry
        if (entry == null) {
            entry = virtualInvokers.firstEntry();
        }
        // 返回選擇的invoker
        return entry.getValue();
    }

    /**
     * 計算hash值
     * @param digest
     * @param number
     * @return
     */
    private long hash(byte[] digest,int number) {
        return (((long) (digest[3 + number * 4] & 0xFF) << 24)
                | ((long) (digest[2 + number * 4] & 0xFF) << 16)
                | ((long) (digest[1 + number * 4] & 0xFF) << 8)
                | (digest[number * 4] & 0xFF))
                & 0xFFFFFFFFL;
    }

    /**
     * md5
     * @param value
     * @return
     */
    private byte[] md5(String value) {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(e.getMessage(),e);
        }
        md5.reset();
        byte[] bytes;
        try {
            bytes = value.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e.getMessage(),e);
        }
        md5.update(bytes);
        return md5.digest();
    }

}
複製程式碼

該類是內部類,是一致性 hash 選擇器,首先看它的屬性,利用TreeMap來儲存 Invoker 虛擬節點,因為需要提供高效的查詢操作。再看看它的構造方法,執行了一系列的初始化邏輯,比如從配置中獲取虛擬節點數以及參與 hash 計算的引數下標,預設情況下只使用第一個引數進行 hash,並且ConsistentHashLoadBalance 的負載均衡邏輯只受引數值影響,具有相同引數值的請求將會被分配給同一個服務提供者。還有一個select方法,比較簡單,先進行md5運算。然後hash,最後選擇出對應的invoker。

(五)RoundRobinLoadBalance

該類是負載均衡基於加權輪詢演演算法的實現。那麼什麼是加權輪詢,輪詢很好理解,比如我第一個請求分配給A伺服器,第二個請求分配給B伺服器,第三個請求分配給C伺服器,第四個請求又分配給A伺服器,這就是輪詢,但是這隻適合每臺伺服器效能相近的情況,這種是一種非常理想的情況,那更多的是每臺伺服器的效能都會有所差異,這個時候效能差的伺服器被分到等額的請求,就會需要承受壓力大宕機的情況,這個時候我們需要對輪詢加權,我舉個例子,伺服器 A、B、C 權重比為 6:3:1,那麼在10次請求中,伺服器 A 將收到其中的6次請求,伺服器 B 會收到其中的3次請求,伺服器 C 則收到其中的1次請求,也就是說每臺伺服器能夠收到的請求歸結於它的權重。

1.屬性

/**
 * 回收間隔
 */
private static int RECYCLE_PERIOD = 60000;
複製程式碼

2.WeightedRoundRobin

protected static class WeightedRoundRobin {
    /**
     * 權重
     */
    private int weight;
    /**
     * 當前已經有多少請求落在該服務提供者身上,也可以看成是一個動態的權重
     */
    private AtomicLong current = new AtomicLong(0);
    /**
     * 最後一次更新時間
     */
    private long lastUpdate;
    public int getWeight() {
        return weight;
    }
    public void setWeight(int weight) {
        this.weight = weight;
        current.set(0);
    }
    public long increaseCurrent() {
        return current.addAndGet(weight);
    }
    public void sel(int total) {
        current.addAndGet(-1 * total);
    }
    public long getLastUpdate() {
        return lastUpdate;
    }
    public void setLastUpdate(long lastUpdate) {
        this.lastUpdate = lastUpdate;
    }
}
複製程式碼

該內部類是一個加權輪詢器,它記錄了某一個服務提供者的一些資料,比如權重、比如當前已經有多少請求落在該服務提供者上等。

3.doSelect

@Override
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers,Invocation invocation) {
    // key = 全限定類名 + "." + 方法名,比如 com.xxx.DemoService.sayHello
    String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName();
    ConcurrentMap<String,WeightedRoundRobin> map = methodWeightMap.get(key);
    if (map == null) {
        methodWeightMap.putIfAbsent(key,new ConcurrentHashMap<String,WeightedRoundRobin>());
        map = methodWeightMap.get(key);
    }
    // 權重總和
    int totalWeight = 0;
    // 最小權重
    long maxCurrent = Long.MIN_VALUE;
    // 獲得現在的時間戳
    long now = System.currentTimeMillis();
    // 建立已經選擇的invoker
    Invoker<T> selectedInvoker = null;
    // 建立加權輪詢器
    WeightedRoundRobin selectedWRR = null;

    // 下面這個迴圈主要做了這樣幾件事情:
    //   1. 遍歷 Invoker 列表,檢測當前 Invoker 是否有
    //      相應的 WeightedRoundRobin,沒有則建立
    //   2. 檢測 Invoker 權重是否發生了變化,若變化了,
    //      則更新 WeightedRoundRobin 的 weight 欄位
    //   3. 讓 current 欄位加上自身權重,等價於 current += weight
    //   4. 設定 lastUpdate 欄位,即 lastUpdate = now
    //   5. 尋找具有最大 current 的 Invoker,以及 Invoker 對應的 WeightedRoundRobin,
    //      暫存起來,留作後用
    //   6. 計算權重總和
    for (Invoker<T> invoker : invokers) {
        // 獲得identify的值
        String identifyString = invoker.getUrl().toIdentityString();
        // 獲得加權輪詢器
        WeightedRoundRobin weightedRoundRobin = map.get(identifyString);
        // 計算權重
        int weight = getWeight(invoker,invocation);
        // 如果權重小於0,則設定0
        if (weight < 0) {
            weight = 0;
        }
        // 如果加權輪詢器為空
        if (weightedRoundRobin == null) {
            // 建立加權輪詢器
            weightedRoundRobin = new WeightedRoundRobin();
            // 設定權重
            weightedRoundRobin.setWeight(weight);
            // 加入集合
            map.putIfAbsent(identifyString,weightedRoundRobin);
            weightedRoundRobin = map.get(identifyString);
        }
        // 如果權重跟之前的權重不一樣,則重新設定權重
        if (weight != weightedRoundRobin.getWeight()) {
            //weight changed
            weightedRoundRobin.setWeight(weight);
        }
        // 計數器加1
        long cur = weightedRoundRobin.increaseCurrent();
        // 更新最後一次更新時間
        weightedRoundRobin.setLastUpdate(now);
        // 當落在該服務提供者的統計數大於最大可承受的數
        if (cur > maxCurrent) {
            // 賦值
            maxCurrent = cur;
            // 被選擇的selectedInvoker賦值
            selectedInvoker = invoker;
            // 被選擇的加權輪詢器賦值
            selectedWRR = weightedRoundRobin;
        }
        // 累加
        totalWeight += weight;
    }
    // 如果更新鎖不能獲得並且invokers的大小跟map大小不匹配
    // 對 <identifyString,WeightedRoundRobin> 進行檢查,過濾掉長時間未被更新的節點。
    // 該節點可能掛了,invokers 中不包含該節點,所以該節點的 lastUpdate 長時間無法被更新。
    // 若未更新時長超過閾值後,就會被移除掉,預設閾值為60秒。
    if (!updateLock.get() && invokers.size() != map.size()) {
        if (updateLock.compareAndSet(false,true)) {
            try {
                // copy -> modify -> update reference
                ConcurrentMap<String,WeightedRoundRobin> newMap = new ConcurrentHashMap<String,WeightedRoundRobin>();
                // 複製
                newMap.putAll(map);
                Iterator<Entry<String,WeightedRoundRobin>> it = newMap.entrySet().iterator();
                // 輪詢
                while (it.hasNext()) {
                    Entry<String,WeightedRoundRobin> item = it.next();
                    // 如果大於回收時間,則進行回收
                    if (now - item.getValue().getLastUpdate() > RECYCLE_PERIOD) {
                        // 從集合中移除
                        it.remove();
                    }
                }
                // 加入集合
                methodWeightMap.put(key,newMap);
            } finally {
                updateLock.set(false);
            }
        }
    }
    // 如果被選擇的selectedInvoker不為空
    if (selectedInvoker != null) {
        // 設定總的權重
        selectedWRR.sel(totalWeight);
        return selectedInvoker;
    }
    // should not happen here
    return invokers.get(0);
}
複製程式碼

該方法是選擇的核心,其實關鍵是一些資料記錄,在每次請求都會記錄落在該服務上的請求數,然後在根據權重來分配,並且會有回收時間來處理一些長時間未被更新的節點。

後記

該部分相關的原始碼解析地址:github.com/CrazyHZM/in…

該文章講解了叢集中關於負載均衡實現的部分,每個演演算法都是現在很普遍的負載均衡演演算法,希望大家細細品味。接下來我將開始對叢集模組關於分組聚合部分進行講解。