1. 程式人生 > >【Dubbo原始碼學習】負載均衡演算法(1)-隨機演算法

【Dubbo原始碼學習】負載均衡演算法(1)-隨機演算法

/**
* random load balance.
*
*/
public class RandomLoadBalance extends AbstractLoadBalance {

public static final String NAME = "random";

@Override
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
int length = invokers.size(); // Number of invokers
boolean sameWeight = true; // Every invoker has the same weight?
int firstWeight = getWeight(invokers.get(0), invocation);
int totalWeight = firstWeight; // The sum of weights
//判斷是否所有服務提供者的權重都相同

for (int i = 1; i < length; i++) {
int weight = getWeight(invokers.get(i), invocation);
totalWeight += weight; // Sum
if (sameWeight && weight != firstWeight) {
sameWeight = false;
}
}
//所有服務提供者的權重不都相同,且權重之和>0,則隨機生成一個0-totalWeight的隨機數,

// 然後用此隨機數迴圈減去服務提供者的權重直到改值<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 = ThreadLocalRandom.current().nextInt(totalWeight);
// Return a invoker based on the random value.
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(ThreadLocalRandom.current().nextInt(length));
}

}