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

Posted on 2019-01-08 20:22 21004129 阅读() 评论() 编辑 收藏

/**
* 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));
}

}


版权声明:本文为walson原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/walson/p/10240279.html