Add test for redis cluster max redirections and refactor JedisClusterCommand exception handling

This commit is contained in:
Marcos Nils
2014-01-16 18:04:27 -03:00
parent 2f9564e1d3
commit 46733c5d5a
7 changed files with 228 additions and 168 deletions

View File

@@ -2,7 +2,8 @@ package redis.clients.jedis;
import redis.clients.jedis.exceptions.JedisAskDataException;
import redis.clients.jedis.exceptions.JedisClusterException;
import redis.clients.jedis.exceptions.JedisMovedDataException;
import redis.clients.jedis.exceptions.JedisClusterMaxRedirectionsException;
import redis.clients.jedis.exceptions.JedisRedirectionException;
import redis.clients.util.JedisClusterCRC16;
public abstract class JedisClusterCommand<T> {
@@ -10,18 +11,25 @@ public abstract class JedisClusterCommand<T> {
private boolean asking = false;
private JedisClusterConnectionHandler connectionHandler;
private int commandTimeout;
private int redirections;
// private boolean asking = false;
public JedisClusterCommand(JedisClusterConnectionHandler connectionHandler) {
public JedisClusterCommand(JedisClusterConnectionHandler connectionHandler, int timeout, int maxRedirections) {
this.connectionHandler = connectionHandler;
this.commandTimeout = timeout;
this.redirections = maxRedirections;
}
public abstract T execute();
public T run(String key) {
try {
if (key == null) {
throw new JedisClusterException("No way to dispatch this command to Redis Cluster.");
} else if (redirections == 0) {
throw new JedisClusterMaxRedirectionsException("Too many Cluster redirections?");
}
connectionHandler.getConnectionFromSlot(JedisClusterCRC16.getSlot(key));
if (asking) {
@@ -29,13 +37,17 @@ public abstract class JedisClusterCommand<T> {
connectionHandler.getConnection().asking();
}
return execute();
} catch (JedisMovedDataException jme) {
this.connectionHandler.assignSlotToNode(jme.getSlot(), jme.getTargetNode());
return run(key);
} catch (JedisAskDataException jae) {
asking = true;
this.connectionHandler.assignSlotToNode(jae.getSlot(), jae.getTargetNode());
return run(key);
} catch (JedisRedirectionException jre) {
return handleRedirection(jre, key);
}
}
}
private T handleRedirection(JedisRedirectionException jre, String key) {
if (jre instanceof JedisAskDataException) {
asking = true;
}
redirections--;
this.connectionHandler.assignSlotToNode(jre.getSlot(), jre.getTargetNode());
return run(key);
}
}