Merge JedisSlotBasedConnectionGuaranteedConnectionHandler to JedisSlotBasedConnectionHandler

This commit is contained in:
Marcos Nils
2014-03-03 18:54:24 -03:00
parent b5fe10729b
commit 4e78b811be
3 changed files with 47 additions and 73 deletions

View File

@@ -1,7 +1,12 @@
package redis.clients.jedis;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import redis.clients.jedis.exceptions.JedisConnectionException;
public class JedisSlotBasedConnectionHandler extends
JedisClusterConnectionHandler {
@@ -10,7 +15,35 @@ public class JedisSlotBasedConnectionHandler extends
}
public Jedis getConnection() {
return getRandomConnection().getResource();
// In antirez's redis-rb-cluster implementation,
// getRandomConnection always return valid connection (able to ping-pong)
// or exception if all connections are invalid
List<JedisPool> pools = getShuffledNodesPool();
for (JedisPool pool : pools) {
Jedis jedis = null;
try {
jedis = pool.getResource();
if (jedis == null) {
continue;
}
String result = jedis.ping();
if (result.equalsIgnoreCase("pong"))
return jedis;
pool.returnBrokenResource(jedis);
} catch (JedisConnectionException ex) {
if (jedis != null) {
pool.returnBrokenResource(jedis);
}
}
}
throw new JedisConnectionException("no reachable node in cluster");
}
@Override
@@ -21,10 +54,19 @@ public class JedisSlotBasedConnectionHandler extends
@Override
public Jedis getConnectionFromSlot(int slot) {
JedisPool connectionPool = slots.get(slot);
if (connectionPool == null) {
connectionPool = getRandomConnection();
if (connectionPool != null) {
// It can't guaranteed to get valid connection because of node assignment
return connectionPool.getResource();
} else {
return getConnection();
}
return connectionPool.getResource();
}
private List<JedisPool> getShuffledNodesPool() {
List<JedisPool> pools = new ArrayList<JedisPool>();
pools.addAll(nodes.values());
Collections.shuffle(pools);
return pools;
}
}