From 3b5c1f848b4c62a993d18f4ca19a3a04a69ed0a0 Mon Sep 17 00:00:00 2001 From: Shailender Bathula Date: Thu, 18 Aug 2016 11:13:14 +1200 Subject: [PATCH] #582: Always find a connection to read --- .../balancer/WeightedRoundRobinBalancer.java | 32 ++++++++++++++----- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/redisson/src/main/java/org/redisson/connection/balancer/WeightedRoundRobinBalancer.java b/redisson/src/main/java/org/redisson/connection/balancer/WeightedRoundRobinBalancer.java index b7f43d0c0..c5227783c 100644 --- a/redisson/src/main/java/org/redisson/connection/balancer/WeightedRoundRobinBalancer.java +++ b/redisson/src/main/java/org/redisson/connection/balancer/WeightedRoundRobinBalancer.java @@ -117,7 +117,6 @@ public class WeightedRoundRobinBalancer implements LoadBalancer { Map weightsCopy = new HashMap(weights); - List clientsCopy = new ArrayList(); synchronized (this) { for (Iterator iterator = weightsCopy.values().iterator(); iterator.hasNext();) { @@ -136,15 +135,18 @@ public class WeightedRoundRobinBalancer implements LoadBalancer { weightsCopy = weights; } + List clientsCopy = findClients(clients, weightsCopy); - for (InetSocketAddress addr : weightsCopy.keySet()) { - for (ClientConnectionsEntry clientConnectionsEntry : clients) { - if (clientConnectionsEntry.getClient().getAddr().equals(addr) - && !clientConnectionsEntry.isFreezed()) { - clientsCopy.add(clientConnectionsEntry); - break; - } + // If there are no connections available to servers that have a weight counter + // remaining, then reset the weight counters and find a connection again. In the worst + // case, there should always be a connection to the master. + if (clientsCopy.isEmpty()) { + for (WeightEntry entry : weights.values()) { + entry.resetWeightCounter(); } + + weightsCopy = weights; + clientsCopy = findClients(clients, weightsCopy); } int ind = Math.abs(index.incrementAndGet() % clientsCopy.size()); @@ -155,4 +157,18 @@ public class WeightedRoundRobinBalancer implements LoadBalancer { } } + private List findClients(List clients, Map weightsCopy) { + List clientsCopy = new ArrayList(); + for (InetSocketAddress addr : weightsCopy.keySet()) { + for (ClientConnectionsEntry clientConnectionsEntry : clients) { + if (clientConnectionsEntry.getClient().getAddr().equals(addr) + && !clientConnectionsEntry.isFreezed()) { + clientsCopy.add(clientConnectionsEntry); + break; + } + } + } + return clientsCopy; + } + }