diff --git a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalance.java b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalance.java index adfd04b3161..50215d699bd 100644 --- a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalance.java +++ b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalance.java @@ -49,20 +49,17 @@ protected Invoker doSelect(List> invokers, URL url, Invocation int length = invokers.size(); // Every invoker has the same weight? boolean sameWeight = true; - // the weight of every invokers + // the maxWeight of every invokers, the minWeight = 0 or the maxWeight of the last invoker int[] weights = new int[length]; - // the first invoker's weight - int firstWeight = getWeight(invokers.get(0), invocation); - weights[0] = firstWeight; // The sum of weights - int totalWeight = firstWeight; - for (int i = 1; i < length; i++) { + int totalWeight = 0; + for (int i = 0; i < length; i++) { int weight = getWeight(invokers.get(i), invocation); - // save for later use - weights[i] = weight; // Sum totalWeight += weight; - if (sameWeight && weight != firstWeight) { + // save for later use + weights[i] = totalWeight; + if (sameWeight && totalWeight != weight * (i + 1)) { sameWeight = false; } } @@ -71,8 +68,7 @@ protected Invoker doSelect(List> invokers, URL url, Invocation int offset = ThreadLocalRandom.current().nextInt(totalWeight); // Return a invoker based on the random value. for (int i = 0; i < length; i++) { - offset -= weights[i]; - if (offset < 0) { + if (offset < weights[i]) { return invokers.get(i); } }