简化后的
/**
* 每个服务维护一个活跃数计数器。当A机器开始处理请求,该计数器加1,此时A还未处理完成。
* 若处理完毕则计数器减1。而B机器接受到请求后很快处理完毕。
* 那么A,B的活跃数分别是1,0。当又产生了一个新的请求,
* 则选择B机器去执行(B活跃数最小),这样使慢的机器A收到少的请求。
* @param invokers
* @param url
* @param invocation
* @param <T>
* @return
*/
@Override
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
// Number of invokers 总个数
int length = invokers.size();
// The least active value of all invokers 最小的活跃数
int leastActive = -1;
// The number of invokers having the same least active value (leastActive) 相同最小活跃数的个数
int leastCount = 0;
// The index of invokers having the same least active value (leastActive) 相同最小活跃数的下标
int[] leastIndexes = new int[length];
//查找优先级 先找活跃最小值最小的
for (int i = 0; i < length; i++) {
Invoker<T> invoker = invokers.get(i);
// 获取当前提供方机器活跃数越小,越优秀
int active = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName()).getActive();
// 如果最小是-1或者是小于-1
if (leastActive == -1 || active < leastActive) {
leastActive = active;
leastCount = 1;
leastIndexes[0] = i;
} else if (active == leastActive) {
// 累计相同最小活跃数下标
leastIndexes[leastCount++] = i;
}
// 如果只有一个最小则直接返回
if (leastCount == 1) {
return invokers.get(leastIndexes[0]);
}
// 。。。。。。。。
}
// 如果权重相同或权重为0则均等随机(权重代码已略去)
return invokers.get(leastIndexes[ThreadLocalRandom.current().nextInt(leastCount)]);
}