@Override protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, 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 //记录所有的invokers的weight是否是一样的 if (sameWeight && i > 0 && weight != getWeight(invokers.get(i - 1), invocation)) { sameWeight = false; } } //如果不是所有的invoker权重都一样 if (totalWeight > 0 && !sameWeight) { // If (not every invoker has the same weight & at least one invoker's weight>0), select randomly based on totalWeight. //获取随机数的范围是[0, 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) { //返回invoker return invokers.get(i); } } } //如果所有的invoker都是一样的weight,则直接获取随机数,并返回 //这里使用了ThreadLocalRandom做了优化 // If all invokers have the same weight value or totalWeight=0, return evenly. return invokers.get(ThreadLocalRandom.current().nextInt(length)); }