博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

【Dubbo源码学习】负载均衡算法(1)-随机算法

Posted on 2019-01-08 20:22  21004129  阅读(349)  评论(0编辑  收藏  举报
/**
* 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));
}

}