Apply "Format" to all files, Closes #765

This commit is contained in:
Jungtaek Lim
2014-10-09 21:08:05 +09:00
parent 4db138921e
commit 7f45a2ca24
63 changed files with 1243 additions and 1100 deletions

View File

@@ -26,7 +26,7 @@ public interface BasicRedisPipeline {
Response<String> flushAll(); Response<String> flushAll();
Response<String> info(); Response<String> info();
Response<List<String>> time(); Response<List<String>> time();
Response<Long> dbSize(); Response<Long> dbSize();

View File

@@ -51,7 +51,7 @@ public class BinaryClient extends Connection {
public BinaryClient() { public BinaryClient() {
super(); super();
} }
public BinaryClient(final String host) { public BinaryClient(final String host) {
super(host); super(host);
} }
@@ -208,7 +208,7 @@ public class BinaryClient extends Connection {
} }
public void incrByFloat(final byte[] key, final double value) { public void incrByFloat(final byte[] key, final double value) {
sendCommand(INCRBYFLOAT, key, toByteArray(value)); sendCommand(INCRBYFLOAT, key, toByteArray(value));
} }
public void incr(final byte[] key) { public void incr(final byte[] key) {
@@ -328,7 +328,7 @@ public class BinaryClient extends Connection {
public void sadd(final byte[] key, final byte[]... members) { public void sadd(final byte[] key, final byte[]... members) {
sendCommand(SADD, joinParameters(key, members)); sendCommand(SADD, joinParameters(key, members));
} }
public void smembers(final byte[] key) { public void smembers(final byte[] key) {
sendCommand(SMEMBERS, key); sendCommand(SMEMBERS, key);
} }
@@ -568,10 +568,11 @@ public class BinaryClient extends Connection {
public void punsubscribe(final byte[]... patterns) { public void punsubscribe(final byte[]... patterns) {
sendCommand(PUNSUBSCRIBE, patterns); sendCommand(PUNSUBSCRIBE, patterns);
} }
public void pubsub(final byte[]... args) { public void pubsub(final byte[]... args) {
sendCommand(PUBSUB, args); sendCommand(PUBSUB, args);
} }
public void zcount(final byte[] key, final double min, final double max) { public void zcount(final byte[] key, final double min, final double max) {
byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf" byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf"
@@ -835,7 +836,7 @@ public class BinaryClient extends Connection {
args.addAll(params.getParams()); args.addAll(params.getParams());
sendCommand(ZINTERSTORE, args.toArray(new byte[args.size()][])); sendCommand(ZINTERSTORE, args.toArray(new byte[args.size()][]));
} }
public void zlexcount(final byte[] key, final byte[] min, final byte[] max) { public void zlexcount(final byte[] key, final byte[] min, final byte[] max) {
sendCommand(ZLEXCOUNT, key, min, max); sendCommand(ZLEXCOUNT, key, min, max);
} }
@@ -844,22 +845,23 @@ public class BinaryClient extends Connection {
sendCommand(ZRANGEBYLEX, key, min, max); sendCommand(ZRANGEBYLEX, key, min, max);
} }
public void zrangeByLex(final byte[] key, final byte[] min, final byte[] max, public void zrangeByLex(final byte[] key, final byte[] min,
final int offset, final int count) { final byte[] max, final int offset, final int count) {
sendCommand(ZRANGEBYLEX, key, min, max, LIMIT.raw, sendCommand(ZRANGEBYLEX, key, min, max, LIMIT.raw, toByteArray(offset),
toByteArray(count));
}
public void zrevrangeByLex(final byte[] key, final byte[] max,
final byte[] min) {
sendCommand(ZREVRANGEBYLEX, key, max, min);
}
public void zrevrangeByLex(final byte[] key, final byte[] max,
final byte[] min, final int offset, final int count) {
sendCommand(ZREVRANGEBYLEX, key, max, min, LIMIT.raw,
toByteArray(offset), toByteArray(count)); toByteArray(offset), toByteArray(count));
} }
public void zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min) {
sendCommand(ZREVRANGEBYLEX, key, max, min);
}
public void zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min,
final int offset, final int count) {
sendCommand(ZREVRANGEBYLEX, key, max, min, LIMIT.raw,
toByteArray(offset), toByteArray(count));
}
public void zremrangeByLex(byte[] key, byte[] min, byte[] max) { public void zremrangeByLex(byte[] key, byte[] min, byte[] max) {
sendCommand(ZREMRANGEBYLEX, key, min, max); sendCommand(ZREMRANGEBYLEX, key, min, max);
} }
@@ -965,15 +967,16 @@ public class BinaryClient extends Connection {
public void getbit(byte[] key, long offset) { public void getbit(byte[] key, long offset) {
sendCommand(GETBIT, key, toByteArray(offset)); sendCommand(GETBIT, key, toByteArray(offset));
} }
public void bitpos(final byte[] key, final boolean value, final BitPosParams params) { public void bitpos(final byte[] key, final boolean value,
final BitPosParams params) {
final List<byte[]> args = new ArrayList<byte[]>(); final List<byte[]> args = new ArrayList<byte[]>();
args.add(key); args.add(key);
args.add(toByteArray(value)); args.add(toByteArray(value));
args.addAll(params.getParams()); args.addAll(params.getParams());
sendCommand(BITPOS, args.toArray(new byte[args.size()][])); sendCommand(BITPOS, args.toArray(new byte[args.size()][]));
} }
public void setrange(byte[] key, long offset, byte[] value) { public void setrange(byte[] key, long offset, byte[] value) {
sendCommand(SETRANGE, key, toByteArray(offset), value); sendCommand(SETRANGE, key, toByteArray(offset), value);
} }
@@ -1200,7 +1203,8 @@ public class BinaryClient extends Connection {
sendCommand(SCAN, args.toArray(new byte[args.size()][])); sendCommand(SCAN, args.toArray(new byte[args.size()][]));
} }
public void hscan(final byte[] key, final byte[] cursor, final ScanParams params) { public void hscan(final byte[] key, final byte[] cursor,
final ScanParams params) {
final List<byte[]> args = new ArrayList<byte[]>(); final List<byte[]> args = new ArrayList<byte[]>();
args.add(key); args.add(key);
args.add(cursor); args.add(cursor);
@@ -1208,7 +1212,8 @@ public class BinaryClient extends Connection {
sendCommand(HSCAN, args.toArray(new byte[args.size()][])); sendCommand(HSCAN, args.toArray(new byte[args.size()][]));
} }
public void sscan(final byte[] key, final byte[] cursor, final ScanParams params) { public void sscan(final byte[] key, final byte[] cursor,
final ScanParams params) {
final List<byte[]> args = new ArrayList<byte[]>(); final List<byte[]> args = new ArrayList<byte[]>();
args.add(key); args.add(key);
args.add(cursor); args.add(cursor);
@@ -1216,7 +1221,8 @@ public class BinaryClient extends Connection {
sendCommand(SSCAN, args.toArray(new byte[args.size()][])); sendCommand(SSCAN, args.toArray(new byte[args.size()][]));
} }
public void zscan(final byte[] key, final byte[] cursor, final ScanParams params) { public void zscan(final byte[] key, final byte[] cursor,
final ScanParams params) {
final List<byte[]> args = new ArrayList<byte[]>(); final List<byte[]> args = new ArrayList<byte[]>();
args.add(key); args.add(key);
args.add(cursor); args.add(cursor);
@@ -1235,20 +1241,20 @@ public class BinaryClient extends Connection {
public void asking() { public void asking() {
sendCommand(Command.ASKING); sendCommand(Command.ASKING);
} }
public void pfadd(final byte[] key, final byte[]... elements) { public void pfadd(final byte[] key, final byte[]... elements) {
sendCommand(PFADD, joinParameters(key, elements)); sendCommand(PFADD, joinParameters(key, elements));
}
public void pfcount(final byte[] key) {
sendCommand(PFCOUNT, key);
} }
public void pfcount(final byte[]...keys) { public void pfcount(final byte[] key) {
sendCommand(PFCOUNT, keys); sendCommand(PFCOUNT, key);
}
public void pfcount(final byte[]... keys) {
sendCommand(PFCOUNT, keys);
} }
public void pfmerge(final byte[] destkey, final byte[]... sourcekeys) { public void pfmerge(final byte[] destkey, final byte[]... sourcekeys) {
sendCommand(PFMERGE, joinParameters(destkey, sourcekeys)); sendCommand(PFMERGE, joinParameters(destkey, sourcekeys));
} }
} }

View File

@@ -26,11 +26,11 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands,
protected Client client = null; protected Client client = null;
protected Transaction transaction = null; protected Transaction transaction = null;
protected Pipeline pipeline = null; protected Pipeline pipeline = null;
public BinaryJedis() { public BinaryJedis() {
client = new Client(); client = new Client();
} }
public BinaryJedis(final String host) { public BinaryJedis(final String host) {
URI uri = URI.create(host); URI uri = URI.create(host);
if (uri.getScheme() != null && uri.getScheme().equals("redis")) { if (uri.getScheme() != null && uri.getScheme().equals("redis")) {
@@ -1773,7 +1773,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands,
public Transaction multi() { public Transaction multi() {
client.multi(); client.multi();
client.getOne(); // expected OK client.getOne(); // expected OK
transaction = new Transaction(client); transaction = new Transaction(client);
return transaction; return transaction;
} }
@@ -1789,7 +1789,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands,
List<Object> results = null; List<Object> results = null;
jedisTransaction.setClient(client); jedisTransaction.setClient(client);
client.multi(); client.multi();
client.getOne(); // expected OK client.getOne(); // expected OK
jedisTransaction.execute(); jedisTransaction.execute();
results = jedisTransaction.exec(); results = jedisTransaction.exec();
return results; return results;
@@ -2838,20 +2838,21 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands,
} }
@Override @Override
public Set<byte[]> zrangeByLex(final byte[] key, final byte[] min, final byte[] max) { public Set<byte[]> zrangeByLex(final byte[] key, final byte[] min,
final byte[] max) {
checkIsInMulti(); checkIsInMulti();
client.zrangeByLex(key, min, max); client.zrangeByLex(key, min, max);
return new LinkedHashSet<byte[]>(client.getBinaryMultiBulkReply()); return new LinkedHashSet<byte[]>(client.getBinaryMultiBulkReply());
} }
@Override @Override
public Set<byte[]> zrangeByLex(final byte[] key, final byte[] min, final byte[] max, public Set<byte[]> zrangeByLex(final byte[] key, final byte[] min,
final int offset, final int count) { final byte[] max, final int offset, final int count) {
checkIsInMulti(); checkIsInMulti();
client.zrangeByLex(key, min, max, offset, count); client.zrangeByLex(key, min, max, offset, count);
return new LinkedHashSet<byte[]>(client.getBinaryMultiBulkReply()); return new LinkedHashSet<byte[]>(client.getBinaryMultiBulkReply());
} }
@Override @Override
public Set<byte[]> zrevrangeByLex(byte[] key, byte[] max, byte[] min) { public Set<byte[]> zrevrangeByLex(byte[] key, byte[] max, byte[] min) {
checkIsInMulti(); checkIsInMulti();
@@ -2868,7 +2869,8 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands,
} }
@Override @Override
public Long zremrangeByLex(final byte[] key, final byte[] min, final byte[] max) { public Long zremrangeByLex(final byte[] key, final byte[] min,
final byte[] max) {
checkIsInMulti(); checkIsInMulti();
client.zremrangeByLex(key, min, max); client.zremrangeByLex(key, min, max);
return client.getIntegerReply(); return client.getIntegerReply();

View File

@@ -196,19 +196,20 @@ public interface BinaryJedisCommands {
Long zremrangeByScore(byte[] key, double start, double end); Long zremrangeByScore(byte[] key, double start, double end);
Long zremrangeByScore(byte[] key, byte[] start, byte[] end); Long zremrangeByScore(byte[] key, byte[] start, byte[] end);
Long zlexcount(final byte[] key, final byte[] min, final byte[] max); Long zlexcount(final byte[] key, final byte[] min, final byte[] max);
Set<byte[]> zrangeByLex(final byte[] key, final byte[] min, final byte[] max); Set<byte[]> zrangeByLex(final byte[] key, final byte[] min, final byte[] max);
Set<byte[]> zrangeByLex(final byte[] key, final byte[] min, final byte[] max, Set<byte[]> zrangeByLex(final byte[] key, final byte[] min,
int offset, int count); final byte[] max, int offset, int count);
Set<byte[]> zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min); Set<byte[]> zrevrangeByLex(final byte[] key, final byte[] max,
final byte[] min);
Set<byte[]> zrevrangeByLex(final byte[] key, final byte[] max,
final byte[] min, int offset, int count);
Set<byte[]> zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min,
int offset, int count);
Long zremrangeByLex(final byte[] key, final byte[] min, final byte[] max); Long zremrangeByLex(final byte[] key, final byte[] min, final byte[] max);
Long linsert(byte[] key, Client.LIST_POSITION where, byte[] pivot, Long linsert(byte[] key, Client.LIST_POSITION where, byte[] pivot,
@@ -231,8 +232,8 @@ public interface BinaryJedisCommands {
Long bitcount(final byte[] key); Long bitcount(final byte[] key);
Long bitcount(final byte[] key, long start, long end); Long bitcount(final byte[] key, long start, long end);
Long pfadd(final byte[] key, final byte[]... elements); Long pfadd(final byte[] key, final byte[]... elements);
long pfcount(final byte[] key); long pfcount(final byte[] key);
} }

View File

@@ -206,26 +206,30 @@ public interface BinaryRedisPipeline {
Response<Long> zrevrank(byte[] key, byte[] member); Response<Long> zrevrank(byte[] key, byte[] member);
Response<Double> zscore(byte[] key, byte[] member); Response<Double> zscore(byte[] key, byte[] member);
Response<Long> zlexcount(final byte[] key, final byte[] min, final byte[] max);
Response<Set<byte[]>> zrangeByLex(final byte[] key, final byte[] min, final byte[] max);
Response<Set<byte[]>> zrangeByLex(final byte[] key, final byte[] min, final byte[] max, Response<Long> zlexcount(final byte[] key, final byte[] min,
int offset, int count); final byte[] max);
Response<Set<byte[]>> zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min); Response<Set<byte[]>> zrangeByLex(final byte[] key, final byte[] min,
final byte[] max);
Response<Set<byte[]>> zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min,
int offset, int count); Response<Set<byte[]>> zrangeByLex(final byte[] key, final byte[] min,
final byte[] max, int offset, int count);
Response<Long> zremrangeByLex(final byte[] key, final byte[] min, final byte[] max);
Response<Set<byte[]>> zrevrangeByLex(final byte[] key, final byte[] max,
final byte[] min);
Response<Set<byte[]>> zrevrangeByLex(final byte[] key, final byte[] max,
final byte[] min, int offset, int count);
Response<Long> zremrangeByLex(final byte[] key, final byte[] min,
final byte[] max);
Response<Long> bitcount(byte[] key); Response<Long> bitcount(byte[] key);
Response<Long> bitcount(byte[] key, long start, long end); Response<Long> bitcount(byte[] key, long start, long end);
Response<Long> pfadd(final byte[] key, final byte[]... elements); Response<Long> pfadd(final byte[] key, final byte[]... elements);
Response<Long> pfcount(final byte[] key); Response<Long> pfcount(final byte[] key);
} }

View File

@@ -111,8 +111,8 @@ public class BinaryShardedJedis extends Sharded<Jedis, JedisShardInfo>
} }
public Double incrByFloat(byte[] key, double integer) { public Double incrByFloat(byte[] key, double integer) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.incrByFloat(key, integer); return j.incrByFloat(key, integer);
} }
public Long incr(byte[] key) { public Long incr(byte[] key) {
@@ -161,8 +161,8 @@ public class BinaryShardedJedis extends Sharded<Jedis, JedisShardInfo>
} }
public Double hincrByFloat(byte[] key, byte[] field, double value) { public Double hincrByFloat(byte[] key, byte[] field, double value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hincrByFloat(key, field, value); return j.hincrByFloat(key, field, value);
} }
public Boolean hexists(byte[] key, byte[] field) { public Boolean hexists(byte[] key, byte[] field) {
@@ -302,8 +302,8 @@ public class BinaryShardedJedis extends Sharded<Jedis, JedisShardInfo>
@Override @Override
public List srandmember(byte[] key, int count) { public List srandmember(byte[] key, int count) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.srandmember(key, count); return j.srandmember(key, count);
} }
public Long zadd(byte[] key, double score, byte[] member) { public Long zadd(byte[] key, double score, byte[] member) {
@@ -490,7 +490,7 @@ public class BinaryShardedJedis extends Sharded<Jedis, JedisShardInfo>
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zremrangeByScore(key, start, end); return j.zremrangeByScore(key, start, end);
} }
@Override @Override
public Long zlexcount(final byte[] key, final byte[] min, final byte[] max) { public Long zlexcount(final byte[] key, final byte[] min, final byte[] max) {
Jedis j = getShard(key); Jedis j = getShard(key);
@@ -498,18 +498,19 @@ public class BinaryShardedJedis extends Sharded<Jedis, JedisShardInfo>
} }
@Override @Override
public Set<byte[]> zrangeByLex(final byte[] key, final byte[] min, final byte[] max) { public Set<byte[]> zrangeByLex(final byte[] key, final byte[] min,
final byte[] max) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrangeByLex(key, min, max); return j.zrangeByLex(key, min, max);
} }
@Override @Override
public Set<byte[]> zrangeByLex(final byte[] key, final byte[] min, final byte[] max, public Set<byte[]> zrangeByLex(final byte[] key, final byte[] min,
final int offset, final int count) { final byte[] max, final int offset, final int count) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrangeByLex(key, min, max, offset, count); return j.zrangeByLex(key, min, max, offset, count);
} }
@Override @Override
public Set<byte[]> zrevrangeByLex(byte[] key, byte[] max, byte[] min) { public Set<byte[]> zrevrangeByLex(byte[] key, byte[] max, byte[] min) {
Jedis j = getShard(key); Jedis j = getShard(key);
@@ -524,7 +525,8 @@ public class BinaryShardedJedis extends Sharded<Jedis, JedisShardInfo>
} }
@Override @Override
public Long zremrangeByLex(final byte[] key, final byte[] min, final byte[] max) { public Long zremrangeByLex(final byte[] key, final byte[] min,
final byte[] max) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zremrangeByLex(key, min, max); return j.zremrangeByLex(key, min, max);
} }
@@ -623,7 +625,7 @@ public class BinaryShardedJedis extends Sharded<Jedis, JedisShardInfo>
Jedis j = getShard(key); Jedis j = getShard(key);
return j.bitcount(key, start, end); return j.bitcount(key, start, end);
} }
@Override @Override
public Long pfadd(final byte[] key, final byte[]... elements) { public Long pfadd(final byte[] key, final byte[]... elements) {
Jedis j = getShard(key); Jedis j = getShard(key);

View File

@@ -17,7 +17,7 @@ public class BitPosParams {
public BitPosParams(long start, long end) { public BitPosParams(long start, long end) {
this(start); this(start);
params.add(Protocol.toByteArray(end)); params.add(Protocol.toByteArray(end));
} }

View File

@@ -104,7 +104,7 @@ public class BuilderFactory {
} }
}; };
public static final Builder<Map<String, String>> PUBSUB_NUMSUB_MAP = new Builder<Map<String, String>>() { public static final Builder<Map<String, String>> PUBSUB_NUMSUB_MAP = new Builder<Map<String, String>>() {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public Map<String, String> build(Object data) { public Map<String, String> build(Object data) {
@@ -124,7 +124,7 @@ public class BuilderFactory {
} }
}; };
public static final Builder<Set<String>> STRING_SET = new Builder<Set<String>>() { public static final Builder<Set<String>> STRING_SET = new Builder<Set<String>>() {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public Set<String> build(Object data) { public Set<String> build(Object data) {

View File

@@ -12,11 +12,11 @@ import redis.clients.jedis.JedisCluster.Reset;
import redis.clients.util.SafeEncoder; import redis.clients.util.SafeEncoder;
public class Client extends BinaryClient implements Commands { public class Client extends BinaryClient implements Commands {
public Client() { public Client() {
super(); super();
} }
public Client(final String host) { public Client(final String host) {
super(host); super(host);
} }
@@ -591,33 +591,38 @@ public class Client extends BinaryClient implements Commands {
} }
zinterstore(SafeEncoder.encode(dstkey), params, bsets); zinterstore(SafeEncoder.encode(dstkey), params, bsets);
} }
public void zlexcount(final String key, final String min, final String max) { public void zlexcount(final String key, final String min, final String max) {
zlexcount(SafeEncoder.encode(key), SafeEncoder.encode(min), SafeEncoder.encode(max)); zlexcount(SafeEncoder.encode(key), SafeEncoder.encode(min),
SafeEncoder.encode(max));
} }
public void zrangeByLex(final String key, final String min, final String max) { public void zrangeByLex(final String key, final String min, final String max) {
zrangeByLex(SafeEncoder.encode(key), SafeEncoder.encode(min), SafeEncoder.encode(max)); zrangeByLex(SafeEncoder.encode(key), SafeEncoder.encode(min),
SafeEncoder.encode(max));
} }
public void zrangeByLex(final String key, final String min, final String max, public void zrangeByLex(final String key, final String min,
final int offset, final int count) { final String max, final int offset, final int count) {
zrangeByLex(SafeEncoder.encode(key), SafeEncoder.encode(min), SafeEncoder.encode(max), zrangeByLex(SafeEncoder.encode(key), SafeEncoder.encode(min),
offset, count); SafeEncoder.encode(max), offset, count);
} }
public void zrevrangeByLex(String key, String max, String min) { public void zrevrangeByLex(String key, String max, String min) {
zrevrangeByLex(SafeEncoder.encode(key), SafeEncoder.encode(max), SafeEncoder.encode(min)); zrevrangeByLex(SafeEncoder.encode(key), SafeEncoder.encode(max),
SafeEncoder.encode(min));
} }
public void zrevrangeByLex(String key, String max, String min, int offset, public void zrevrangeByLex(String key, String max, String min, int offset,
int count) { int count) {
zrevrangeByLex(SafeEncoder.encode(key), SafeEncoder.encode(max), SafeEncoder.encode(min), zrevrangeByLex(SafeEncoder.encode(key), SafeEncoder.encode(max),
offset, count); SafeEncoder.encode(min), offset, count);
} }
public void zremrangeByLex(final String key, final String min, final String max) { public void zremrangeByLex(final String key, final String min,
zremrangeByLex(SafeEncoder.encode(key), SafeEncoder.encode(min), SafeEncoder.encode(max)); final String max) {
zremrangeByLex(SafeEncoder.encode(key), SafeEncoder.encode(min),
SafeEncoder.encode(max));
} }
public void strlen(final String key) { public void strlen(final String key) {
@@ -663,9 +668,11 @@ public class Client extends BinaryClient implements Commands {
getbit(SafeEncoder.encode(key), offset); getbit(SafeEncoder.encode(key), offset);
} }
public void bitpos(final String key, final boolean value, final BitPosParams params) { public void bitpos(final String key, final boolean value,
final BitPosParams params) {
bitpos(SafeEncoder.encode(key), value, params); bitpos(SafeEncoder.encode(key), value, params);
} }
public void setrange(String key, long offset, String value) { public void setrange(String key, long offset, String value) {
setrange(SafeEncoder.encode(key), offset, SafeEncoder.encode(value)); setrange(SafeEncoder.encode(key), offset, SafeEncoder.encode(value));
} }
@@ -709,11 +716,11 @@ public class Client extends BinaryClient implements Commands {
} }
subscribe(cs); subscribe(cs);
} }
public void pubsubChannels(String pattern) { public void pubsubChannels(String pattern) {
pubsub(Protocol.PUBSUB_CHANNELS, pattern); pubsub(Protocol.PUBSUB_CHANNELS, pattern);
} }
public void pubsubNumPat() { public void pubsubNumPat() {
pubsub(Protocol.PUBSUB_NUM_PAT); pubsub(Protocol.PUBSUB_NUM_PAT);
} }
@@ -873,16 +880,19 @@ public class Client extends BinaryClient implements Commands {
public void scan(final String cursor, final ScanParams params) { public void scan(final String cursor, final ScanParams params) {
scan(SafeEncoder.encode(cursor), params); scan(SafeEncoder.encode(cursor), params);
} }
public void hscan(final String key, final String cursor, final ScanParams params) { public void hscan(final String key, final String cursor,
final ScanParams params) {
hscan(SafeEncoder.encode(key), SafeEncoder.encode(cursor), params); hscan(SafeEncoder.encode(key), SafeEncoder.encode(cursor), params);
} }
public void sscan(final String key, final String cursor, final ScanParams params) { public void sscan(final String key, final String cursor,
final ScanParams params) {
sscan(SafeEncoder.encode(key), SafeEncoder.encode(cursor), params); sscan(SafeEncoder.encode(key), SafeEncoder.encode(cursor), params);
} }
public void zscan(final String key, final String cursor, final ScanParams params) { public void zscan(final String key, final String cursor,
final ScanParams params) {
zscan(SafeEncoder.encode(key), SafeEncoder.encode(cursor), params); zscan(SafeEncoder.encode(key), SafeEncoder.encode(cursor), params);
} }
@@ -894,14 +904,14 @@ public class Client extends BinaryClient implements Commands {
arg[0] = SafeEncoder.encode(subcommand); arg[0] = SafeEncoder.encode(subcommand);
cluster(arg); cluster(arg);
} }
public void pubsub(final String subcommand, final String... args) { public void pubsub(final String subcommand, final String... args) {
final byte[][] arg = new byte[args.length+1][]; final byte[][] arg = new byte[args.length + 1][];
for (int i = 1; i < arg.length; i++) { for (int i = 1; i < arg.length; i++) {
arg[i] = SafeEncoder.encode(args[i-1]); arg[i] = SafeEncoder.encode(args[i - 1]);
} }
arg[0] = SafeEncoder.encode(subcommand); arg[0] = SafeEncoder.encode(subcommand);
pubsub(arg); pubsub(arg);
} }
public void cluster(final String subcommand, final String... args) { public void cluster(final String subcommand, final String... args) {
@@ -971,18 +981,19 @@ public class Client extends BinaryClient implements Commands {
pfcount(SafeEncoder.encode(key)); pfcount(SafeEncoder.encode(key));
} }
public void pfcount(final String...keys) { public void pfcount(final String... keys) {
pfcount(SafeEncoder.encodeMany(keys)); pfcount(SafeEncoder.encodeMany(keys));
} }
public void pfmerge(final String destkey, final String... sourcekeys) { public void pfmerge(final String destkey, final String... sourcekeys) {
pfmerge(SafeEncoder.encode(destkey), SafeEncoder.encodeMany(sourcekeys)); pfmerge(SafeEncoder.encode(destkey), SafeEncoder.encodeMany(sourcekeys));
} }
public void clusterSetSlotStable(final int slot) {
public void clusterSetSlotStable(final int slot) {
cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot), cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot),
Protocol.CLUSTER_SETSLOT_STABLE); Protocol.CLUSTER_SETSLOT_STABLE);
} }
public void clusterForget(final String nodeId) { public void clusterForget(final String nodeId) {
cluster(Protocol.CLUSTER_FORGET, nodeId); cluster(Protocol.CLUSTER_FORGET, nodeId);
} }
@@ -1014,7 +1025,7 @@ public void clusterSetSlotStable(final int slot) {
public void clusterFailover() { public void clusterFailover() {
cluster(Protocol.CLUSTER_FAILOVER); cluster(Protocol.CLUSTER_FAILOVER);
} }
public void clusterSlots() { public void clusterSlots() {
cluster(Protocol.CLUSTER_SLOTS); cluster(Protocol.CLUSTER_SLOTS);
} }

View File

@@ -22,26 +22,26 @@ public interface ClusterCommands {
String clusterSetSlotMigrating(final int slot, final String nodeId); String clusterSetSlotMigrating(final int slot, final String nodeId);
String clusterSetSlotImporting(final int slot, final String nodeId); String clusterSetSlotImporting(final int slot, final String nodeId);
String clusterSetSlotStable(final int slot); String clusterSetSlotStable(final int slot);
String clusterForget(final String nodeId); String clusterForget(final String nodeId);
String clusterFlushSlots(); String clusterFlushSlots();
Long clusterKeySlot(final String key); Long clusterKeySlot(final String key);
Long clusterCountKeysInSlot(final int slot); Long clusterCountKeysInSlot(final int slot);
String clusterSaveConfig(); String clusterSaveConfig();
String clusterReplicate(final String nodeId); String clusterReplicate(final String nodeId);
List<String> clusterSlaves(final String nodeId); List<String> clusterSlaves(final String nodeId);
String clusterFailover(); String clusterFailover();
List<Object> clusterSlots(); List<Object> clusterSlots();
String clusterReset(Reset resetType); String clusterReset(Reset resetType);
} }

View File

@@ -81,7 +81,8 @@ public interface Commands {
public void hincrBy(final String key, final String field, final long value); public void hincrBy(final String key, final String field, final long value);
public void hincrByFloat(final String key, final String field, final double value); public void hincrByFloat(final String key, final String field,
final double value);
public void hexists(final String key, final String field); public void hexists(final String key, final String field);
@@ -303,11 +304,14 @@ public interface Commands {
public void scan(final String cursor, final ScanParams params); public void scan(final String cursor, final ScanParams params);
public void hscan(final String key, final String cursor, final ScanParams params); public void hscan(final String key, final String cursor,
final ScanParams params);
public void sscan(final String key, final String cursor, final ScanParams params); public void sscan(final String key, final String cursor,
final ScanParams params);
public void zscan(final String key, final String cursor,
final ScanParams params);
public void zscan(final String key, final String cursor, final ScanParams params);
public void waitReplicas(int replicas, long timeout); public void waitReplicas(int replicas, long timeout);
} }

View File

@@ -16,7 +16,7 @@ import redis.clients.util.RedisOutputStream;
import redis.clients.util.SafeEncoder; import redis.clients.util.SafeEncoder;
public class Connection implements Closeable { public class Connection implements Closeable {
private String host = Protocol.DEFAULT_HOST; private String host = Protocol.DEFAULT_HOST;
private int port = Protocol.DEFAULT_PORT; private int port = Protocol.DEFAULT_PORT;
private Socket socket; private Socket socket;
@@ -24,14 +24,14 @@ public class Connection implements Closeable {
private RedisInputStream inputStream; private RedisInputStream inputStream;
private int timeout = Protocol.DEFAULT_TIMEOUT; private int timeout = Protocol.DEFAULT_TIMEOUT;
private boolean broken = false; private boolean broken = false;
public Connection() { public Connection() {
} }
public Connection(final String host) { public Connection(final String host) {
this.host = host; this.host = host;
} }
public Connection(final String host, final int port) { public Connection(final String host, final int port) {
this.host = host; this.host = host;
this.port = port; this.port = port;
@@ -223,8 +223,8 @@ public class Connection implements Closeable {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public List<Long> getIntegerMultiBulkReply() { public List<Long> getIntegerMultiBulkReply() {
flush(); flush();
return (List<Long>) Protocol.read(inputStream); return (List<Long>) Protocol.read(inputStream);
} }
public Object getOne() { public Object getOne() {

View File

@@ -35,7 +35,7 @@ public class HostAndPort {
@Override @Override
public int hashCode() { public int hashCode() {
return 31 * convertHost(host).hashCode() + port; return 31 * convertHost(host).hashCode() + port;
} }
@Override @Override

View File

@@ -26,7 +26,7 @@ public class Jedis extends BinaryJedis implements JedisCommands,
public Jedis() { public Jedis() {
super(); super();
} }
public Jedis(final String host) { public Jedis(final String host) {
super(host); super(host);
} }
@@ -326,11 +326,11 @@ public class Jedis extends BinaryJedis implements JedisCommands,
* *
* @param key * @param key
* @return Integer reply, returns the remaining time to live in seconds of a * @return Integer reply, returns the remaining time to live in seconds of a
* key that has an EXPIRE. * key that has an EXPIRE. In Redis 2.6 or older, if the Key does
* In Redis 2.6 or older, if the Key does not exists or does not * not exists or does not have an associated expire, -1 is returned.
* have an associated expire, -1 is returned. * In Redis 2.8 or newer, if the Key does not have an associated
* In Redis 2.8 or newer, if the Key does not have an associated expire, -1 is returned * expire, -1 is returned or if the Key does not exists, -2 is
* or if the Key does not exists, -2 is returned. * returned.
*/ */
public Long ttl(final String key) { public Long ttl(final String key) {
checkIsInMulti(); checkIsInMulti();
@@ -2630,7 +2630,7 @@ public class Jedis extends BinaryJedis implements JedisCommands,
client.zinterstore(dstkey, params, sets); client.zinterstore(dstkey, params, sets);
return client.getIntegerReply(); return client.getIntegerReply();
} }
@Override @Override
public Long zlexcount(final String key, final String min, final String max) { public Long zlexcount(final String key, final String min, final String max) {
checkIsInMulti(); checkIsInMulti();
@@ -2639,15 +2639,16 @@ public class Jedis extends BinaryJedis implements JedisCommands,
} }
@Override @Override
public Set<String> zrangeByLex(final String key, final String min, final String max) { public Set<String> zrangeByLex(final String key, final String min,
final String max) {
checkIsInMulti(); checkIsInMulti();
client.zrangeByLex(key, min, max); client.zrangeByLex(key, min, max);
return new LinkedHashSet<String>(client.getMultiBulkReply()); return new LinkedHashSet<String>(client.getMultiBulkReply());
} }
@Override @Override
public Set<String> zrangeByLex(final String key, final String min, final String max, public Set<String> zrangeByLex(final String key, final String min,
final int offset, final int count) { final String max, final int offset, final int count) {
checkIsInMulti(); checkIsInMulti();
client.zrangeByLex(key, min, max, offset, count); client.zrangeByLex(key, min, max, offset, count);
return new LinkedHashSet<String>(client.getMultiBulkReply()); return new LinkedHashSet<String>(client.getMultiBulkReply());
@@ -2666,10 +2667,11 @@ public class Jedis extends BinaryJedis implements JedisCommands,
checkIsInMulti(); checkIsInMulti();
client.zrevrangeByLex(key, max, min, offset, count); client.zrevrangeByLex(key, max, min, offset, count);
return new LinkedHashSet<String>(client.getMultiBulkReply()); return new LinkedHashSet<String>(client.getMultiBulkReply());
} }
@Override @Override
public Long zremrangeByLex(final String key, final String min, final String max) { public Long zremrangeByLex(final String key, final String min,
final String max) {
checkIsInMulti(); checkIsInMulti();
client.zremrangeByLex(key, min, max); client.zremrangeByLex(key, min, max);
return client.getIntegerReply(); return client.getIntegerReply();
@@ -3328,7 +3330,7 @@ public class Jedis extends BinaryJedis implements JedisCommands,
client.clusterMeet(ip, port); client.clusterMeet(ip, port);
return client.getStatusCodeReply(); return client.getStatusCodeReply();
} }
public String clusterReset(final Reset resetType) { public String clusterReset(final Reset resetType) {
checkIsInMulti(); checkIsInMulti();
client.clusterReset(resetType); client.clusterReset(resetType);
@@ -3430,7 +3432,7 @@ public class Jedis extends BinaryJedis implements JedisCommands,
client.clusterFailover(); client.clusterFailover();
return client.getStatusCodeReply(); return client.getStatusCodeReply();
} }
@Override @Override
public List<Object> clusterSlots() { public List<Object> clusterSlots() {
checkIsInMulti(); checkIsInMulti();
@@ -3459,8 +3461,8 @@ public class Jedis extends BinaryJedis implements JedisCommands,
public Map<String, String> pubsubNumSub(String... channels) { public Map<String, String> pubsubNumSub(String... channels) {
checkIsInMulti(); checkIsInMulti();
client.pubsubNumSub(channels); client.pubsubNumSub(channels);
return BuilderFactory.PUBSUB_NUMSUB_MAP return BuilderFactory.PUBSUB_NUMSUB_MAP.build(client
.build(client.getBinaryMultiBulkReply()); .getBinaryMultiBulkReply());
} }
@Override @Override

View File

@@ -1,7 +1,5 @@
package redis.clients.jedis; package redis.clients.jedis;
import redis.clients.jedis.BinaryClient.LIST_POSITION;
import java.io.Closeable; import java.io.Closeable;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -10,12 +8,16 @@ import java.util.Set;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.BinaryClient.LIST_POSITION;
public class JedisCluster implements JedisCommands, BasicCommands, Closeable { public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
public static final short HASHSLOTS = 16384; public static final short HASHSLOTS = 16384;
private static final int DEFAULT_TIMEOUT = 1; private static final int DEFAULT_TIMEOUT = 1;
private static final int DEFAULT_MAX_REDIRECTIONS = 5; private static final int DEFAULT_MAX_REDIRECTIONS = 5;
public static enum Reset {SOFT, HARD} public static enum Reset {
SOFT, HARD
}
private int timeout; private int timeout;
private int maxRedirections; private int maxRedirections;
@@ -30,30 +32,28 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
this(nodes, DEFAULT_TIMEOUT); this(nodes, DEFAULT_TIMEOUT);
} }
public JedisCluster(Set<HostAndPort> nodes, int timeout, public JedisCluster(Set<HostAndPort> nodes, int timeout, int maxRedirections) {
int maxRedirections) { this(nodes, timeout, maxRedirections, new GenericObjectPoolConfig());
this(nodes, timeout, maxRedirections,
new GenericObjectPoolConfig());
} }
public JedisCluster(Set<HostAndPort> nodes, public JedisCluster(Set<HostAndPort> nodes,
final GenericObjectPoolConfig poolConfig) { final GenericObjectPoolConfig poolConfig) {
this(nodes, DEFAULT_TIMEOUT, DEFAULT_MAX_REDIRECTIONS, poolConfig); this(nodes, DEFAULT_TIMEOUT, DEFAULT_MAX_REDIRECTIONS, poolConfig);
} }
public JedisCluster(Set<HostAndPort> nodes, int timeout, public JedisCluster(Set<HostAndPort> nodes, int timeout,
final GenericObjectPoolConfig poolConfig) { final GenericObjectPoolConfig poolConfig) {
this(nodes, timeout, DEFAULT_MAX_REDIRECTIONS, poolConfig); this(nodes, timeout, DEFAULT_MAX_REDIRECTIONS, poolConfig);
} }
public JedisCluster(Set<HostAndPort> jedisClusterNode, int timeout, public JedisCluster(Set<HostAndPort> jedisClusterNode, int timeout,
int maxRedirections, final GenericObjectPoolConfig poolConfig) { int maxRedirections, final GenericObjectPoolConfig poolConfig) {
this.connectionHandler = new JedisSlotBasedConnectionHandler( this.connectionHandler = new JedisSlotBasedConnectionHandler(
jedisClusterNode, poolConfig); jedisClusterNode, poolConfig);
this.timeout = timeout; this.timeout = timeout;
this.maxRedirections = maxRedirections; this.maxRedirections = maxRedirections;
} }
@Override @Override
public void close() { public void close() {
if (connectionHandler != null) { if (connectionHandler != null) {
@@ -82,14 +82,14 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
@Override @Override
public String set(final String key, final String value, final String nxxx, public String set(final String key, final String value, final String nxxx,
final String expx, final long time) { final String expx, final long time) {
return new JedisClusterCommand<String>(connectionHandler, timeout, return new JedisClusterCommand<String>(connectionHandler, timeout,
maxRedirections) { maxRedirections) {
@Override @Override
public String execute(Jedis connection) { public String execute(Jedis connection) {
return connection.set(key, value, nxxx, expx, time); return connection.set(key, value, nxxx, expx, time);
} }
}.run(key); }.run(key);
} }
@Override @Override
@@ -153,8 +153,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Long execute(Jedis connection) { public Long execute(Jedis connection) {
return connection return connection.expireAt(key, unixTime);
.expireAt(key, unixTime);
} }
}.run(key); }.run(key);
} }
@@ -177,8 +176,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Boolean execute(Jedis connection) { public Boolean execute(Jedis connection) {
return connection.setbit(key, offset, return connection.setbit(key, offset, value);
value);
} }
}.run(key); }.run(key);
} }
@@ -190,8 +188,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Boolean execute(Jedis connection) { public Boolean execute(Jedis connection) {
return connection.setbit(key, offset, return connection.setbit(key, offset, value);
value);
} }
}.run(key); }.run(key);
} }
@@ -213,8 +210,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Long execute(Jedis connection) { public Long execute(Jedis connection) {
return connection.setrange(key, offset, return connection.setrange(key, offset, value);
value);
} }
}.run(key); }.run(key);
} }
@@ -226,8 +222,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public String execute(Jedis connection) { public String execute(Jedis connection) {
return connection.getrange(key, return connection.getrange(key, startOffset, endOffset);
startOffset, endOffset);
} }
}.run(key); }.run(key);
} }
@@ -260,8 +255,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public String execute(Jedis connection) { public String execute(Jedis connection) {
return connection.setex(key, seconds, return connection.setex(key, seconds, value);
value);
} }
}.run(key); }.run(key);
} }
@@ -327,8 +321,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public String execute(Jedis connection) { public String execute(Jedis connection) {
return connection return connection.substr(key, start, end);
.substr(key, start, end);
} }
}.run(key); }.run(key);
} }
@@ -339,8 +332,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Long execute(Jedis connection) { public Long execute(Jedis connection) {
return connection return connection.hset(key, field, value);
.hset(key, field, value);
} }
}.run(key); }.run(key);
} }
@@ -362,8 +354,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Long execute(Jedis connection) { public Long execute(Jedis connection) {
return connection.hsetnx(key, field, return connection.hsetnx(key, field, value);
value);
} }
}.run(key); }.run(key);
} }
@@ -396,8 +387,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Long execute(Jedis connection) { public Long execute(Jedis connection) {
return connection.hincrBy(key, field, return connection.hincrBy(key, field, value);
value);
} }
}.run(key); }.run(key);
} }
@@ -508,8 +498,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
timeout, maxRedirections) { timeout, maxRedirections) {
@Override @Override
public List<String> execute(Jedis connection) { public List<String> execute(Jedis connection) {
return connection return connection.lrange(key, start, end);
.lrange(key, start, end);
} }
}.run(key); }.run(key);
} }
@@ -542,8 +531,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public String execute(Jedis connection) { public String execute(Jedis connection) {
return connection return connection.lset(key, index, value);
.lset(key, index, value);
} }
}.run(key); }.run(key);
} }
@@ -554,8 +542,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Long execute(Jedis connection) { public Long execute(Jedis connection) {
return connection return connection.lrem(key, count, value);
.lrem(key, count, value);
} }
}.run(key); }.run(key);
} }
@@ -661,13 +648,13 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
@Override @Override
public List<String> srandmember(final String key, final int count) { public List<String> srandmember(final String key, final int count) {
return new JedisClusterCommand<List<String>>(connectionHandler, timeout, return new JedisClusterCommand<List<String>>(connectionHandler,
maxRedirections) { timeout, maxRedirections) {
@Override @Override
public List<String> execute(Jedis connection) { public List<String> execute(Jedis connection) {
return connection.srandmember(key, count); return connection.srandmember(key, count);
} }
}.run(key); }.run(key);
} }
@Override @Override
@@ -687,8 +674,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Long execute(Jedis connection) { public Long execute(Jedis connection) {
return connection.zadd(key, score, return connection.zadd(key, score, member);
member);
} }
}.run(key); }.run(key);
} }
@@ -699,8 +685,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Long execute(Jedis connection) { public Long execute(Jedis connection) {
return connection return connection.zadd(key, scoreMembers);
.zadd(key, scoreMembers);
} }
}.run(key); }.run(key);
} }
@@ -711,8 +696,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Set<String> execute(Jedis connection) { public Set<String> execute(Jedis connection) {
return connection return connection.zrange(key, start, end);
.zrange(key, start, end);
} }
}.run(key); }.run(key);
} }
@@ -735,8 +719,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Double execute(Jedis connection) { public Double execute(Jedis connection) {
return connection.zincrby(key, score, return connection.zincrby(key, score, member);
member);
} }
}.run(key); }.run(key);
} }
@@ -770,8 +753,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Set<String> execute(Jedis connection) { public Set<String> execute(Jedis connection) {
return connection.zrevrange(key, start, return connection.zrevrange(key, start, end);
end);
} }
}.run(key); }.run(key);
} }
@@ -783,8 +765,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Set<Tuple> execute(Jedis connection) { public Set<Tuple> execute(Jedis connection) {
return connection.zrangeWithScores(key, return connection.zrangeWithScores(key, start, end);
start, end);
} }
}.run(key); }.run(key);
} }
@@ -796,8 +777,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Set<Tuple> execute(Jedis connection) { public Set<Tuple> execute(Jedis connection) {
return connection.zrevrangeWithScores( return connection.zrevrangeWithScores(key, start, end);
key, start, end);
} }
}.run(key); }.run(key);
} }
@@ -842,8 +822,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
timeout, maxRedirections) { timeout, maxRedirections) {
@Override @Override
public List<String> execute(Jedis connection) { public List<String> execute(Jedis connection) {
return connection.sort(key, return connection.sort(key, sortingParameters);
sortingParameters);
} }
}.run(key); }.run(key);
} }
@@ -877,8 +856,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Set<String> execute(Jedis connection) { public Set<String> execute(Jedis connection) {
return connection.zrangeByScore(key, return connection.zrangeByScore(key, min, max);
min, max);
} }
}.run(key); }.run(key);
} }
@@ -890,8 +868,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Set<String> execute(Jedis connection) { public Set<String> execute(Jedis connection) {
return connection.zrangeByScore(key, return connection.zrangeByScore(key, min, max);
min, max);
} }
}.run(key); }.run(key);
} }
@@ -903,8 +880,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Set<String> execute(Jedis connection) { public Set<String> execute(Jedis connection) {
return connection.zrevrangeByScore(key, return connection.zrevrangeByScore(key, min, max);
min, max);
} }
}.run(key); }.run(key);
} }
@@ -916,8 +892,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Set<String> execute(Jedis connection) { public Set<String> execute(Jedis connection) {
return connection.zrangeByScore(key, return connection.zrangeByScore(key, min, max, offset, count);
min, max, offset, count);
} }
}.run(key); }.run(key);
} }
@@ -929,8 +904,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Set<String> execute(Jedis connection) { public Set<String> execute(Jedis connection) {
return connection.zrevrangeByScore(key, return connection.zrevrangeByScore(key, min, max);
min, max);
} }
}.run(key); }.run(key);
} }
@@ -942,8 +916,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Set<String> execute(Jedis connection) { public Set<String> execute(Jedis connection) {
return connection.zrangeByScore(key, return connection.zrangeByScore(key, min, max, offset, count);
min, max, offset, count);
} }
}.run(key); }.run(key);
} }
@@ -955,8 +928,8 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Set<String> execute(Jedis connection) { public Set<String> execute(Jedis connection) {
return connection.zrevrangeByScore(key, return connection
min, max, offset, count); .zrevrangeByScore(key, min, max, offset, count);
} }
}.run(key); }.run(key);
} }
@@ -968,8 +941,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Set<Tuple> execute(Jedis connection) { public Set<Tuple> execute(Jedis connection) {
return connection return connection.zrangeByScoreWithScores(key, min, max);
.zrangeByScoreWithScores(key, min, max);
} }
}.run(key); }.run(key);
} }
@@ -981,8 +953,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Set<Tuple> execute(Jedis connection) { public Set<Tuple> execute(Jedis connection) {
return connection return connection.zrevrangeByScoreWithScores(key, min, max);
.zrevrangeByScoreWithScores(key, min, max);
} }
}.run(key); }.run(key);
} }
@@ -995,8 +966,8 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Set<Tuple> execute(Jedis connection) { public Set<Tuple> execute(Jedis connection) {
return connection return connection.zrangeByScoreWithScores(key, min, max,
.zrangeByScoreWithScores(key, min, max, offset, count); offset, count);
} }
}.run(key); }.run(key);
} }
@@ -1008,8 +979,8 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Set<String> execute(Jedis connection) { public Set<String> execute(Jedis connection) {
return connection.zrevrangeByScore(key, return connection
min, max, offset, count); .zrevrangeByScore(key, min, max, offset, count);
} }
}.run(key); }.run(key);
} }
@@ -1021,8 +992,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Set<Tuple> execute(Jedis connection) { public Set<Tuple> execute(Jedis connection) {
return connection return connection.zrangeByScoreWithScores(key, min, max);
.zrangeByScoreWithScores(key, min, max);
} }
}.run(key); }.run(key);
} }
@@ -1034,8 +1004,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Set<Tuple> execute(Jedis connection) { public Set<Tuple> execute(Jedis connection) {
return connection return connection.zrevrangeByScoreWithScores(key, min, max);
.zrevrangeByScoreWithScores(key, min, max);
} }
}.run(key); }.run(key);
} }
@@ -1048,8 +1017,8 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Set<Tuple> execute(Jedis connection) { public Set<Tuple> execute(Jedis connection) {
return connection return connection.zrangeByScoreWithScores(key, min, max,
.zrangeByScoreWithScores(key, min, max, offset, count); offset, count);
} }
}.run(key); }.run(key);
} }
@@ -1062,9 +1031,8 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Set<Tuple> execute(Jedis connection) { public Set<Tuple> execute(Jedis connection) {
return connection return connection.zrevrangeByScoreWithScores(key, max, min,
.zrevrangeByScoreWithScores(key, max, min, offset, offset, count);
count);
} }
}.run(key); }.run(key);
} }
@@ -1077,9 +1045,8 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Set<Tuple> execute(Jedis connection) { public Set<Tuple> execute(Jedis connection) {
return connection return connection.zrevrangeByScoreWithScores(key, max, min,
.zrevrangeByScoreWithScores(key, max, min, offset, offset, count);
count);
} }
}.run(key); }.run(key);
} }
@@ -1091,8 +1058,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Long execute(Jedis connection) { public Long execute(Jedis connection) {
return connection.zremrangeByRank(key, return connection.zremrangeByRank(key, start, end);
start, end);
} }
}.run(key); }.run(key);
} }
@@ -1104,8 +1070,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Long execute(Jedis connection) { public Long execute(Jedis connection) {
return connection.zremrangeByScore(key, return connection.zremrangeByScore(key, start, end);
start, end);
} }
}.run(key); }.run(key);
} }
@@ -1117,15 +1082,14 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Long execute(Jedis connection) { public Long execute(Jedis connection) {
return connection.zremrangeByScore(key, return connection.zremrangeByScore(key, start, end);
start, end);
} }
}.run(key); }.run(key);
} }
@Override @Override
public Long zlexcount(final String key, final String min, final String max) { public Long zlexcount(final String key, final String min, final String max) {
return new JedisClusterCommand<Long>(connectionHandler, timeout, return new JedisClusterCommand<Long>(connectionHandler, timeout,
maxRedirections) { maxRedirections) {
@Override @Override
public Long execute(Jedis connection) { public Long execute(Jedis connection) {
@@ -1135,8 +1099,9 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
} }
@Override @Override
public Set<String> zrangeByLex(final String key, final String min, final String max) { public Set<String> zrangeByLex(final String key, final String min,
return new JedisClusterCommand<Set<String>>(connectionHandler, timeout, final String max) {
return new JedisClusterCommand<Set<String>>(connectionHandler, timeout,
maxRedirections) { maxRedirections) {
@Override @Override
public Set<String> execute(Jedis connection) { public Set<String> execute(Jedis connection) {
@@ -1146,9 +1111,9 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
} }
@Override @Override
public Set<String> zrangeByLex(final String key, final String min, final String max, public Set<String> zrangeByLex(final String key, final String min,
final int offset, final int count) { final String max, final int offset, final int count) {
return new JedisClusterCommand<Set<String>>(connectionHandler, timeout, return new JedisClusterCommand<Set<String>>(connectionHandler, timeout,
maxRedirections) { maxRedirections) {
@Override @Override
public Set<String> execute(Jedis connection) { public Set<String> execute(Jedis connection) {
@@ -1158,8 +1123,9 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
} }
@Override @Override
public Set<String> zrevrangeByLex(final String key, final String max, final String min) { public Set<String> zrevrangeByLex(final String key, final String max,
return new JedisClusterCommand<Set<String>>(connectionHandler, timeout, final String min) {
return new JedisClusterCommand<Set<String>>(connectionHandler, timeout,
maxRedirections) { maxRedirections) {
@Override @Override
public Set<String> execute(Jedis connection) { public Set<String> execute(Jedis connection) {
@@ -1169,9 +1135,9 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
} }
@Override @Override
public Set<String> zrevrangeByLex(final String key, final String max, final String min, public Set<String> zrevrangeByLex(final String key, final String max,
final int offset, final int count) { final String min, final int offset, final int count) {
return new JedisClusterCommand<Set<String>>(connectionHandler, timeout, return new JedisClusterCommand<Set<String>>(connectionHandler, timeout,
maxRedirections) { maxRedirections) {
@Override @Override
public Set<String> execute(Jedis connection) { public Set<String> execute(Jedis connection) {
@@ -1181,8 +1147,9 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
} }
@Override @Override
public Long zremrangeByLex(final String key, final String min, final String max) { public Long zremrangeByLex(final String key, final String min,
return new JedisClusterCommand<Long>(connectionHandler, timeout, final String max) {
return new JedisClusterCommand<Long>(connectionHandler, timeout,
maxRedirections) { maxRedirections) {
@Override @Override
public Long execute(Jedis connection) { public Long execute(Jedis connection) {
@@ -1198,8 +1165,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Long execute(Jedis connection) { public Long execute(Jedis connection) {
return connection.linsert(key, where, return connection.linsert(key, where, pivot, value);
pivot, value);
} }
}.run(key); }.run(key);
} }
@@ -1298,8 +1264,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
maxRedirections) { maxRedirections) {
@Override @Override
public Long execute(Jedis connection) { public Long execute(Jedis connection) {
return connection.bitcount(key, start, return connection.bitcount(key, start, end);
end);
} }
}.run(key); }.run(key);
} }
@@ -1534,7 +1499,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
} }
}.run(null); }.run(null);
} }
@Override @Override
public ScanResult<String> sscan(final String key, final String cursor) { public ScanResult<String> sscan(final String key, final String cursor) {
return new JedisClusterCommand<ScanResult<String>>(connectionHandler, return new JedisClusterCommand<ScanResult<String>>(connectionHandler,
@@ -1545,7 +1510,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
} }
}.run(null); }.run(null);
} }
@Override @Override
public ScanResult<Tuple> zscan(final String key, final String cursor) { public ScanResult<Tuple> zscan(final String key, final String cursor) {
return new JedisClusterCommand<ScanResult<Tuple>>(connectionHandler, return new JedisClusterCommand<ScanResult<Tuple>>(connectionHandler,
@@ -1559,8 +1524,8 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
@Override @Override
public Long pfadd(final String key, final String... elements) { public Long pfadd(final String key, final String... elements) {
return new JedisClusterCommand<Long>(connectionHandler, return new JedisClusterCommand<Long>(connectionHandler, timeout,
timeout, maxRedirections) { maxRedirections) {
@Override @Override
public Long execute(Jedis connection) { public Long execute(Jedis connection) {
return connection.pfadd(key, elements); return connection.pfadd(key, elements);
@@ -1570,8 +1535,8 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
@Override @Override
public long pfcount(final String key) { public long pfcount(final String key) {
return new JedisClusterCommand<Long>(connectionHandler, return new JedisClusterCommand<Long>(connectionHandler, timeout,
timeout, maxRedirections) { maxRedirections) {
@Override @Override
public Long execute(Jedis connection) { public Long execute(Jedis connection) {
return connection.pfcount(key); return connection.pfcount(key);
@@ -1585,7 +1550,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
timeout, maxRedirections) { timeout, maxRedirections) {
@Override @Override
public List<String> execute(Jedis connection) { public List<String> execute(Jedis connection) {
return connection.blpop(timeout,key); return connection.blpop(timeout, key);
} }
}.run(null); }.run(null);
} }
@@ -1596,7 +1561,7 @@ public class JedisCluster implements JedisCommands, BasicCommands, Closeable {
timeout, maxRedirections) { timeout, maxRedirections) {
@Override @Override
public List<String> execute(Jedis connection) { public List<String> execute(Jedis connection) {
return connection.brpop(timeout,key); return connection.brpop(timeout, key);
} }
}.run(null); }.run(null);
} }

View File

@@ -42,7 +42,6 @@ public abstract class JedisClusterCommand<T> {
Jedis connection = null; Jedis connection = null;
try { try {
if (asking) { if (asking) {
// TODO: Pipeline asking with the original command to make it // TODO: Pipeline asking with the original command to make it
@@ -52,13 +51,14 @@ public abstract class JedisClusterCommand<T> {
// if asking success, reset asking flag // if asking success, reset asking flag
asking = false; asking = false;
}else{ } else {
if (tryRandomNode) { if (tryRandomNode) {
connection = connectionHandler.getConnection(); connection = connectionHandler.getConnection();
} else { } else {
connection = connectionHandler connection = connectionHandler
.getConnectionFromSlot(JedisClusterCRC16.getSlot(key)); .getConnectionFromSlot(JedisClusterCRC16
} .getSlot(key));
}
} }
return execute(connection); return execute(connection);
@@ -76,7 +76,8 @@ public abstract class JedisClusterCommand<T> {
} catch (JedisRedirectionException jre) { } catch (JedisRedirectionException jre) {
if (jre instanceof JedisAskDataException) { if (jre instanceof JedisAskDataException) {
asking = true; asking = true;
askConnection.set(this.connectionHandler.getConnectionFromNode(jre.getTargetNode())); askConnection.set(this.connectionHandler
.getConnectionFromNode(jre.getTargetNode()));
} else if (jre instanceof JedisMovedDataException) { } else if (jre instanceof JedisMovedDataException) {
// it rebuilds cluster's slot cache // it rebuilds cluster's slot cache
// recommended by Redis cluster specification // recommended by Redis cluster specification

View File

@@ -32,7 +32,8 @@ public abstract class JedisClusterConnectionHandler {
.getResource(); .getResource();
} }
public JedisClusterConnectionHandler(Set<HostAndPort> nodes, final GenericObjectPoolConfig poolConfig) { public JedisClusterConnectionHandler(Set<HostAndPort> nodes,
final GenericObjectPoolConfig poolConfig) {
this.cache = new JedisClusterInfoCache(poolConfig); this.cache = new JedisClusterInfoCache(poolConfig);
initializeSlotsCache(nodes, poolConfig); initializeSlotsCache(nodes, poolConfig);
} }
@@ -45,7 +46,8 @@ public abstract class JedisClusterConnectionHandler {
cache.assignSlotToNode(slot, targetNode); cache.assignSlotToNode(slot, targetNode);
} }
private void initializeSlotsCache(Set<HostAndPort> startNodes, GenericObjectPoolConfig poolConfig) { private void initializeSlotsCache(Set<HostAndPort> startNodes,
GenericObjectPoolConfig poolConfig) {
for (HostAndPort hostAndPort : startNodes) { for (HostAndPort hostAndPort : startNodes) {
JedisPool jp = new JedisPool(poolConfig, hostAndPort.getHost(), JedisPool jp = new JedisPool(poolConfig, hostAndPort.getHost(),
hostAndPort.getPort()); hostAndPort.getPort());

View File

@@ -1,10 +1,5 @@
package redis.clients.jedis; package redis.clients.jedis;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.util.ClusterNodeInformation;
import redis.clients.util.ClusterNodeInformationParser;
import redis.clients.util.SafeEncoder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@@ -12,6 +7,12 @@ import java.util.Map;
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.util.ClusterNodeInformation;
import redis.clients.util.ClusterNodeInformationParser;
import redis.clients.util.SafeEncoder;
public class JedisClusterInfoCache { public class JedisClusterInfoCache {
public static final ClusterNodeInformationParser nodeInfoParser = new ClusterNodeInformationParser(); public static final ClusterNodeInformationParser nodeInfoParser = new ClusterNodeInformationParser();
@@ -24,7 +25,7 @@ public class JedisClusterInfoCache {
private final GenericObjectPoolConfig poolConfig; private final GenericObjectPoolConfig poolConfig;
public JedisClusterInfoCache(final GenericObjectPoolConfig poolConfig) { public JedisClusterInfoCache(final GenericObjectPoolConfig poolConfig) {
this.poolConfig = poolConfig; this.poolConfig = poolConfig;
} }
public void discoverClusterNodesAndSlots(Jedis jedis) { public void discoverClusterNodesAndSlots(Jedis jedis) {
@@ -96,7 +97,8 @@ public class JedisClusterInfoCache {
if (nodes.containsKey(nodeKey)) if (nodes.containsKey(nodeKey))
return; return;
JedisPool nodePool = new JedisPool(poolConfig, node.getHost(), node.getPort()); JedisPool nodePool = new JedisPool(poolConfig, node.getHost(),
node.getPort());
nodes.put(nodeKey, nodePool); nodes.put(nodeKey, nodePool);
} finally { } finally {
w.unlock(); w.unlock();

View File

@@ -10,8 +10,7 @@ import java.util.Set;
public interface JedisCommands { public interface JedisCommands {
String set(String key, String value); String set(String key, String value);
String set(String key, String value, String nxxx, String set(String key, String value, String nxxx, String expx, long time);
String expx, long time);
String get(String key); String get(String key);
@@ -194,19 +193,20 @@ public interface JedisCommands {
Long zremrangeByScore(String key, double start, double end); Long zremrangeByScore(String key, double start, double end);
Long zremrangeByScore(String key, String start, String end); Long zremrangeByScore(String key, String start, String end);
Long zlexcount(final String key, final String min, final String max); Long zlexcount(final String key, final String min, final String max);
Set<String> zrangeByLex(final String key, final String min, final String max); Set<String> zrangeByLex(final String key, final String min, final String max);
Set<String> zrangeByLex(final String key, final String min, final String max, Set<String> zrangeByLex(final String key, final String min,
final int offset, final int count); final String max, final int offset, final int count);
Set<String> zrevrangeByLex(final String key, final String max, final String min); Set<String> zrevrangeByLex(final String key, final String max,
final String min);
Set<String> zrevrangeByLex(final String key, final String max,
final String min, final int offset, final int count);
Set<String> zrevrangeByLex(final String key, final String max, final String min,
final int offset, final int count);
Long zremrangeByLex(final String key, final String min, final String max); Long zremrangeByLex(final String key, final String min, final String max);
Long linsert(String key, Client.LIST_POSITION where, String pivot, Long linsert(String key, Client.LIST_POSITION where, String pivot,
@@ -217,11 +217,11 @@ public interface JedisCommands {
Long rpushx(String key, String... string); Long rpushx(String key, String... string);
List<String> blpop(String arg); List<String> blpop(String arg);
List<String> blpop(int timeout, String key); List<String> blpop(int timeout, String key);
List<String> brpop(String arg); List<String> brpop(String arg);
List<String> brpop(int timeout, String key); List<String> brpop(int timeout, String key);
Long del(String key); Long del(String key);
@@ -234,14 +234,15 @@ public interface JedisCommands {
Long bitcount(final String key, long start, long end); Long bitcount(final String key, long start, long end);
ScanResult<Map.Entry<String, String>> hscan(final String key, final String cursor); ScanResult<Map.Entry<String, String>> hscan(final String key,
final String cursor);
ScanResult<String> sscan(final String key, final String cursor); ScanResult<String> sscan(final String key, final String cursor);
ScanResult<Tuple> zscan(final String key, final String cursor); ScanResult<Tuple> zscan(final String key, final String cursor);
Long pfadd(final String key, final String... elements); Long pfadd(final String key, final String... elements);
long pfcount(final String key); long pfcount(final String key);
} }

View File

@@ -32,7 +32,7 @@ class JedisFactory implements PooledObjectFactory<Jedis> {
} }
public void setHostAndPort(final HostAndPort hostAndPort) { public void setHostAndPort(final HostAndPort hostAndPort) {
this.hostAndPort.set(hostAndPort); this.hostAndPort.set(hostAndPort);
} }
@Override @Override
@@ -64,8 +64,9 @@ class JedisFactory implements PooledObjectFactory<Jedis> {
@Override @Override
public PooledObject<Jedis> makeObject() throws Exception { public PooledObject<Jedis> makeObject() throws Exception {
final HostAndPort hostAndPort = this.hostAndPort.get(); final HostAndPort hostAndPort = this.hostAndPort.get();
final Jedis jedis = new Jedis(hostAndPort.getHost(), hostAndPort.getPort(), this.timeout); final Jedis jedis = new Jedis(hostAndPort.getHost(),
hostAndPort.getPort(), this.timeout);
jedis.connect(); jedis.connect();
if (null != this.password) { if (null != this.password) {
@@ -96,8 +97,9 @@ class JedisFactory implements PooledObjectFactory<Jedis> {
String connectionHost = jedis.getClient().getHost(); String connectionHost = jedis.getClient().getHost();
int connectionPort = jedis.getClient().getPort(); int connectionPort = jedis.getClient().getPort();
return hostAndPort.getHost().equals(connectionHost) && hostAndPort.getPort() == connectionPort && return hostAndPort.getHost().equals(connectionHost)
jedis.isConnected() && jedis.ping().equals("PONG"); && hostAndPort.getPort() == connectionPort
&& jedis.isConnected() && jedis.ping().equals("PONG");
} catch (final Exception e) { } catch (final Exception e) {
return false; return false;
} }

View File

@@ -13,7 +13,7 @@ public class JedisPool extends Pool<Jedis> {
public JedisPool() { public JedisPool() {
this(Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT); this(Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT);
} }
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host) { public JedisPool(final GenericObjectPoolConfig poolConfig, final String host) {
this(poolConfig, host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT, this(poolConfig, host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT,
null, Protocol.DEFAULT_DATABASE, null); null, Protocol.DEFAULT_DATABASE, null);
@@ -119,10 +119,10 @@ public class JedisPool extends Pool<Jedis> {
} }
public int getNumActive() { public int getNumActive() {
if (this.internalPool == null || this.internalPool.isClosed()) { if (this.internalPool == null || this.internalPool.isClosed()) {
return -1; return -1;
} }
return this.internalPool.getNumActive(); return this.internalPool.getNumActive();
} }
} }

View File

@@ -95,14 +95,16 @@ public class JedisSentinelPool extends Pool<Jedis> {
if (!master.equals(currentHostMaster)) { if (!master.equals(currentHostMaster)) {
currentHostMaster = master; currentHostMaster = master;
if (factory == null) { if (factory == null) {
factory = new JedisFactory(master.getHost(), master.getPort(), factory = new JedisFactory(master.getHost(), master.getPort(),
timeout, password, database); timeout, password, database);
initPool(poolConfig, factory); initPool(poolConfig, factory);
} else { } else {
factory.setHostAndPort(currentHostMaster); factory.setHostAndPort(currentHostMaster);
// although we clear the pool, we still have to check the returned object // although we clear the pool, we still have to check the
// in getResource, this call only clears idle instances, not borrowed instances // returned object
internalPool.clear(); // in getResource, this call only clears idle instances, not
// borrowed instances
internalPool.clear();
} }
log.info("Created JedisPool to master at " + master); log.info("Created JedisPool to master at " + master);
@@ -154,12 +156,14 @@ public class JedisSentinelPool extends Pool<Jedis> {
if (master == null) { if (master == null) {
if (sentinelAvailable) { if (sentinelAvailable) {
// can connect to sentinel, but master name seems to not monitored // can connect to sentinel, but master name seems to not
throw new JedisException("Can connect to sentinel, but " + masterName // monitored
+ " seems to be not monitored..."); throw new JedisException("Can connect to sentinel, but "
+ masterName + " seems to be not monitored...");
} else { } else {
throw new JedisConnectionException("All sentinels down, cannot determine where is " throw new JedisConnectionException(
+ masterName + " master is running..."); "All sentinels down, cannot determine where is "
+ masterName + " master is running...");
} }
} }
@@ -193,14 +197,14 @@ public class JedisSentinelPool extends Pool<Jedis> {
// get a reference because it can change concurrently // get a reference because it can change concurrently
final HostAndPort master = currentHostMaster; final HostAndPort master = currentHostMaster;
final HostAndPort connection = new HostAndPort(jedis.getClient().getHost(), final HostAndPort connection = new HostAndPort(jedis.getClient()
jedis.getClient().getPort()); .getHost(), jedis.getClient().getPort());
if (master.equals(connection)) { if (master.equals(connection)) {
// connected to the correct master // connected to the correct master
return jedis; return jedis;
} else { } else {
returnBrokenResource(jedis); returnBrokenResource(jedis);
} }
} }
} }

View File

@@ -1,39 +1,41 @@
package redis.clients.jedis; package redis.clients.jedis;
import redis.clients.jedis.exceptions.JedisConnectionException;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.exceptions.JedisConnectionException;
public class JedisSlotBasedConnectionHandler extends public class JedisSlotBasedConnectionHandler extends
JedisClusterConnectionHandler { JedisClusterConnectionHandler {
public JedisSlotBasedConnectionHandler(Set<HostAndPort> nodes, public JedisSlotBasedConnectionHandler(Set<HostAndPort> nodes,
final GenericObjectPoolConfig poolConfig) { final GenericObjectPoolConfig poolConfig) {
super(nodes, poolConfig); super(nodes, poolConfig);
} }
public Jedis getConnection() { public Jedis getConnection() {
// In antirez's redis-rb-cluster implementation, // In antirez's redis-rb-cluster implementation,
// getRandomConnection always return valid connection (able to ping-pong) // getRandomConnection always return valid connection (able to
// ping-pong)
// or exception if all connections are invalid // or exception if all connections are invalid
List<JedisPool> pools = getShuffledNodesPool(); List<JedisPool> pools = getShuffledNodesPool();
for (JedisPool pool : pools) { for (JedisPool pool : pools) {
Jedis jedis = null; Jedis jedis = null;
try { try {
jedis = pool.getResource(); jedis = pool.getResource();
if (jedis == null) { if (jedis == null) {
continue; continue;
} }
String result = jedis.ping(); String result = jedis.ping();
if (result.equalsIgnoreCase("pong")) if (result.equalsIgnoreCase("pong"))
return jedis; return jedis;
@@ -44,7 +46,7 @@ public class JedisSlotBasedConnectionHandler extends
} }
} }
} }
throw new JedisConnectionException("no reachable node in cluster"); throw new JedisConnectionException("no reachable node in cluster");
} }
@@ -52,13 +54,14 @@ public class JedisSlotBasedConnectionHandler extends
public Jedis getConnectionFromSlot(int slot) { public Jedis getConnectionFromSlot(int slot) {
JedisPool connectionPool = cache.getSlotPool(slot); JedisPool connectionPool = cache.getSlotPool(slot);
if (connectionPool != null) { if (connectionPool != null) {
// It can't guaranteed to get valid connection because of node assignment // It can't guaranteed to get valid connection because of node
// assignment
return connectionPool.getResource(); return connectionPool.getResource();
} else { } else {
return getConnection(); return getConnection();
} }
} }
private List<JedisPool> getShuffledNodesPool() { private List<JedisPool> getShuffledNodesPool() {
List<JedisPool> pools = new ArrayList<JedisPool>(); List<JedisPool> pools = new ArrayList<JedisPool>();
pools.addAll(cache.getNodes().values()); pools.addAll(cache.getNodes().values());

View File

@@ -69,7 +69,7 @@ public interface MultiKeyBinaryCommands {
byte[] randomBinaryKey(); byte[] randomBinaryKey();
Long bitop(BitOP op, final byte[] destKey, byte[]... srcKeys); Long bitop(BitOP op, final byte[] destKey, byte[]... srcKeys);
String pfmerge(final byte[] destkey, final byte[]... sourcekeys); String pfmerge(final byte[] destkey, final byte[]... sourcekeys);
Long pfcount(byte[]... keys); Long pfcount(byte[]... keys);

View File

@@ -65,8 +65,8 @@ public interface MultiKeyBinaryRedisPipeline {
Response<byte[]> randomKeyBinary(); Response<byte[]> randomKeyBinary();
Response<Long> bitop(BitOP op, final byte[] destKey, byte[]... srcKeys); Response<Long> bitop(BitOP op, final byte[] destKey, byte[]... srcKeys);
Response<String> pfmerge(final byte[] destkey, final byte[]... sourcekeys); Response<String> pfmerge(final byte[] destkey, final byte[]... sourcekeys);
Response<Long> pfcount(final byte[] ... keys); Response<Long> pfcount(final byte[]... keys);
} }

View File

@@ -71,8 +71,8 @@ public interface MultiKeyCommands {
Long bitop(BitOP op, final String destKey, String... srcKeys); Long bitop(BitOP op, final String destKey, String... srcKeys);
ScanResult<String> scan(final String cursor); ScanResult<String> scan(final String cursor);
String pfmerge(final String destkey, final String... sourcekeys); String pfmerge(final String destkey, final String... sourcekeys);
long pfcount(final String...keys); long pfcount(final String... keys);
} }

View File

@@ -64,8 +64,8 @@ public interface MultiKeyCommandsPipeline {
Response<String> randomKey(); Response<String> randomKey();
Response<Long> bitop(BitOP op, final String destKey, String... srcKeys); Response<Long> bitop(BitOP op, final String destKey, String... srcKeys);
Response<String> pfmerge(final String destkey, final String... sourcekeys); Response<String> pfmerge(final String destkey, final String... sourcekeys);
Response<Long> pfcount(final String...keys); Response<Long> pfcount(final String... keys);
} }

View File

@@ -367,10 +367,10 @@ abstract class MultiKeyPipelineBase extends PipelineBase implements
client.info(); client.info();
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<List<String>> time() { public Response<List<String>> time() {
client.time(); client.time();
return getResponse(BuilderFactory.STRING_LIST); return getResponse(BuilderFactory.STRING_LIST);
} }
public Response<Long> dbSize() { public Response<Long> dbSize() {
@@ -451,7 +451,7 @@ abstract class MultiKeyPipelineBase extends PipelineBase implements
client.clusterSetSlotImporting(slot, nodeId); client.clusterSetSlotImporting(slot, nodeId);
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
@Override @Override
public Response<String> pfmerge(byte[] destkey, byte[]... sourcekeys) { public Response<String> pfmerge(byte[] destkey, byte[]... sourcekeys) {
client.pfmerge(destkey, sourcekeys); client.pfmerge(destkey, sourcekeys);
@@ -465,13 +465,13 @@ abstract class MultiKeyPipelineBase extends PipelineBase implements
} }
@Override @Override
public Response<Long> pfcount(String...keys) { public Response<Long> pfcount(String... keys) {
client.pfcount(keys); client.pfcount(keys);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
@Override @Override
public Response<Long> pfcount(final byte[] ... keys) { public Response<Long> pfcount(final byte[]... keys) {
client.pfcount(keys); client.pfcount(keys);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }

View File

@@ -1,10 +1,10 @@
package redis.clients.jedis; package redis.clients.jedis;
import redis.clients.jedis.exceptions.JedisDataException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import redis.clients.jedis.exceptions.JedisDataException;
public class Pipeline extends MultiKeyPipelineBase { public class Pipeline extends MultiKeyPipelineBase {
private MultiResponseBuilder currentMulti; private MultiResponseBuilder currentMulti;
@@ -150,5 +150,5 @@ public class Pipeline extends MultiKeyPipelineBase {
currentMulti = new MultiResponseBuilder(); currentMulti = new MultiResponseBuilder();
return response; return response;
} }
} }

View File

@@ -142,25 +142,27 @@ abstract class PipelineBase extends Queable implements BinaryRedisPipeline,
getClient(key).getbit(key, offset); getClient(key).getbit(key, offset);
return getResponse(BuilderFactory.BOOLEAN); return getResponse(BuilderFactory.BOOLEAN);
} }
public Response<Long> bitpos(final String key, final boolean value) { public Response<Long> bitpos(final String key, final boolean value) {
return bitpos(key, value, new BitPosParams()); return bitpos(key, value, new BitPosParams());
} }
public Response<Long> bitpos(final String key, final boolean value, final BitPosParams params) { public Response<Long> bitpos(final String key, final boolean value,
final BitPosParams params) {
getClient(key).bitpos(key, value, params); getClient(key).bitpos(key, value, params);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Long> bitpos(final byte[] key, final boolean value) { public Response<Long> bitpos(final byte[] key, final boolean value) {
return bitpos(key, value, new BitPosParams()); return bitpos(key, value, new BitPosParams());
} }
public Response<Long> bitpos(final byte[] key, final boolean value, final BitPosParams params) { public Response<Long> bitpos(final byte[] key, final boolean value,
final BitPosParams params) {
getClient(key).bitpos(key, value, params); getClient(key).bitpos(key, value, params);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<String> getrange(String key, long startOffset, public Response<String> getrange(String key, long startOffset,
long endOffset) { long endOffset) {
getClient(key).getrange(key, startOffset, endOffset); getClient(key).getrange(key, startOffset, endOffset);
@@ -177,7 +179,8 @@ abstract class PipelineBase extends Queable implements BinaryRedisPipeline,
return getResponse(BuilderFactory.BYTE_ARRAY); return getResponse(BuilderFactory.BYTE_ARRAY);
} }
public Response<byte[]> getrange(byte[] key, long startOffset, long endOffset) { public Response<byte[]> getrange(byte[] key, long startOffset,
long endOffset) {
getClient(key).getrange(key, startOffset, endOffset); getClient(key).getrange(key, startOffset, endOffset);
return getResponse(BuilderFactory.BYTE_ARRAY); return getResponse(BuilderFactory.BYTE_ARRAY);
} }
@@ -1027,77 +1030,89 @@ abstract class PipelineBase extends Queable implements BinaryRedisPipeline,
} }
@Override @Override
public Response<Long> zlexcount(final byte[] key, final byte[] min, final byte[] max) { public Response<Long> zlexcount(final byte[] key, final byte[] min,
final byte[] max) {
getClient(key).zlexcount(key, min, max); getClient(key).zlexcount(key, min, max);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
@Override @Override
public Response<Long> zlexcount(final String key, final String min, final String max) { public Response<Long> zlexcount(final String key, final String min,
final String max) {
getClient(key).zlexcount(key, min, max); getClient(key).zlexcount(key, min, max);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
@Override @Override
public Response<Set<byte[]>> zrangeByLex(final byte[] key, final byte[] min, final byte[] max) { public Response<Set<byte[]>> zrangeByLex(final byte[] key,
final byte[] min, final byte[] max) {
getClient(key).zrangeByLex(key, min, max); getClient(key).zrangeByLex(key, min, max);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
} }
@Override @Override
public Response<Set<String>> zrangeByLex(final String key, final String min, final String max) { public Response<Set<String>> zrangeByLex(final String key,
final String min, final String max) {
getClient(key).zrangeByLex(key, min, max); getClient(key).zrangeByLex(key, min, max);
return getResponse(BuilderFactory.STRING_ZSET); return getResponse(BuilderFactory.STRING_ZSET);
} }
@Override @Override
public Response<Set<byte[]>> zrangeByLex(final byte[] key, final byte[] min, public Response<Set<byte[]>> zrangeByLex(final byte[] key,
final byte[] max, final int offset, final int count) { final byte[] min, final byte[] max, final int offset,
final int count) {
getClient(key).zrangeByLex(key, min, max, offset, count); getClient(key).zrangeByLex(key, min, max, offset, count);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
} }
@Override @Override
public Response<Set<String>> zrangeByLex(final String key, final String min, public Response<Set<String>> zrangeByLex(final String key,
final String max, final int offset, final int count) { final String min, final String max, final int offset,
final int count) {
getClient(key).zrangeByLex(key, min, max, offset, count); getClient(key).zrangeByLex(key, min, max, offset, count);
return getResponse(BuilderFactory.STRING_ZSET); return getResponse(BuilderFactory.STRING_ZSET);
} }
@Override @Override
public Response<Set<byte[]>> zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min) { public Response<Set<byte[]>> zrevrangeByLex(final byte[] key,
final byte[] max, final byte[] min) {
getClient(key).zrevrangeByLex(key, max, min); getClient(key).zrevrangeByLex(key, max, min);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
} }
@Override @Override
public Response<Set<String>> zrevrangeByLex(final String key, final String max, final String min) { public Response<Set<String>> zrevrangeByLex(final String key,
final String max, final String min) {
getClient(key).zrevrangeByLex(key, max, min); getClient(key).zrevrangeByLex(key, max, min);
return getResponse(BuilderFactory.STRING_ZSET); return getResponse(BuilderFactory.STRING_ZSET);
} }
@Override @Override
public Response<Set<byte[]>> zrevrangeByLex(final byte[] key, final byte[] max, public Response<Set<byte[]>> zrevrangeByLex(final byte[] key,
final byte[] min, final int offset, final int count) { final byte[] max, final byte[] min, final int offset,
final int count) {
getClient(key).zrevrangeByLex(key, max, min, offset, count); getClient(key).zrevrangeByLex(key, max, min, offset, count);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
} }
@Override @Override
public Response<Set<String>> zrevrangeByLex(final String key, final String max, public Response<Set<String>> zrevrangeByLex(final String key,
final String min, final int offset, final int count) { final String max, final String min, final int offset,
final int count) {
getClient(key).zrevrangeByLex(key, max, min, offset, count); getClient(key).zrevrangeByLex(key, max, min, offset, count);
return getResponse(BuilderFactory.STRING_ZSET); return getResponse(BuilderFactory.STRING_ZSET);
} }
@Override @Override
public Response<Long> zremrangeByLex(final byte[] key, final byte[] min, final byte[] max) { public Response<Long> zremrangeByLex(final byte[] key, final byte[] min,
final byte[] max) {
getClient(key).zremrangeByLex(key, min, max); getClient(key).zremrangeByLex(key, min, max);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
@Override @Override
public Response<Long> zremrangeByLex(final String key, final String min, final String max) { public Response<Long> zremrangeByLex(final String key, final String min,
final String max) {
getClient(key).zremrangeByLex(key, min, max); getClient(key).zremrangeByLex(key, min, max);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
@@ -1321,5 +1336,5 @@ abstract class PipelineBase extends Queable implements BinaryRedisPipeline,
getClient(key).pfcount(key); getClient(key).pfcount(key);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
} }

View File

@@ -62,7 +62,7 @@ public final class Protocol {
public static final String CLUSTER_SLAVES = "slaves"; public static final String CLUSTER_SLAVES = "slaves";
public static final String CLUSTER_FAILOVER = "failover"; public static final String CLUSTER_FAILOVER = "failover";
public static final String CLUSTER_SLOTS = "slots"; public static final String CLUSTER_SLOTS = "slots";
public static final String PUBSUB_CHANNELS= "channels"; public static final String PUBSUB_CHANNELS = "channels";
public static final String PUBSUB_NUMSUB = "numsub"; public static final String PUBSUB_NUMSUB = "numsub";
public static final String PUBSUB_NUM_PAT = "numpat"; public static final String PUBSUB_NUM_PAT = "numpat";
@@ -204,7 +204,7 @@ public final class Protocol {
} }
public static final byte[] toByteArray(final boolean value) { public static final byte[] toByteArray(final boolean value) {
return toByteArray(value ? 1 : 0); return toByteArray(value ? 1 : 0);
} }
public static final byte[] toByteArray(final int value) { public static final byte[] toByteArray(final int value) {

View File

@@ -184,26 +184,30 @@ public interface RedisPipeline {
Response<Long> zrevrank(String key, String member); Response<Long> zrevrank(String key, String member);
Response<Double> zscore(String key, String member); Response<Double> zscore(String key, String member);
Response<Long> zlexcount(final String key, final String min, final String max);
Response<Set<String>> zrangeByLex(final String key, final String min, final String max);
Response<Set<String>> zrangeByLex(final String key, final String min, final String max, Response<Long> zlexcount(final String key, final String min,
final int offset, final int count); final String max);
Response<Set<String>> zrevrangeByLex(final String key, final String max, final String min); Response<Set<String>> zrangeByLex(final String key, final String min,
final String max);
Response<Set<String>> zrevrangeByLex(final String key, final String max, final String min,
final int offset, final int count); Response<Set<String>> zrangeByLex(final String key, final String min,
final String max, final int offset, final int count);
Response<Long> zremrangeByLex(final String key, final String start, final String end);
Response<Set<String>> zrevrangeByLex(final String key, final String max,
final String min);
Response<Set<String>> zrevrangeByLex(final String key, final String max,
final String min, final int offset, final int count);
Response<Long> zremrangeByLex(final String key, final String start,
final String end);
Response<Long> bitcount(String key); Response<Long> bitcount(String key);
Response<Long> bitcount(String key, long start, long end); Response<Long> bitcount(String key, long start, long end);
Response<Long> pfadd(final String key, final String... elements); Response<Long> pfadd(final String key, final String... elements);
Response<Long> pfcount(final String key); Response<Long> pfcount(final String key);
} }

View File

@@ -13,14 +13,15 @@ import redis.clients.util.SafeEncoder;
public class ScanParams { public class ScanParams {
private List<byte[]> params = new ArrayList<byte[]>(); private List<byte[]> params = new ArrayList<byte[]>();
public final static String SCAN_POINTER_START = String.valueOf(0); public final static String SCAN_POINTER_START = String.valueOf(0);
public final static byte[] SCAN_POINTER_START_BINARY = SafeEncoder.encode(SCAN_POINTER_START); public final static byte[] SCAN_POINTER_START_BINARY = SafeEncoder
.encode(SCAN_POINTER_START);
public ScanParams match(final byte[] pattern) { public ScanParams match(final byte[] pattern) {
params.add(MATCH.raw); params.add(MATCH.raw);
params.add(pattern); params.add(pattern);
return this; return this;
} }
public ScanParams match(final String pattern) { public ScanParams match(final String pattern) {
params.add(MATCH.raw); params.add(MATCH.raw);
params.add(SafeEncoder.encode(pattern)); params.add(SafeEncoder.encode(pattern));

View File

@@ -16,15 +16,15 @@ public class ScanResult<T> {
this.cursor = cursor; this.cursor = cursor;
this.results = results; this.results = results;
} }
public String getCursor() { public String getCursor() {
return SafeEncoder.encode(cursor); return SafeEncoder.encode(cursor);
} }
public byte[] getCursorAsBytes() { public byte[] getCursorAsBytes() {
return cursor; return cursor;
} }
public List<T> getResult() { public List<T> getResult() {
return results; return results;
} }

View File

@@ -4,19 +4,21 @@ import java.util.List;
import java.util.Map; import java.util.Map;
public interface SentinelCommands { public interface SentinelCommands {
public List<Map<String, String>> sentinelMasters(); public List<Map<String, String>> sentinelMasters();
public List<String> sentinelGetMasterAddrByName(String masterName); public List<String> sentinelGetMasterAddrByName(String masterName);
public Long sentinelReset(String pattern); public Long sentinelReset(String pattern);
public List<Map<String, String>> sentinelSlaves(String masterName); public List<Map<String, String>> sentinelSlaves(String masterName);
public String sentinelFailover(String masterName); public String sentinelFailover(String masterName);
public String sentinelMonitor(String masterName, String ip, int port, int quorum); public String sentinelMonitor(String masterName, String ip, int port,
int quorum);
public String sentinelRemove(String masterName);
public String sentinelRemove(String masterName);
public String sentinelSet(String masterName, Map<String, String> parameterMap);
public String sentinelSet(String masterName,
Map<String, String> parameterMap);
} }

View File

@@ -1,16 +1,14 @@
package redis.clients.jedis; package redis.clients.jedis;
import java.io.Closeable; import java.io.Closeable;
import redis.clients.jedis.BinaryClient.LIST_POSITION;
import redis.clients.util.Hashing;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Set; import java.util.Set;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import redis.clients.jedis.BinaryClient.LIST_POSITION;
import redis.clients.util.Hashing;
import redis.clients.util.Pool; import redis.clients.util.Pool;
public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, public class ShardedJedis extends BinaryShardedJedis implements JedisCommands,
@@ -126,18 +124,22 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands,
Jedis j = getShard(arg); Jedis j = getShard(arg);
return j.blpop(arg); return j.blpop(arg);
} }
public List<String> blpop(int timeout,String key){
public List<String> blpop(int timeout, String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.blpop(timeout,key); return j.blpop(timeout, key);
} }
public List<String> brpop(String arg) { public List<String> brpop(String arg) {
Jedis j = getShard(arg); Jedis j = getShard(arg);
return j.brpop(arg); return j.brpop(arg);
} }
public List<String> brpop(int timeout,String key) {
public List<String> brpop(int timeout, String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.brpop(timeout,key); return j.brpop(timeout, key);
} }
public Long decrBy(String key, long integer) { public Long decrBy(String key, long integer) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.decrBy(key, integer); return j.decrBy(key, integer);
@@ -355,8 +357,8 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands,
@Override @Override
public List<String> srandmember(String key, int count) { public List<String> srandmember(String key, int count) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.srandmember(key, count); return j.srandmember(key, count);
} }
public Long zadd(String key, double score, String member) { public Long zadd(String key, double score, String member) {
@@ -543,23 +545,24 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands,
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zremrangeByScore(key, start, end); return j.zremrangeByScore(key, start, end);
} }
@Override @Override
public Long zlexcount(final String key, final String min, final String max) { public Long zlexcount(final String key, final String min, final String max) {
return getShard(key).zlexcount(key, min, max); return getShard(key).zlexcount(key, min, max);
} }
@Override @Override
public Set<String> zrangeByLex(final String key, final String min, final String max) { public Set<String> zrangeByLex(final String key, final String min,
final String max) {
return getShard(key).zrangeByLex(key, min, max); return getShard(key).zrangeByLex(key, min, max);
} }
@Override @Override
public Set<String> zrangeByLex(final String key, final String min, final String max, public Set<String> zrangeByLex(final String key, final String min,
final int offset, final int count) { final String max, final int offset, final int count) {
return getShard(key).zrangeByLex(key, min, max, offset, count); return getShard(key).zrangeByLex(key, min, max, offset, count);
} }
@Override @Override
public Set<String> zrevrangeByLex(String key, String max, String min) { public Set<String> zrevrangeByLex(String key, String max, String min) {
return getShard(key).zrevrangeByLex(key, max, min); return getShard(key).zrevrangeByLex(key, max, min);
@@ -570,9 +573,10 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands,
int offset, int count) { int offset, int count) {
return getShard(key).zrevrangeByLex(key, max, min, offset, count); return getShard(key).zrevrangeByLex(key, max, min, offset, count);
} }
@Override @Override
public Long zremrangeByLex(final String key, final String min, final String max) { public Long zremrangeByLex(final String key, final String min,
final String max) {
return getShard(key).zremrangeByLex(key, min, max); return getShard(key).zremrangeByLex(key, min, max);
} }
@@ -592,7 +596,8 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands,
return j.bitcount(key, start, end); return j.bitcount(key, start, end);
} }
public ScanResult<Entry<String, String>> hscan(String key, final String cursor) { public ScanResult<Entry<String, String>> hscan(String key,
final String cursor) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hscan(key, cursor); return j.hscan(key, cursor);
} }

View File

@@ -23,12 +23,12 @@ public class ZParams {
private List<byte[]> params = new ArrayList<byte[]>(); private List<byte[]> params = new ArrayList<byte[]>();
/** /**
* Set weights. * Set weights.
* *
* @param weights * @param weights
* weights. * weights.
*/ */
public ZParams weights(final double... weights) { public ZParams weights(final double... weights) {
params.add(WEIGHTS.raw); params.add(WEIGHTS.raw);
for (final double weight : weights) { for (final double weight : weights) {

View File

@@ -1,10 +1,10 @@
package redis.clients.util; package redis.clients.util;
import redis.clients.jedis.HostAndPort;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import redis.clients.jedis.HostAndPort;
public class ClusterNodeInformation { public class ClusterNodeInformation {
private HostAndPort node; private HostAndPort node;
private List<Integer> availableSlots; private List<Integer> availableSlots;
@@ -14,35 +14,35 @@ public class ClusterNodeInformation {
public ClusterNodeInformation(HostAndPort node) { public ClusterNodeInformation(HostAndPort node) {
this.node = node; this.node = node;
this.availableSlots = new ArrayList<Integer>(); this.availableSlots = new ArrayList<Integer>();
this.slotsBeingImported = new ArrayList<Integer>(); this.slotsBeingImported = new ArrayList<Integer>();
this.slotsBeingMigrated = new ArrayList<Integer>(); this.slotsBeingMigrated = new ArrayList<Integer>();
} }
public void addAvailableSlot(int slot) { public void addAvailableSlot(int slot) {
availableSlots.add(slot); availableSlots.add(slot);
} }
public void addSlotBeingImported(int slot) { public void addSlotBeingImported(int slot) {
slotsBeingImported.add(slot); slotsBeingImported.add(slot);
} }
public void addSlotBeingMigrated(int slot) { public void addSlotBeingMigrated(int slot) {
slotsBeingMigrated.add(slot); slotsBeingMigrated.add(slot);
} }
public HostAndPort getNode() { public HostAndPort getNode() {
return node; return node;
} }
public List<Integer> getAvailableSlots() { public List<Integer> getAvailableSlots() {
return availableSlots; return availableSlots;
} }
public List<Integer> getSlotsBeingImported() { public List<Integer> getSlotsBeingImported() {
return slotsBeingImported; return slotsBeingImported;
} }
public List<Integer> getSlotsBeingMigrated() { public List<Integer> getSlotsBeingMigrated() {
return slotsBeingMigrated; return slotsBeingMigrated;
} }
} }

View File

@@ -1,39 +1,53 @@
package redis.clients.util; package redis.clients.util;
/** /**
* CRC16 Implementation according to CCITT standard * CRC16 Implementation according to CCITT standard Polynomial : 1021 (x^16 +
* Polynomial : 1021 (x^16 + x^12 + x^5 + 1) * x^12 + x^5 + 1)
* *
* @see http://redis.io/topics/cluster-spec * @see http://redis.io/topics/cluster-spec Appendix A. CRC16 reference
* Appendix A. CRC16 reference implementation in ANSI C * implementation in ANSI C
*/ */
public class JedisClusterCRC16 { public class JedisClusterCRC16 {
private static final int LOOKUP_TABLE[] = { 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, 0x8108, 0x9129, private static final int LOOKUP_TABLE[] = { 0x0000, 0x1021, 0x2042, 0x3063,
0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, 0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, 0x4084, 0x50A5, 0x60C6, 0x70E7, 0x8108, 0x9129, 0xA14A, 0xB16B,
0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, 0x1231, 0x0210, 0x3273, 0x2252,
0x44A4, 0x5485, 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, 0x3653, 0x2672, 0x1611, 0x0630, 0x52B5, 0x4294, 0x72F7, 0x62D6, 0x9339, 0x8318, 0xB37B, 0xA35A,
0x76D7, 0x66F6, 0x5695, 0x46B4, 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, 0x48C4, 0x58E5, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, 0x2462, 0x3443, 0x0420, 0x1401,
0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B, 0x64E6, 0x74C7, 0x44A4, 0x5485, 0xA56A, 0xB54B, 0x8528, 0x9509,
0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, 0x3653, 0x2672, 0x1611, 0x0630,
0xBB3B, 0xAB1A, 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0x76D7, 0x66F6, 0x5695, 0x46B4, 0xB75B, 0xA77A, 0x9719, 0x8738,
0xAD2A, 0xBD0B, 0x8D68, 0x9D49, 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, 0xFF9F, 0xEFBE, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, 0x48C4, 0x58E5, 0x6886, 0x78A7,
0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, 0x0840, 0x1861, 0x2802, 0x3823, 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF,
0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0x8948, 0x9969, 0xA90A, 0xB92B, 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96,
0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0x1A71, 0x0A50, 0x3A33, 0x2A12, 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E,
0xF56E, 0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xA7DB, 0xB7FA, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A, 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5,
0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, 0x2C22, 0x3C03, 0x0C60, 0x1C41, 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD,
0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49, 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4,
0x3882, 0x28A3, 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x3E13, 0x2E32, 0x1E51, 0x0E70, 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC,
0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, 0x9188, 0x81A9, 0xB1CA, 0xA1EB,
0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, 0xD10C, 0xC12D, 0xF14E, 0xE16F, 0x1080, 0x00A1, 0x30C2, 0x20E3,
0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0, }; 0x5004, 0x4025, 0x7046, 0x6067, 0x83B9, 0x9398, 0xA3FB, 0xB3DA,
0xC33D, 0xD31C, 0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2,
0x4235, 0x5214, 0x6277, 0x7256, 0xB5EA, 0xA5CB, 0x95A8, 0x8589,
0xF56E, 0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, 0x0481,
0x7466, 0x6447, 0x5424, 0x4405, 0xA7DB, 0xB7FA, 0x8799, 0x97B8,
0xE75F, 0xF77E, 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691, 0x16B0,
0x6657, 0x7676, 0x4615, 0x5634, 0xD94C, 0xC96D, 0xF90E, 0xE92F,
0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827,
0x18C0, 0x08E1, 0x3882, 0x28A3, 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E,
0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16,
0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D,
0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07, 0x5C64, 0x4C45,
0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C,
0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, 0x6E17, 0x7E36, 0x4E55, 0x5E74,
0x2E93, 0x3EB2, 0x0ED1, 0x1EF0, };
public static int getSlot(String key) { public static int getSlot(String key) {
int s = key.indexOf("{"); int s = key.indexOf("{");
if (s > -1) { if (s > -1) {
int e = key.indexOf("}", s+1); int e = key.indexOf("}", s + 1);
if (e > -1 && e != s+1) { if (e > -1 && e != s + 1) {
key = key.substring(s+1, e); key = key.substring(s + 1, e);
} }
} }
// optimization with modulo operator with power of 2 // optimization with modulo operator with power of 2
@@ -42,8 +56,8 @@ public class JedisClusterCRC16 {
} }
/** /**
* Create a CRC16 checksum from the bytes. * Create a CRC16 checksum from the bytes. implementation is from
* implementation is from mp911de/lettuce, modified with some more optimizations * mp911de/lettuce, modified with some more optimizations
* *
* @param bytes * @param bytes
* @return CRC16 as integer value * @return CRC16 as integer value

View File

@@ -10,35 +10,35 @@ import redis.clients.jedis.exceptions.JedisConnectionException;
public class ConnectionCloseTest extends Assert { public class ConnectionCloseTest extends Assert {
private Connection client; private Connection client;
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
client = new Connection(); client = new Connection();
} }
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
client.close(); client.close();
} }
@Test(expected = JedisConnectionException.class) @Test(expected = JedisConnectionException.class)
public void checkUnkownHost() { public void checkUnkownHost() {
client.setHost("someunknownhost"); client.setHost("someunknownhost");
client.connect(); client.connect();
} }
@Test(expected = JedisConnectionException.class) @Test(expected = JedisConnectionException.class)
public void checkWrongPort() { public void checkWrongPort() {
client.setHost("localhost"); client.setHost("localhost");
client.setPort(55665); client.setPort(55665);
client.connect(); client.connect();
} }
@Test @Test
public void connectIfNotConnectedWhenSettingTimeoutInfinite() { public void connectIfNotConnectedWhenSettingTimeoutInfinite() {
client.setHost("localhost"); client.setHost("localhost");
client.setPort(6379); client.setPort(6379);
client.setTimeoutInfinite(); client.setTimeoutInfinite();
} }
} }

View File

@@ -12,18 +12,29 @@ public class HostAndPortUtil {
private static List<HostAndPort> clusterHostAndPortList = new ArrayList<HostAndPort>(); private static List<HostAndPort> clusterHostAndPortList = new ArrayList<HostAndPort>();
static { static {
redisHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_PORT)); redisHostAndPortList.add(new HostAndPort("localhost",
redisHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_PORT + 1)); Protocol.DEFAULT_PORT));
redisHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_PORT + 2)); redisHostAndPortList.add(new HostAndPort("localhost",
redisHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_PORT + 3)); Protocol.DEFAULT_PORT + 1));
redisHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_PORT + 4)); redisHostAndPortList.add(new HostAndPort("localhost",
redisHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_PORT + 5)); Protocol.DEFAULT_PORT + 2));
redisHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_PORT + 6)); redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 3));
sentinelHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_SENTINEL_PORT)); redisHostAndPortList.add(new HostAndPort("localhost",
sentinelHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_SENTINEL_PORT + 1)); Protocol.DEFAULT_PORT + 4));
sentinelHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_SENTINEL_PORT + 2)); redisHostAndPortList.add(new HostAndPort("localhost",
sentinelHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_SENTINEL_PORT + 3)); Protocol.DEFAULT_PORT + 5));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 6));
sentinelHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_SENTINEL_PORT));
sentinelHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_SENTINEL_PORT + 1));
sentinelHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_SENTINEL_PORT + 2));
sentinelHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_SENTINEL_PORT + 3));
clusterHostAndPortList.add(new HostAndPort("localhost", 7379)); clusterHostAndPortList.add(new HostAndPort("localhost", 7379));
clusterHostAndPortList.add(new HostAndPort("localhost", 7380)); clusterHostAndPortList.add(new HostAndPort("localhost", 7380));

View File

@@ -3,6 +3,7 @@ package redis.clients.jedis.tests;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import redis.clients.jedis.HostAndPort; import redis.clients.jedis.HostAndPort;
import redis.clients.util.ClusterNodeInformation; import redis.clients.util.ClusterNodeInformation;
import redis.clients.util.ClusterNodeInformationParser; import redis.clients.util.ClusterNodeInformationParser;

View File

@@ -5,14 +5,13 @@ import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.logging.Logger;
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.junit.After; import org.junit.After;
@@ -40,14 +39,14 @@ public class JedisClusterTest extends Assert {
private static Jedis node2; private static Jedis node2;
private static Jedis node3; private static Jedis node3;
private static Jedis node4; private static Jedis node4;
private String localHost = "127.0.0.1"; private String localHost = "127.0.0.1";
private HostAndPort nodeInfo1 = HostAndPortUtil.getClusterServers().get(0); private HostAndPort nodeInfo1 = HostAndPortUtil.getClusterServers().get(0);
private HostAndPort nodeInfo2 = HostAndPortUtil.getClusterServers().get(1); private HostAndPort nodeInfo2 = HostAndPortUtil.getClusterServers().get(1);
private HostAndPort nodeInfo3 = HostAndPortUtil.getClusterServers().get(2); private HostAndPort nodeInfo3 = HostAndPortUtil.getClusterServers().get(2);
private HostAndPort nodeInfo4 = HostAndPortUtil.getClusterServers().get(3); private HostAndPort nodeInfo4 = HostAndPortUtil.getClusterServers().get(3);
protected Logger log = Logger.getLogger(getClass().getName()); protected Logger log = Logger.getLogger(getClass().getName());
@Before @Before
public void setUp() throws InterruptedException { public void setUp() throws InterruptedException {
node1 = new Jedis(nodeInfo1.getHost(), nodeInfo1.getPort()); node1 = new Jedis(nodeInfo1.getHost(), nodeInfo1.getPort());
@@ -61,7 +60,7 @@ public class JedisClusterTest extends Assert {
node3 = new Jedis(nodeInfo3.getHost(), nodeInfo3.getPort()); node3 = new Jedis(nodeInfo3.getHost(), nodeInfo3.getPort());
node3.connect(); node3.connect();
node3.flushAll(); node3.flushAll();
node4 = new Jedis(nodeInfo4.getHost(), nodeInfo4.getPort()); node4 = new Jedis(nodeInfo4.getHost(), nodeInfo4.getPort());
node4.connect(); node4.connect();
node4.flushAll(); node4.flushAll();
@@ -71,13 +70,13 @@ public class JedisClusterTest extends Assert {
// add nodes to cluster // add nodes to cluster
node1.clusterMeet(localHost, nodeInfo2.getPort()); node1.clusterMeet(localHost, nodeInfo2.getPort());
node1.clusterMeet(localHost, nodeInfo3.getPort()); node1.clusterMeet(localHost, nodeInfo3.getPort());
// split available slots across the three nodes // split available slots across the three nodes
int slotsPerNode = JedisCluster.HASHSLOTS / 3; int slotsPerNode = JedisCluster.HASHSLOTS / 3;
int[] node1Slots = new int[slotsPerNode]; int[] node1Slots = new int[slotsPerNode];
int[] node2Slots = new int[slotsPerNode+1]; int[] node2Slots = new int[slotsPerNode + 1];
int[] node3Slots = new int[slotsPerNode]; int[] node3Slots = new int[slotsPerNode];
for (int i = 0, slot1 = 0, slot2 = 0, slot3 = 0 ; i < JedisCluster.HASHSLOTS; i++) { for (int i = 0, slot1 = 0, slot2 = 0, slot3 = 0; i < JedisCluster.HASHSLOTS; i++) {
if (i < slotsPerNode) { if (i < slotsPerNode) {
node1Slots[slot1++] = i; node1Slots[slot1++] = i;
} else if (i > slotsPerNode * 2) { } else if (i > slotsPerNode * 2) {
@@ -86,14 +85,14 @@ public class JedisClusterTest extends Assert {
node2Slots[slot2++] = i; node2Slots[slot2++] = i;
} }
} }
node1.clusterAddSlots(node1Slots); node1.clusterAddSlots(node1Slots);
node2.clusterAddSlots(node2Slots); node2.clusterAddSlots(node2Slots);
node3.clusterAddSlots(node3Slots); node3.clusterAddSlots(node3Slots);
JedisClusterTestUtil.waitForClusterReady(node1, node2, node3); JedisClusterTestUtil.waitForClusterReady(node1, node2, node3);
} }
@AfterClass @AfterClass
public static void cleanUp() { public static void cleanUp() {
node1.flushDB(); node1.flushDB();
@@ -155,13 +154,12 @@ public class JedisClusterTest extends Assert {
assertEquals("bar", node3.get("foo")); assertEquals("bar", node3.get("foo"));
assertEquals("test", node2.get("test")); assertEquals("test", node2.get("test"));
} }
/** /**
* slot->nodes * slot->nodes 15363 node3 e
* 15363 node3 e
*/ */
@Test @Test
public void testMigrate(){ public void testMigrate() {
log.info("test migrate slot"); log.info("test migrate slot");
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(nodeInfo1); jedisClusterNode.add(nodeInfo1);
@@ -170,50 +168,52 @@ public class JedisClusterTest extends Assert {
String node2Id = JedisClusterTestUtil.getNodeId(node2.clusterNodes()); String node2Id = JedisClusterTestUtil.getNodeId(node2.clusterNodes());
node3.clusterSetSlotMigrating(15363, node2Id); node3.clusterSetSlotMigrating(15363, node2Id);
node2.clusterSetSlotImporting(15363, node3Id); node2.clusterSetSlotImporting(15363, node3Id);
try{ try {
node2.set("e", "e"); node2.set("e", "e");
}catch(JedisMovedDataException jme){ } catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot()); assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()), jme.getTargetNode()); assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()),
jme.getTargetNode());
} }
try{ try {
node3.set("e", "e"); node3.set("e", "e");
}catch(JedisAskDataException jae){ } catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot()); assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo2.getPort()), jae.getTargetNode()); assertEquals(new HostAndPort(localHost, nodeInfo2.getPort()),
jae.getTargetNode());
} }
jc.set("e", "e"); jc.set("e", "e");
try{ try {
node2.get("e"); node2.get("e");
}catch(JedisMovedDataException jme){ } catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot()); assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()), jme.getTargetNode()); assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()),
jme.getTargetNode());
} }
try{ try {
node3.get("e"); node3.get("e");
}catch(JedisAskDataException jae){ } catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot()); assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo2.getPort()), jae.getTargetNode()); assertEquals(new HostAndPort(localHost, nodeInfo2.getPort()),
jae.getTargetNode());
} }
assertEquals("e", jc.get("e")); assertEquals("e", jc.get("e"));
node2.clusterSetSlotNode(15363, node2Id); node2.clusterSetSlotNode(15363, node2Id);
node3.clusterSetSlotNode(15363, node2Id); node3.clusterSetSlotNode(15363, node2Id);
//assertEquals("e", jc.get("e")); // assertEquals("e", jc.get("e"));
assertEquals("e", node2.get("e")); assertEquals("e", node2.get("e"));
//assertEquals("e", node3.get("e")); // assertEquals("e", node3.get("e"));
} }
@Test @Test
public void testMigrateToNewNode() throws InterruptedException{ public void testMigrateToNewNode() throws InterruptedException {
log.info("test migrate slot to new node"); log.info("test migrate slot to new node");
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(nodeInfo1); jedisClusterNode.add(nodeInfo1);
@@ -221,48 +221,52 @@ public class JedisClusterTest extends Assert {
node4.clusterMeet(localHost, nodeInfo1.getPort()); node4.clusterMeet(localHost, nodeInfo1.getPort());
String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes()); String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes());
String node4Id = JedisClusterTestUtil.getNodeId(node4.clusterNodes()); String node4Id = JedisClusterTestUtil.getNodeId(node4.clusterNodes());
JedisClusterTestUtil.waitForClusterReady(node4); JedisClusterTestUtil.waitForClusterReady(node4);
node3.clusterSetSlotMigrating(15363, node4Id); node3.clusterSetSlotMigrating(15363, node4Id);
node4.clusterSetSlotImporting(15363, node3Id); node4.clusterSetSlotImporting(15363, node3Id);
try{ try {
node4.set("e", "e"); node4.set("e", "e");
}catch(JedisMovedDataException jme){ } catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot()); assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()), jme.getTargetNode()); assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()),
jme.getTargetNode());
} }
try{ try {
node3.set("e", "e"); node3.set("e", "e");
}catch(JedisAskDataException jae){ } catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot()); assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo4.getPort()), jae.getTargetNode()); assertEquals(new HostAndPort(localHost, nodeInfo4.getPort()),
jae.getTargetNode());
} }
jc.set("e", "e"); jc.set("e", "e");
try{ try {
node4.get("e"); node4.get("e");
}catch(JedisMovedDataException jme){ } catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot()); assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()), jme.getTargetNode()); assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()),
jme.getTargetNode());
} }
try{ try {
node3.get("e"); node3.get("e");
}catch(JedisAskDataException jae){ } catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot()); assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo4.getPort()), jae.getTargetNode()); assertEquals(new HostAndPort(localHost, nodeInfo4.getPort()),
jae.getTargetNode());
} }
assertEquals("e", jc.get("e")); assertEquals("e", jc.get("e"));
node4.clusterSetSlotNode(15363, node4Id); node4.clusterSetSlotNode(15363, node4Id);
node3.clusterSetSlotNode(15363, node4Id); node3.clusterSetSlotNode(15363, node4Id);
//assertEquals("e", jc.get("e")); // assertEquals("e", jc.get("e"));
assertEquals("e", node4.get("e")); assertEquals("e", node4.get("e"));
//assertEquals("e", node3.get("e")); // assertEquals("e", node3.get("e"));
} }
@Test @Test
@@ -286,8 +290,10 @@ public class JedisClusterTest extends Assert {
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode); JedisCluster jc = new JedisCluster(jedisClusterNode);
int slot51 = JedisClusterCRC16.getSlot("51"); int slot51 = JedisClusterCRC16.getSlot("51");
node3.clusterSetSlotImporting(slot51, JedisClusterTestUtil.getNodeId(node2.clusterNodes())); node3.clusterSetSlotImporting(slot51,
node2.clusterSetSlotMigrating(slot51, JedisClusterTestUtil.getNodeId(node3.clusterNodes())); JedisClusterTestUtil.getNodeId(node2.clusterNodes()));
node2.clusterSetSlotMigrating(slot51,
JedisClusterTestUtil.getNodeId(node3.clusterNodes()));
jc.set("51", "foo"); jc.set("51", "foo");
assertEquals("foo", jc.get("51")); assertEquals("foo", jc.get("51"));
} }
@@ -307,56 +313,61 @@ public class JedisClusterTest extends Assert {
JedisCluster jc = new JedisCluster(jedisClusterNode); JedisCluster jc = new JedisCluster(jedisClusterNode);
int slot51 = JedisClusterCRC16.getSlot("51"); int slot51 = JedisClusterCRC16.getSlot("51");
// This will cause an infinite redirection loop // This will cause an infinite redirection loop
node2.clusterSetSlotMigrating(slot51, JedisClusterTestUtil.getNodeId(node3.clusterNodes())); node2.clusterSetSlotMigrating(slot51,
JedisClusterTestUtil.getNodeId(node3.clusterNodes()));
jc.set("51", "foo"); jc.set("51", "foo");
} }
@Test @Test
public void testRedisHashtag() { public void testRedisHashtag() {
assertEquals(JedisClusterCRC16.getSlot("{bar"), JedisClusterCRC16.getSlot("foo{{bar}}zap")); assertEquals(JedisClusterCRC16.getSlot("{bar"),
assertEquals(JedisClusterCRC16.getSlot("{user1000}.following"), JedisClusterCRC16.getSlot("{user1000}.followers")); JedisClusterCRC16.getSlot("foo{{bar}}zap"));
assertNotEquals(JedisClusterCRC16.getSlot("foo{}{bar}"), JedisClusterCRC16.getSlot("bar")); assertEquals(JedisClusterCRC16.getSlot("{user1000}.following"),
assertEquals(JedisClusterCRC16.getSlot("foo{bar}{zap}"), JedisClusterCRC16.getSlot("bar")); JedisClusterCRC16.getSlot("{user1000}.followers"));
assertNotEquals(JedisClusterCRC16.getSlot("foo{}{bar}"),
JedisClusterCRC16.getSlot("bar"));
assertEquals(JedisClusterCRC16.getSlot("foo{bar}{zap}"),
JedisClusterCRC16.getSlot("bar"));
} }
@Test @Test
public void testClusterForgetNode() throws InterruptedException { public void testClusterForgetNode() throws InterruptedException {
// at first, join node4 to cluster // at first, join node4 to cluster
node1.clusterMeet("127.0.0.1", nodeInfo4.getPort()); node1.clusterMeet("127.0.0.1", nodeInfo4.getPort());
String node7Id = JedisClusterTestUtil.getNodeId(node4.clusterNodes()); String node7Id = JedisClusterTestUtil.getNodeId(node4.clusterNodes());
JedisClusterTestUtil.assertNodeIsKnown(node3, node7Id, 1000); JedisClusterTestUtil.assertNodeIsKnown(node3, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsKnown(node2, node7Id, 1000); JedisClusterTestUtil.assertNodeIsKnown(node2, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsKnown(node1, node7Id, 1000); JedisClusterTestUtil.assertNodeIsKnown(node1, node7Id, 1000);
assertNodeHandshakeEnded(node3, 1000); assertNodeHandshakeEnded(node3, 1000);
assertNodeHandshakeEnded(node2, 1000); assertNodeHandshakeEnded(node2, 1000);
assertNodeHandshakeEnded(node1, 1000); assertNodeHandshakeEnded(node1, 1000);
assertEquals(4, node1.clusterNodes().split("\n").length); assertEquals(4, node1.clusterNodes().split("\n").length);
assertEquals(4, node2.clusterNodes().split("\n").length); assertEquals(4, node2.clusterNodes().split("\n").length);
assertEquals(4, node3.clusterNodes().split("\n").length); assertEquals(4, node3.clusterNodes().split("\n").length);
// do cluster forget // do cluster forget
node1.clusterForget(node7Id); node1.clusterForget(node7Id);
node2.clusterForget(node7Id); node2.clusterForget(node7Id);
node3.clusterForget(node7Id); node3.clusterForget(node7Id);
JedisClusterTestUtil.assertNodeIsUnknown(node1, node7Id, 1000); JedisClusterTestUtil.assertNodeIsUnknown(node1, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsUnknown(node2, node7Id, 1000); JedisClusterTestUtil.assertNodeIsUnknown(node2, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsUnknown(node3, node7Id, 1000); JedisClusterTestUtil.assertNodeIsUnknown(node3, node7Id, 1000);
assertEquals(3, node1.clusterNodes().split("\n").length); assertEquals(3, node1.clusterNodes().split("\n").length);
assertEquals(3, node2.clusterNodes().split("\n").length); assertEquals(3, node2.clusterNodes().split("\n").length);
assertEquals(3, node3.clusterNodes().split("\n").length); assertEquals(3, node3.clusterNodes().split("\n").length);
} }
@Test @Test
public void testClusterFlushSlots() { public void testClusterFlushSlots() {
String slotRange = getNodeServingSlotRange(node1.clusterNodes()); String slotRange = getNodeServingSlotRange(node1.clusterNodes());
assertNotNull(slotRange); assertNotNull(slotRange);
try { try {
node1.clusterFlushSlots(); node1.clusterFlushSlots();
assertNull(getNodeServingSlotRange(node1.clusterNodes())); assertNull(getNodeServingSlotRange(node1.clusterNodes()));
@@ -365,73 +376,81 @@ public class JedisClusterTest extends Assert {
String[] rangeInfo = slotRange.split("-"); String[] rangeInfo = slotRange.split("-");
int lower = Integer.parseInt(rangeInfo[0]); int lower = Integer.parseInt(rangeInfo[0]);
int upper = Integer.parseInt(rangeInfo[1]); int upper = Integer.parseInt(rangeInfo[1]);
int[] node1Slots = new int[upper - lower + 1]; int[] node1Slots = new int[upper - lower + 1];
for (int i = 0 ; lower <= upper ; ) { for (int i = 0; lower <= upper;) {
node1Slots[i++] = lower++; node1Slots[i++] = lower++;
} }
node1.clusterAddSlots(node1Slots); node1.clusterAddSlots(node1Slots);
} }
} }
@Test @Test
public void testClusterKeySlot() { public void testClusterKeySlot() {
// It assumes JedisClusterCRC16 is correctly implemented // It assumes JedisClusterCRC16 is correctly implemented
assertEquals(node1.clusterKeySlot("foo{bar}zap}").intValue(), JedisClusterCRC16.getSlot("foo{bar}zap")); assertEquals(node1.clusterKeySlot("foo{bar}zap}").intValue(),
assertEquals(node1.clusterKeySlot("{user1000}.following").intValue(), JedisClusterCRC16.getSlot("{user1000}.following")); JedisClusterCRC16.getSlot("foo{bar}zap"));
assertEquals(node1.clusterKeySlot("{user1000}.following").intValue(),
JedisClusterCRC16.getSlot("{user1000}.following"));
} }
@Test @Test
public void testClusterCountKeysInSlot() { public void testClusterCountKeysInSlot() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort())); jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1
.getPort()));
JedisCluster jc = new JedisCluster(jedisClusterNode); JedisCluster jc = new JedisCluster(jedisClusterNode);
for (int index = 0 ; index < 5 ; index++) { for (int index = 0; index < 5; index++) {
jc.set("foo{bar}" + index, "hello"); jc.set("foo{bar}" + index, "hello");
} }
int slot = JedisClusterCRC16.getSlot("foo{bar}"); int slot = JedisClusterCRC16.getSlot("foo{bar}");
assertEquals(5, node1.clusterCountKeysInSlot(slot).intValue()); assertEquals(5, node1.clusterCountKeysInSlot(slot).intValue());
} }
@Test @Test
public void testStableSlotWhenMigratingNodeOrImportingNodeIsNotSpecified() throws InterruptedException { public void testStableSlotWhenMigratingNodeOrImportingNodeIsNotSpecified()
throws InterruptedException {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort())); jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1
.getPort()));
JedisCluster jc = new JedisCluster(jedisClusterNode); JedisCluster jc = new JedisCluster(jedisClusterNode);
int slot51 = JedisClusterCRC16.getSlot("51"); int slot51 = JedisClusterCRC16.getSlot("51");
jc.set("51", "foo"); jc.set("51", "foo");
// node2 is responsible of taking care of slot51 (7186) // node2 is responsible of taking care of slot51 (7186)
node3.clusterSetSlotImporting(slot51, JedisClusterTestUtil.getNodeId(node2.clusterNodes())); node3.clusterSetSlotImporting(slot51,
JedisClusterTestUtil.getNodeId(node2.clusterNodes()));
assertEquals("foo", jc.get("51")); assertEquals("foo", jc.get("51"));
node3.clusterSetSlotStable(slot51); node3.clusterSetSlotStable(slot51);
assertEquals("foo", jc.get("51")); assertEquals("foo", jc.get("51"));
node2.clusterSetSlotMigrating(slot51, JedisClusterTestUtil.getNodeId(node3.clusterNodes())); node2.clusterSetSlotMigrating(slot51,
//assertEquals("foo", jc.get("51")); // it leads Max Redirections JedisClusterTestUtil.getNodeId(node3.clusterNodes()));
// assertEquals("foo", jc.get("51")); // it leads Max Redirections
node2.clusterSetSlotStable(slot51); node2.clusterSetSlotStable(slot51);
assertEquals("foo", jc.get("51")); assertEquals("foo", jc.get("51"));
} }
@Test(expected = JedisConnectionException.class) @Test(expected = JedisConnectionException.class)
public void testIfPoolConfigAppliesToClusterPools() { public void testIfPoolConfigAppliesToClusterPools() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig(); GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(0); config.setMaxTotal(0);
config.setMaxWaitMillis(2000); config.setMaxWaitMillis(2000);
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode, config); JedisCluster jc = new JedisCluster(jedisClusterNode, config);
jc.set("52", "poolTestValue"); jc.set("52", "poolTestValue");
} }
@Test @Test
public void testCloseable() { public void testCloseable() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort())); jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1
.getPort()));
JedisCluster jc = null; JedisCluster jc = null;
try { try {
jc = new JedisCluster(jedisClusterNode); jc = new JedisCluster(jedisClusterNode);
@@ -442,7 +461,8 @@ public class JedisClusterTest extends Assert {
} }
} }
Iterator<JedisPool> poolIterator = jc.getClusterNodes().values().iterator(); Iterator<JedisPool> poolIterator = jc.getClusterNodes().values()
.iterator();
while (poolIterator.hasNext()) { while (poolIterator.hasNext()) {
JedisPool pool = poolIterator.next(); JedisPool pool = poolIterator.next();
try { try {
@@ -453,21 +473,24 @@ public class JedisClusterTest extends Assert {
} }
} }
} }
@Test @Test
public void testJedisClusterRunsWithMultithreaded() throws InterruptedException, ExecutionException { public void testJedisClusterRunsWithMultithreaded()
throws InterruptedException, ExecutionException {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
final JedisCluster jc = new JedisCluster(jedisClusterNode); final JedisCluster jc = new JedisCluster(jedisClusterNode);
jc.set("foo", "bar"); jc.set("foo", "bar");
ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 100, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10)); ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 100, 0,
TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));
List<Future<String>> futures = new ArrayList<Future<String>>(); List<Future<String>> futures = new ArrayList<Future<String>>();
for (int i = 0 ; i < 50 ; i++) { for (int i = 0; i < 50; i++) {
executor.submit(new Callable<String>() { executor.submit(new Callable<String>() {
@Override @Override
public String call() throws Exception { public String call() throws Exception {
// FIXME : invalidate slot cache from JedisCluster to test random connection also does work // FIXME : invalidate slot cache from JedisCluster to test
// random connection also does work
return jc.get("foo"); return jc.get("foo");
} }
}); });
@@ -477,12 +500,13 @@ public class JedisClusterTest extends Assert {
String value = future.get(); String value = future.get();
assertEquals("bar", value); assertEquals("bar", value);
} }
jc.close(); jc.close();
} }
private static String getNodeServingSlotRange(String infoOutput) { private static String getNodeServingSlotRange(String infoOutput) {
// f4f3dc4befda352a4e0beccf29f5e8828438705d 127.0.0.1:7380 master - 0 1394372400827 0 connected 5461-10922 // f4f3dc4befda352a4e0beccf29f5e8828438705d 127.0.0.1:7380 master - 0
// 1394372400827 0 connected 5461-10922
for (String infoLine : infoOutput.split("\n")) { for (String infoLine : infoOutput.split("\n")) {
if (infoLine.contains("myself")) { if (infoLine.contains("myself")) {
try { try {
@@ -494,23 +518,23 @@ public class JedisClusterTest extends Assert {
} }
return null; return null;
} }
private void assertNodeHandshakeEnded(Jedis node, int timeoutMs) { private void assertNodeHandshakeEnded(Jedis node, int timeoutMs) {
int sleepInterval = 100; int sleepInterval = 100;
for (int sleepTime = 0 ; sleepTime <= timeoutMs ; sleepTime += sleepInterval) { for (int sleepTime = 0; sleepTime <= timeoutMs; sleepTime += sleepInterval) {
boolean isHandshaking = isAnyNodeHandshaking(node); boolean isHandshaking = isAnyNodeHandshaking(node);
if (!isHandshaking) if (!isHandshaking)
return; return;
try { try {
Thread.sleep(sleepInterval); Thread.sleep(sleepInterval);
} catch (InterruptedException e) { } catch (InterruptedException e) {
} }
} }
throw new JedisException("Node handshaking is not ended"); throw new JedisException("Node handshaking is not ended");
} }
private boolean isAnyNodeHandshaking(Jedis node) { private boolean isAnyNodeHandshaking(Jedis node) {
String infoOutput = node.clusterNodes(); String infoOutput = node.clusterNodes();
for (String infoLine : infoOutput.split("\n")) { for (String infoLine : infoOutput.split("\n")) {

View File

@@ -33,7 +33,7 @@ public class JedisPoolTest extends Assert {
@Test @Test
public void checkCloseableConnections() throws Exception { public void checkCloseableConnections() throws Exception {
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000); hnp.getPort(), 2000);
Jedis jedis = pool.getResource(); Jedis jedis = pool.getResource();
jedis.auth("foobared"); jedis.auth("foobared");
jedis.set("foo", "bar"); jedis.set("foo", "bar");
@@ -270,37 +270,37 @@ public class JedisPoolTest extends Assert {
@Test @Test
public void getNumActiveIsNegativeWhenPoolIsClosed() { public void getNumActiveIsNegativeWhenPoolIsClosed() {
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000, "foobared", 0, "my_shiny_client_name"); hnp.getPort(), 2000, "foobared", 0, "my_shiny_client_name");
pool.destroy(); pool.destroy();
assertTrue(pool.getNumActive() < 0); assertTrue(pool.getNumActive() < 0);
} }
@Test @Test
public void getNumActiveReturnsTheCorrectNumber() { public void getNumActiveReturnsTheCorrectNumber() {
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000); hnp.getPort(), 2000);
Jedis jedis = pool.getResource(); Jedis jedis = pool.getResource();
jedis.auth("foobared"); jedis.auth("foobared");
jedis.set("foo", "bar"); jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo")); assertEquals("bar", jedis.get("foo"));
assertEquals(1, pool.getNumActive()); assertEquals(1, pool.getNumActive());
Jedis jedis2 = pool.getResource(); Jedis jedis2 = pool.getResource();
jedis.auth("foobared"); jedis.auth("foobared");
jedis.set("foo", "bar"); jedis.set("foo", "bar");
assertEquals(2, pool.getNumActive()); assertEquals(2, pool.getNumActive());
pool.returnResource(jedis); pool.returnResource(jedis);
assertEquals(1, pool.getNumActive()); assertEquals(1, pool.getNumActive());
pool.returnResource(jedis2); pool.returnResource(jedis2);
assertEquals(0, pool.getNumActive()); assertEquals(0, pool.getNumActive());
pool.destroy(); pool.destroy();
} }
} }

View File

@@ -2,7 +2,6 @@ package redis.clients.jedis.tests;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.junit.Before; import org.junit.Before;
@@ -27,7 +26,7 @@ public class JedisSentinelPoolTest extends JedisTestBase {
protected static HostAndPort sentinel1 = HostAndPortUtil protected static HostAndPort sentinel1 = HostAndPortUtil
.getSentinelServers().get(1); .getSentinelServers().get(1);
protected static HostAndPort sentinel2 = HostAndPortUtil protected static HostAndPort sentinel2 = HostAndPortUtil
.getSentinelServers().get(3); .getSentinelServers().get(3);
protected static Jedis sentinelJedis1; protected static Jedis sentinelJedis1;
protected static Jedis sentinelJedis2; protected static Jedis sentinelJedis2;
@@ -42,31 +41,32 @@ public class JedisSentinelPoolTest extends JedisTestBase {
sentinelJedis1 = new Jedis(sentinel1.getHost(), sentinel1.getPort()); sentinelJedis1 = new Jedis(sentinel1.getHost(), sentinel1.getPort());
sentinelJedis2 = new Jedis(sentinel2.getHost(), sentinel2.getPort()); sentinelJedis2 = new Jedis(sentinel2.getHost(), sentinel2.getPort());
} }
@Test(expected=JedisConnectionException.class) @Test(expected = JedisConnectionException.class)
public void initializeWithNotAvailableSentinelsShouldThrowException() { public void initializeWithNotAvailableSentinelsShouldThrowException() {
Set<String> wrongSentinels = new HashSet<String>(); Set<String> wrongSentinels = new HashSet<String>();
wrongSentinels.add(new HostAndPort("localhost", 65432).toString()); wrongSentinels.add(new HostAndPort("localhost", 65432).toString());
wrongSentinels.add(new HostAndPort("localhost", 65431).toString()); wrongSentinels.add(new HostAndPort("localhost", 65431).toString());
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, wrongSentinels); JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME,
wrongSentinels);
pool.destroy(); pool.destroy();
} }
@Test(expected=JedisException.class) @Test(expected = JedisException.class)
public void initializeWithNotMonitoredMasterNameShouldThrowException() { public void initializeWithNotMonitoredMasterNameShouldThrowException() {
final String wrongMasterName = "wrongMasterName"; final String wrongMasterName = "wrongMasterName";
JedisSentinelPool pool = new JedisSentinelPool(wrongMasterName, JedisSentinelPool pool = new JedisSentinelPool(wrongMasterName,
sentinels); sentinels);
pool.destroy(); pool.destroy();
} }
@Test @Test
public void checkCloseableConnections() throws Exception { public void checkCloseableConnections() throws Exception {
GenericObjectPoolConfig config = new GenericObjectPoolConfig(); GenericObjectPoolConfig config = new GenericObjectPoolConfig();
JedisSentinelPool pool = new JedisSentinelPool( JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
MASTER_NAME, sentinels, config, 1000, "foobared", 2); config, 1000, "foobared", 2);
Jedis jedis = pool.getResource(); Jedis jedis = pool.getResource();
jedis.auth("foobared"); jedis.auth("foobared");
jedis.set("foo", "bar"); jedis.set("foo", "bar");
@@ -82,13 +82,14 @@ public class JedisSentinelPoolTest extends JedisTestBase {
new GenericObjectPoolConfig(), 1000, "foobared", 2); new GenericObjectPoolConfig(), 1000, "foobared", 2);
forceFailover(pool); forceFailover(pool);
// after failover sentinel needs a bit of time to stabilize before a new failover // after failover sentinel needs a bit of time to stabilize before a new
// failover
Thread.sleep(100); Thread.sleep(100);
forceFailover(pool); forceFailover(pool);
// you can test failover as much as possible // you can test failover as much as possible
} }
@Test @Test
public void returnResourceShouldResetState() { public void returnResourceShouldResetState() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig(); GenericObjectPoolConfig config = new GenericObjectPoolConfig();
@@ -99,13 +100,13 @@ public class JedisSentinelPoolTest extends JedisTestBase {
Jedis jedis = pool.getResource(); Jedis jedis = pool.getResource();
Jedis jedis2 = null; Jedis jedis2 = null;
try { try {
jedis.set("hello", "jedis"); jedis.set("hello", "jedis");
Transaction t = jedis.multi(); Transaction t = jedis.multi();
t.set("hello", "world"); t.set("hello", "world");
pool.returnResource(jedis); pool.returnResource(jedis);
jedis2 = pool.getResource(); jedis2 = pool.getResource();
assertTrue(jedis == jedis2); assertTrue(jedis == jedis2);
@@ -118,11 +119,11 @@ public class JedisSentinelPoolTest extends JedisTestBase {
} finally { } finally {
if (jedis2 != null) if (jedis2 != null)
pool.returnResource(jedis2); pool.returnResource(jedis2);
pool.destroy(); pool.destroy();
} }
} }
@Test @Test
public void checkResourceIsCloseable() { public void checkResourceIsCloseable() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig(); GenericObjectPoolConfig config = new GenericObjectPoolConfig();
@@ -184,9 +185,10 @@ public class JedisSentinelPoolTest extends JedisTestBase {
Jedis afterFailoverJedis = pool.getResource(); Jedis afterFailoverJedis = pool.getResource();
assertEquals("PONG", afterFailoverJedis.ping()); assertEquals("PONG", afterFailoverJedis.ping());
assertEquals("foobared", afterFailoverJedis.configGet("requirepass").get(1)); assertEquals("foobared", afterFailoverJedis.configGet("requirepass")
.get(1));
assertEquals(2, afterFailoverJedis.getDB().intValue()); assertEquals(2, afterFailoverJedis.getDB().intValue());
// returning both connections to the pool should not throw // returning both connections to the pool should not throw
beforeFailoverJedis.close(); beforeFailoverJedis.close();
afterFailoverJedis.close(); afterFailoverJedis.close();
@@ -194,8 +196,8 @@ public class JedisSentinelPoolTest extends JedisTestBase {
private void waitForFailover(JedisSentinelPool pool, HostAndPort oldMaster) private void waitForFailover(JedisSentinelPool pool, HostAndPort oldMaster)
throws InterruptedException { throws InterruptedException {
HostAndPort newMaster = JedisSentinelTestUtil HostAndPort newMaster = JedisSentinelTestUtil.waitForNewPromotedMaster(
.waitForNewPromotedMaster(MASTER_NAME, sentinelJedis1, sentinelJedis2); MASTER_NAME, sentinelJedis1, sentinelJedis2);
waitForJedisSentinelPoolRecognizeNewMaster(pool, newMaster); waitForJedisSentinelPoolRecognizeNewMaster(pool, newMaster);
} }
@@ -216,5 +218,5 @@ public class JedisSentinelPoolTest extends JedisTestBase {
Thread.sleep(100); Thread.sleep(100);
} }
} }
} }

View File

@@ -22,8 +22,8 @@ public class JedisSentinelTest extends JedisTestBase {
protected static HostAndPort master = HostAndPortUtil.getRedisServers() protected static HostAndPort master = HostAndPortUtil.getRedisServers()
.get(0); .get(0);
protected static HostAndPort slave = HostAndPortUtil.getRedisServers() protected static HostAndPort slave = HostAndPortUtil.getRedisServers().get(
.get(4); 4);
protected static HostAndPort sentinel = HostAndPortUtil protected static HostAndPort sentinel = HostAndPortUtil
.getSentinelServers().get(0); .getSentinelServers().get(0);
@@ -86,15 +86,17 @@ public class JedisSentinelTest extends JedisTestBase {
Jedis j = new Jedis(sentinelForFailover.getHost(), Jedis j = new Jedis(sentinelForFailover.getHost(),
sentinelForFailover.getPort()); sentinelForFailover.getPort());
Jedis j2 = new Jedis(sentinelForFailover.getHost(), Jedis j2 = new Jedis(sentinelForFailover.getHost(),
sentinelForFailover.getPort()); sentinelForFailover.getPort());
try { try {
List<String> masterHostAndPort = j List<String> masterHostAndPort = j
.sentinelGetMasterAddrByName(FAILOVER_MASTER_NAME); .sentinelGetMasterAddrByName(FAILOVER_MASTER_NAME);
HostAndPort currentMaster = new HostAndPort(masterHostAndPort.get(0), HostAndPort currentMaster = new HostAndPort(
masterHostAndPort.get(0),
Integer.parseInt(masterHostAndPort.get(1))); Integer.parseInt(masterHostAndPort.get(1)));
JedisSentinelTestUtil.waitForNewPromotedMaster(FAILOVER_MASTER_NAME, j, j2); JedisSentinelTestUtil.waitForNewPromotedMaster(
FAILOVER_MASTER_NAME, j, j2);
masterHostAndPort = j masterHostAndPort = j
.sentinelGetMasterAddrByName(FAILOVER_MASTER_NAME); .sentinelGetMasterAddrByName(FAILOVER_MASTER_NAME);
@@ -204,5 +206,5 @@ public class JedisSentinelTest extends JedisTestBase {
j.close(); j.close();
} }
} }
} }

View File

@@ -108,7 +108,7 @@ public class JedisTest extends JedisCommandTestBase {
assertEquals(jedis.getClient().getHost(), "localhost"); assertEquals(jedis.getClient().getHost(), "localhost");
assertEquals(jedis.getClient().getPort(), 6380); assertEquals(jedis.getClient().getPort(), 6380);
assertEquals(jedis.getDB(), (Long) 0L); assertEquals(jedis.getDB(), (Long) 0L);
jedis = new Jedis("redis://localhost:6380/"); jedis = new Jedis("redis://localhost:6380/");
jedis.auth("foobared"); jedis.auth("foobared");
assertEquals(jedis.getClient().getHost(), "localhost"); assertEquals(jedis.getClient().getHost(), "localhost");

View File

@@ -1,13 +1,24 @@
package redis.clients.jedis.tests; package redis.clients.jedis.tests;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import redis.clients.jedis.*;
import redis.clients.jedis.exceptions.JedisDataException;
import java.io.UnsupportedEncodingException; import redis.clients.jedis.HostAndPort;
import java.util.*; import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;
import redis.clients.jedis.Tuple;
import redis.clients.jedis.exceptions.JedisDataException;
public class PipeliningTest extends Assert { public class PipeliningTest extends Assert {
private static HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); private static HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0);
@@ -42,9 +53,9 @@ public class PipeliningTest extends Assert {
jedis.hset("hash", "foo", "bar"); jedis.hset("hash", "foo", "bar");
jedis.zadd("zset", 1, "foo"); jedis.zadd("zset", 1, "foo");
jedis.sadd("set", "foo"); jedis.sadd("set", "foo");
jedis.setrange("setrange", 0, "0123456789"); jedis.setrange("setrange", 0, "0123456789");
byte[] bytesForSetRange = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; byte[] bytesForSetRange = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
jedis.setrange("setrangebytes".getBytes(), 0, bytesForSetRange); jedis.setrange("setrangebytes".getBytes(), 0, bytesForSetRange);
Pipeline p = jedis.pipelined(); Pipeline p = jedis.pipelined();
Response<String> string = p.get("string"); Response<String> string = p.get("string");
@@ -61,10 +72,11 @@ public class PipeliningTest extends Assert {
p.sadd("set", "foo"); p.sadd("set", "foo");
Response<Set<String>> smembers = p.smembers("set"); Response<Set<String>> smembers = p.smembers("set");
Response<Set<Tuple>> zrangeWithScores = p.zrangeWithScores("zset", 0, Response<Set<Tuple>> zrangeWithScores = p.zrangeWithScores("zset", 0,
-1); -1);
Response<String> getrange = p.getrange("setrange", 1, 3); Response<String> getrange = p.getrange("setrange", 1, 3);
Response<byte[]> getrangeBytes = p.getrange("setrangebytes".getBytes(), 6, 8); Response<byte[]> getrangeBytes = p.getrange("setrangebytes".getBytes(),
p.sync(); 6, 8);
p.sync();
assertEquals("foo", string.get()); assertEquals("foo", string.get());
assertEquals("foo", list.get()); assertEquals("foo", list.get());
@@ -78,9 +90,9 @@ public class PipeliningTest extends Assert {
assertNotNull(hgetAll.get().get("foo")); assertNotNull(hgetAll.get().get("foo"));
assertEquals(1, smembers.get().size()); assertEquals(1, smembers.get().size());
assertEquals(1, zrangeWithScores.get().size()); assertEquals(1, zrangeWithScores.get().size());
assertEquals("123", getrange.get()); assertEquals("123", getrange.get());
byte[] expectedGetRangeBytes = {6, 7, 8}; byte[] expectedGetRangeBytes = { 6, 7, 8 };
assertArrayEquals(expectedGetRangeBytes, getrangeBytes.get()); assertArrayEquals(expectedGetRangeBytes, getrangeBytes.get());
} }
@Test @Test
@@ -261,7 +273,7 @@ public class PipeliningTest extends Assert {
p.exec(); p.exec();
Response<String> r3 = p.get("hello"); Response<String> r3 = p.get("hello");
p.sync(); p.sync();
// before multi // before multi
assertEquals("foo", r1.get()); assertEquals("foo", r1.get());
// It should be readable whether exec's response was built or not // It should be readable whether exec's response was built or not
@@ -375,75 +387,74 @@ public class PipeliningTest extends Assert {
@Test @Test
public void testPipelinedTransactionResponse() { public void testPipelinedTransactionResponse() {
String key1 = "key1"; String key1 = "key1";
String val1 = "val1"; String val1 = "val1";
String key2 = "key2"; String key2 = "key2";
String val2 = "val2"; String val2 = "val2";
String key3 = "key3"; String key3 = "key3";
String field1 = "field1"; String field1 = "field1";
String field2 = "field2"; String field2 = "field2";
String field3 = "field3"; String field3 = "field3";
String field4 = "field4"; String field4 = "field4";
String value1 = "value1"; String value1 = "value1";
String value2 = "value2"; String value2 = "value2";
String value3 = "value3"; String value3 = "value3";
String value4 = "value4"; String value4 = "value4";
Map<String, String> hashMap = new HashMap<String, String>(); Map<String, String> hashMap = new HashMap<String, String>();
hashMap.put(field1, value1); hashMap.put(field1, value1);
hashMap.put(field2, value2); hashMap.put(field2, value2);
String key4 = "key4"; String key4 = "key4";
Map<String, String> hashMap1 = new HashMap<String, String>(); Map<String, String> hashMap1 = new HashMap<String, String>();
hashMap1.put(field3, value3); hashMap1.put(field3, value3);
hashMap1.put(field4, value4); hashMap1.put(field4, value4);
jedis.set(key1, val1);
jedis.set(key2, val2);
jedis.hmset(key3, hashMap);
jedis.hmset(key4, hashMap1);
jedis.set(key1, val1); Pipeline pipeline = jedis.pipelined();
jedis.set(key2, val2); pipeline.multi();
jedis.hmset(key3, hashMap);
jedis.hmset(key4, hashMap1);
Pipeline pipeline = jedis.pipelined(); pipeline.get(key1);
pipeline.multi(); pipeline.hgetAll(key2);
pipeline.hgetAll(key3);
pipeline.get(key4);
pipeline.get(key1); Response<List<Object>> response = pipeline.exec();
pipeline.hgetAll(key2); pipeline.sync();
pipeline.hgetAll(key3);
pipeline.get(key4);
Response<List<Object> > response = pipeline.exec(); List<Object> result = response.get();
pipeline.sync();
List<Object> result = response.get(); assertEquals(4, result.size());
assertEquals(4, result.size()); assertEquals("val1", result.get(0));
assertEquals("val1", result.get(0)); assertTrue(result.get(1) instanceof JedisDataException);
assertTrue(result.get(1) instanceof JedisDataException); Map<String, String> hashMapReceived = (Map<String, String>) result
.get(2);
Iterator<String> iterator = hashMapReceived.keySet().iterator();
String mapKey1 = iterator.next();
String mapKey2 = iterator.next();
assertFalse(iterator.hasNext());
verifyHasBothValues(mapKey1, mapKey2, field1, field2);
String mapValue1 = hashMapReceived.get(mapKey1);
String mapValue2 = hashMapReceived.get(mapKey2);
verifyHasBothValues(mapValue1, mapValue2, value1, value2);
Map<String, String> hashMapReceived = (Map<String, String>)result.get(2); assertTrue(result.get(3) instanceof JedisDataException);
Iterator<String> iterator = hashMapReceived.keySet().iterator();
String mapKey1 = iterator.next();
String mapKey2 = iterator.next();
assertFalse(iterator.hasNext());
verifyHasBothValues(mapKey1, mapKey2, field1, field2);
String mapValue1 = hashMapReceived.get(mapKey1);
String mapValue2 = hashMapReceived.get(mapKey2);
verifyHasBothValues(mapValue1, mapValue2, value1, value2);
assertTrue(result.get(3) instanceof JedisDataException);
} }
private void verifyHasBothValues(String firstKey, String secondKey, String value1, String value2) { private void verifyHasBothValues(String firstKey, String secondKey,
assertFalse(firstKey.equals(secondKey)); String value1, String value2) {
assertTrue(firstKey.equals(value1) assertFalse(firstKey.equals(secondKey));
|| firstKey.equals(value2)); assertTrue(firstKey.equals(value1) || firstKey.equals(value2));
assertTrue(secondKey.equals(value1) assertTrue(secondKey.equals(value1) || secondKey.equals(value2));
|| secondKey.equals(value2));
} }
} }

View File

@@ -39,26 +39,26 @@ public class ProtocolTest extends JedisTestBase {
assertEquals(expectedCommand, sb.toString()); assertEquals(expectedCommand, sb.toString());
} }
@Test(expected=IOException.class) @Test(expected = IOException.class)
public void writeOverflow() throws IOException { public void writeOverflow() throws IOException {
RedisOutputStream ros = new RedisOutputStream(new OutputStream() { RedisOutputStream ros = new RedisOutputStream(new OutputStream() {
@Override @Override
public void write(int b) throws IOException { public void write(int b) throws IOException {
throw new IOException("thrown exception"); throw new IOException("thrown exception");
} }
}); });
ros.write(new byte[8191]); ros.write(new byte[8191]);
try { try {
ros.write((byte)'*'); ros.write((byte) '*');
} catch (IOException ioe) {} } catch (IOException ioe) {
}
ros.write((byte)'*'); ros.write((byte) '*');
} }

View File

@@ -7,10 +7,9 @@ import redis.clients.util.JedisClusterCRC16;
public class CRC16Benchmark { public class CRC16Benchmark {
private static final int TOTAL_OPERATIONS = 100000000; private static final int TOTAL_OPERATIONS = 100000000;
private static String[] TEST_SET = { private static String[] TEST_SET = { "", "123456789", "sfger132515",
"", "123456789", "sfger132515", "hae9Napahngaikeethievubaibogiech", "hae9Napahngaikeethievubaibogiech", "AAAAAAAAAAAAAAAAAAAAAA",
"AAAAAAAAAAAAAAAAAAAAAA", "Hello, World!" "Hello, World!" };
};
public static void main(String[] args) { public static void main(String[] args) {
long begin = Calendar.getInstance().getTimeInMillis(); long begin = Calendar.getInstance().getTimeInMillis();

View File

@@ -1,5 +1,8 @@
package redis.clients.jedis.tests.commands; package redis.clients.jedis.tests.commands;
import static redis.clients.jedis.ScanParams.SCAN_POINTER_START;
import static redis.clients.jedis.ScanParams.SCAN_POINTER_START_BINARY;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
@@ -10,8 +13,6 @@ import redis.clients.jedis.ScanParams;
import redis.clients.jedis.ScanResult; import redis.clients.jedis.ScanResult;
import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.exceptions.JedisDataException;
import redis.clients.util.SafeEncoder; import redis.clients.util.SafeEncoder;
import static redis.clients.jedis.ScanParams.SCAN_POINTER_START;
import static redis.clients.jedis.ScanParams.SCAN_POINTER_START_BINARY;
public class AllKindOfValuesCommandsTest extends JedisCommandTestBase { public class AllKindOfValuesCommandsTest extends JedisCommandTestBase {
final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 };
@@ -523,14 +524,14 @@ public class AllKindOfValuesCommandsTest extends JedisCommandTestBase {
assertEquals(SCAN_POINTER_START, result.getCursor()); assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty()); assertFalse(result.getResult().isEmpty());
// binary // binary
ScanResult<byte[]> bResult = jedis.scan(SCAN_POINTER_START_BINARY); ScanResult<byte[]> bResult = jedis.scan(SCAN_POINTER_START_BINARY);
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty()); assertFalse(bResult.getResult().isEmpty());
} }
@Test @Test
public void scanMatch() { public void scanMatch() {
ScanParams params = new ScanParams(); ScanParams params = new ScanParams();
@@ -543,7 +544,7 @@ public class AllKindOfValuesCommandsTest extends JedisCommandTestBase {
assertEquals(SCAN_POINTER_START, result.getCursor()); assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty()); assertFalse(result.getResult().isEmpty());
// binary // binary
params = new ScanParams(); params = new ScanParams();
params.match(bfoostar); params.match(bfoostar);
@@ -551,9 +552,10 @@ public class AllKindOfValuesCommandsTest extends JedisCommandTestBase {
jedis.set(bfoo1, bbar); jedis.set(bfoo1, bbar);
jedis.set(bfoo2, bbar); jedis.set(bfoo2, bbar);
jedis.set(bfoo3, bbar); jedis.set(bfoo3, bbar);
ScanResult<byte[]> bResult = jedis.scan(SCAN_POINTER_START_BINARY, params); ScanResult<byte[]> bResult = jedis.scan(SCAN_POINTER_START_BINARY,
params);
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty()); assertFalse(bResult.getResult().isEmpty());
} }
@@ -570,7 +572,7 @@ public class AllKindOfValuesCommandsTest extends JedisCommandTestBase {
ScanResult<String> result = jedis.scan(SCAN_POINTER_START, params); ScanResult<String> result = jedis.scan(SCAN_POINTER_START, params);
assertFalse(result.getResult().isEmpty()); assertFalse(result.getResult().isEmpty());
// binary // binary
params = new ScanParams(); params = new ScanParams();
params.count(2); params.count(2);
@@ -578,9 +580,10 @@ public class AllKindOfValuesCommandsTest extends JedisCommandTestBase {
jedis.set(bfoo1, bbar); jedis.set(bfoo1, bbar);
jedis.set(bfoo2, bbar); jedis.set(bfoo2, bbar);
jedis.set(bfoo3, bbar); jedis.set(bfoo3, bbar);
ScanResult<byte[]> bResult = jedis.scan(SCAN_POINTER_START_BINARY, params); ScanResult<byte[]> bResult = jedis.scan(SCAN_POINTER_START_BINARY,
params);
assertFalse(bResult.getResult().isEmpty()); assertFalse(bResult.getResult().isEmpty());
} }
} }

View File

@@ -32,10 +32,10 @@ public class BitCommandsTest extends JedisCommandTestBase {
jedis.setbit(foo, 7, true); jedis.setbit(foo, 7, true);
jedis.setbit(foo, 13, true); jedis.setbit(foo, 13, true);
jedis.setbit(foo, 39, true); jedis.setbit(foo, 39, true);
/* /*
* byte: 0 1 2 3 4 * byte: 0 1 2 3 4 bit: 00010001 / 00000100 / 00000000 / 00000000 /
* bit: 00010001 / 00000100 / 00000000 / 00000000 / 00000001 * 00000001
*/ */
long offset = jedis.bitpos(foo, true); long offset = jedis.bitpos(foo, true);
assertEquals(2, offset); assertEquals(2, offset);
@@ -69,8 +69,8 @@ public class BitCommandsTest extends JedisCommandTestBase {
jedis.setbit(bfoo, 39, true); jedis.setbit(bfoo, 39, true);
/* /*
* byte: 0 1 2 3 4 * byte: 0 1 2 3 4 bit: 00010001 / 00000100 / 00000000 / 00000000 /
* bit: 00010001 / 00000100 / 00000000 / 00000000 / 00000001 * 00000001
*/ */
long offset = jedis.bitpos(bfoo, true); long offset = jedis.bitpos(bfoo, true);
assertEquals(2, offset); assertEquals(2, offset);
@@ -101,8 +101,7 @@ public class BitCommandsTest extends JedisCommandTestBase {
} }
/* /*
* byte: 0 * byte: 0 bit: 11111111
* bit: 11111111
*/ */
long offset = jedis.bitpos(foo, false); long offset = jedis.bitpos(foo, false);
// offset should be last index + 1 // offset should be last index + 1
@@ -119,8 +118,8 @@ public class BitCommandsTest extends JedisCommandTestBase {
} }
/* /*
* byte: 0 1 2 3 4 * byte: 0 1 2 3 4 bit: 11111111 / 11111111 / 11111111 / 11111111 /
* bit: 11111111 / 11111111 / 11111111 / 11111111 / 11111111 * 11111111
*/ */
long offset = jedis.bitpos(foo, false, new BitPosParams(2, 3)); long offset = jedis.bitpos(foo, false, new BitPosParams(2, 3));
// offset should be -1 // offset should be -1

View File

@@ -47,12 +47,12 @@ public class ClusterCommandsTest extends JedisTestBase {
@Test @Test
public void testClusterSoftReset() { public void testClusterSoftReset() {
node1.clusterMeet("127.0.0.1", nodeInfo2.getPort()); node1.clusterMeet("127.0.0.1", nodeInfo2.getPort());
assertTrue(node1.clusterNodes().split("\n").length > 1); assertTrue(node1.clusterNodes().split("\n").length > 1);
node1.clusterReset(Reset.SOFT); node1.clusterReset(Reset.SOFT);
assertEquals(1, node1.clusterNodes().split("\n").length); assertEquals(1, node1.clusterNodes().split("\n").length);
} }
@Test @Test
public void testClusterHardReset() { public void testClusterHardReset() {
String nodeId = JedisClusterTestUtil.getNodeId(node1.clusterNodes()); String nodeId = JedisClusterTestUtil.getNodeId(node1.clusterNodes());
@@ -60,7 +60,7 @@ public class ClusterCommandsTest extends JedisTestBase {
String newNodeId = JedisClusterTestUtil.getNodeId(node1.clusterNodes()); String newNodeId = JedisClusterTestUtil.getNodeId(node1.clusterNodes());
assertNotEquals(nodeId, newNodeId); assertNotEquals(nodeId, newNodeId);
} }
@Test @Test
public void clusterSetSlotImporting() { public void clusterSetSlotImporting() {
node2.clusterAddSlots(6000); node2.clusterAddSlots(6000);
@@ -124,7 +124,7 @@ public class ClusterCommandsTest extends JedisTestBase {
String status = node1.clusterSetSlotMigrating(5000, nodeId); String status = node1.clusterSetSlotMigrating(5000, nodeId);
assertEquals("OK", status); assertEquals("OK", status);
} }
@Test @Test
public void clusterSlots() { public void clusterSlots() {
// please see cluster slot output format from below commit // please see cluster slot output format from below commit

View File

@@ -1,5 +1,8 @@
package redis.clients.jedis.tests.commands; package redis.clients.jedis.tests.commands;
import static redis.clients.jedis.ScanParams.SCAN_POINTER_START;
import static redis.clients.jedis.ScanParams.SCAN_POINTER_START_BINARY;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
@@ -9,24 +12,22 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import org.junit.Test; import org.junit.Test;
import redis.clients.jedis.Pipeline; import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response; import redis.clients.jedis.Response;
import redis.clients.jedis.ScanParams; import redis.clients.jedis.ScanParams;
import redis.clients.jedis.ScanResult; import redis.clients.jedis.ScanResult;
import static redis.clients.jedis.ScanParams.SCAN_POINTER_START;
import static redis.clients.jedis.ScanParams.SCAN_POINTER_START_BINARY;
public class HashesCommandsTest extends JedisCommandTestBase { public class HashesCommandsTest extends JedisCommandTestBase {
final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 };
final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 };
final byte[] bcar = { 0x09, 0x0A, 0x0B, 0x0C }; final byte[] bcar = { 0x09, 0x0A, 0x0B, 0x0C };
final byte[] bbar1 = { 0x05, 0x06, 0x07, 0x08, 0x0A }; final byte[] bbar1 = { 0x05, 0x06, 0x07, 0x08, 0x0A };
final byte[] bbar2 = { 0x05, 0x06, 0x07, 0x08, 0x0B }; final byte[] bbar2 = { 0x05, 0x06, 0x07, 0x08, 0x0B };
final byte[] bbar3 = { 0x05, 0x06, 0x07, 0x08, 0x0C }; final byte[] bbar3 = { 0x05, 0x06, 0x07, 0x08, 0x0C };
final byte[] bbarstar = { 0x05, 0x06, 0x07, 0x08, '*' }; final byte[] bbarstar = { 0x05, 0x06, 0x07, 0x08, '*' };
@Test @Test
public void hset() { public void hset() {
long status = jedis.hset("foo", "bar", "car"); long status = jedis.hset("foo", "bar", "car");
@@ -157,20 +158,20 @@ public class HashesCommandsTest extends JedisCommandTestBase {
@Test @Test
public void hincrByFloat() { public void hincrByFloat() {
Double value = jedis.hincrByFloat("foo", "bar", 1.5d); Double value = jedis.hincrByFloat("foo", "bar", 1.5d);
assertEquals((Double) 1.5d, value); assertEquals((Double) 1.5d, value);
value = jedis.hincrByFloat("foo", "bar", -1.5d); value = jedis.hincrByFloat("foo", "bar", -1.5d);
assertEquals((Double) 0d, value); assertEquals((Double) 0d, value);
value = jedis.hincrByFloat("foo", "bar", -10.7d); value = jedis.hincrByFloat("foo", "bar", -10.7d);
assertEquals(Double.compare(-10.7d, value), 0); assertEquals(Double.compare(-10.7d, value), 0);
// Binary // Binary
double bvalue = jedis.hincrByFloat(bfoo, bbar, 1.5d); double bvalue = jedis.hincrByFloat(bfoo, bbar, 1.5d);
assertEquals(Double.compare(1.5d, bvalue), 0); assertEquals(Double.compare(1.5d, bvalue), 0);
bvalue = jedis.hincrByFloat(bfoo, bbar, -1.5d); bvalue = jedis.hincrByFloat(bfoo, bbar, -1.5d);
assertEquals(Double.compare(0d, bvalue), 0); assertEquals(Double.compare(0d, bvalue), 0);
bvalue = jedis.hincrByFloat(bfoo, bbar, -10.7d); bvalue = jedis.hincrByFloat(bfoo, bbar, -10.7d);
assertEquals(Double.compare(-10.7d, value), 0); assertEquals(Double.compare(-10.7d, value), 0);
} }
@@ -339,16 +340,18 @@ public class HashesCommandsTest extends JedisCommandTestBase {
jedis.hset("foo", "b", "b"); jedis.hset("foo", "b", "b");
jedis.hset("foo", "a", "a"); jedis.hset("foo", "a", "a");
ScanResult<Map.Entry<String, String>> result = jedis.hscan("foo", SCAN_POINTER_START); ScanResult<Map.Entry<String, String>> result = jedis.hscan("foo",
SCAN_POINTER_START);
assertEquals(SCAN_POINTER_START, result.getCursor()); assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty()); assertFalse(result.getResult().isEmpty());
// binary // binary
jedis.hset(bfoo, bbar, bcar); jedis.hset(bfoo, bbar, bcar);
ScanResult<Map.Entry<byte[], byte[]>> bResult = jedis.hscan(bfoo, SCAN_POINTER_START_BINARY); ScanResult<Map.Entry<byte[], byte[]>> bResult = jedis.hscan(bfoo,
SCAN_POINTER_START_BINARY);
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty()); assertFalse(bResult.getResult().isEmpty());
} }
@@ -361,23 +364,24 @@ public class HashesCommandsTest extends JedisCommandTestBase {
jedis.hset("foo", "b", "b"); jedis.hset("foo", "b", "b");
jedis.hset("foo", "a", "a"); jedis.hset("foo", "a", "a");
jedis.hset("foo", "aa", "aa"); jedis.hset("foo", "aa", "aa");
ScanResult<Map.Entry<String, String>> result = jedis.hscan("foo", ScanResult<Map.Entry<String, String>> result = jedis.hscan("foo",
SCAN_POINTER_START, params); SCAN_POINTER_START, params);
assertEquals(SCAN_POINTER_START, result.getCursor()); assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty()); assertFalse(result.getResult().isEmpty());
// binary // binary
params = new ScanParams(); params = new ScanParams();
params.match(bbarstar); params.match(bbarstar);
jedis.hset(bfoo, bbar, bcar); jedis.hset(bfoo, bbar, bcar);
jedis.hset(bfoo, bbar1, bcar); jedis.hset(bfoo, bbar1, bcar);
jedis.hset(bfoo, bbar2, bcar); jedis.hset(bfoo, bbar2, bcar);
jedis.hset(bfoo, bbar3, bcar); jedis.hset(bfoo, bbar3, bcar);
ScanResult<Map.Entry<byte[], byte[]>> bResult = jedis.hscan(bfoo, SCAN_POINTER_START_BINARY, params); ScanResult<Map.Entry<byte[], byte[]>> bResult = jedis.hscan(bfoo,
SCAN_POINTER_START_BINARY, params);
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty()); assertFalse(bResult.getResult().isEmpty());
} }
@@ -391,22 +395,23 @@ public class HashesCommandsTest extends JedisCommandTestBase {
jedis.hset("foo", "a" + i, "a" + i); jedis.hset("foo", "a" + i, "a" + i);
} }
ScanResult<Map.Entry<String, String>> result = jedis.hscan("foo", ScanResult<Map.Entry<String, String>> result = jedis.hscan("foo",
SCAN_POINTER_START, params); SCAN_POINTER_START, params);
assertFalse(result.getResult().isEmpty()); assertFalse(result.getResult().isEmpty());
// binary // binary
params = new ScanParams(); params = new ScanParams();
params.count(2); params.count(2);
jedis.hset(bfoo, bbar, bcar); jedis.hset(bfoo, bbar, bcar);
jedis.hset(bfoo, bbar1, bcar); jedis.hset(bfoo, bbar1, bcar);
jedis.hset(bfoo, bbar2, bcar); jedis.hset(bfoo, bbar2, bcar);
jedis.hset(bfoo, bbar3, bcar); jedis.hset(bfoo, bbar3, bcar);
ScanResult<Map.Entry<byte[], byte[]>> bResult = jedis.hscan(bfoo, SCAN_POINTER_START_BINARY, params); ScanResult<Map.Entry<byte[], byte[]>> bResult = jedis.hscan(bfoo,
SCAN_POINTER_START_BINARY, params);
assertFalse(bResult.getResult().isEmpty()); assertFalse(bResult.getResult().isEmpty());
} }
} }

View File

@@ -10,61 +10,60 @@ public class HyperLogLogCommandsTest extends JedisCommandTestBase {
public void pfadd() { public void pfadd() {
long status = jedis.pfadd("foo", "a"); long status = jedis.pfadd("foo", "a");
assertEquals(1, status); assertEquals(1, status);
status = jedis.pfadd("foo", "a"); status = jedis.pfadd("foo", "a");
assertEquals(0, status); assertEquals(0, status);
} }
@Test @Test
public void pfaddBinary() { public void pfaddBinary() {
byte[] bFoo = SafeEncoder.encode("foo"); byte[] bFoo = SafeEncoder.encode("foo");
byte[] bBar = SafeEncoder.encode("bar"); byte[] bBar = SafeEncoder.encode("bar");
byte[] bBar2 = SafeEncoder.encode("bar2"); byte[] bBar2 = SafeEncoder.encode("bar2");
long status = jedis.pfadd(bFoo, bBar, bBar2); long status = jedis.pfadd(bFoo, bBar, bBar2);
assertEquals(1, status); assertEquals(1, status);
status = jedis.pfadd(bFoo, bBar, bBar2); status = jedis.pfadd(bFoo, bBar, bBar2);
assertEquals(0, status); assertEquals(0, status);
} }
@Test @Test
public void pfcount() { public void pfcount() {
long status = jedis.pfadd("hll", "foo", "bar", "zap"); long status = jedis.pfadd("hll", "foo", "bar", "zap");
assertEquals(1, status); assertEquals(1, status);
status = jedis.pfadd("hll", "zap", "zap", "zap"); status = jedis.pfadd("hll", "zap", "zap", "zap");
assertEquals(0, status); assertEquals(0, status);
status = jedis.pfadd("hll", "foo", "bar"); status = jedis.pfadd("hll", "foo", "bar");
assertEquals(0, status); assertEquals(0, status);
status = jedis.pfcount("hll"); status = jedis.pfcount("hll");
assertEquals(3, status); assertEquals(3, status);
} }
@Test @Test
public void pfcounts() { public void pfcounts() {
long status = jedis.pfadd("hll_1", "foo", "bar", "zap"); long status = jedis.pfadd("hll_1", "foo", "bar", "zap");
assertEquals(1, status); assertEquals(1, status);
status = jedis.pfadd("hll_2", "foo", "bar", "zap"); status = jedis.pfadd("hll_2", "foo", "bar", "zap");
assertEquals(1, status); assertEquals(1, status);
status = jedis.pfadd("hll_3", "foo", "bar", "baz"); status = jedis.pfadd("hll_3", "foo", "bar", "baz");
assertEquals(1, status); assertEquals(1, status);
status = jedis.pfcount("hll_1"); status = jedis.pfcount("hll_1");
assertEquals(3, status); assertEquals(3, status);
status = jedis.pfcount("hll_2"); status = jedis.pfcount("hll_2");
assertEquals(3, status); assertEquals(3, status);
status = jedis.pfcount("hll_3"); status = jedis.pfcount("hll_3");
assertEquals(3, status); assertEquals(3, status);
status = jedis.pfcount("hll_1", "hll_2"); status = jedis.pfcount("hll_1", "hll_2");
assertEquals(3, status); assertEquals(3, status);
status = jedis.pfcount("hll_1", "hll_2", "hll_3");
assertEquals(4, status);
status = jedis.pfcount("hll_1", "hll_2", "hll_3");
assertEquals(4, status);
} }
@@ -74,35 +73,35 @@ public class HyperLogLogCommandsTest extends JedisCommandTestBase {
byte[] bFoo = SafeEncoder.encode("foo"); byte[] bFoo = SafeEncoder.encode("foo");
byte[] bBar = SafeEncoder.encode("bar"); byte[] bBar = SafeEncoder.encode("bar");
byte[] bZap = SafeEncoder.encode("zap"); byte[] bZap = SafeEncoder.encode("zap");
long status = jedis.pfadd(bHll, bFoo, bBar, bZap); long status = jedis.pfadd(bHll, bFoo, bBar, bZap);
assertEquals(1, status); assertEquals(1, status);
status = jedis.pfadd(bHll, bZap, bZap, bZap); status = jedis.pfadd(bHll, bZap, bZap, bZap);
assertEquals(0, status); assertEquals(0, status);
status = jedis.pfadd(bHll, bFoo, bBar); status = jedis.pfadd(bHll, bFoo, bBar);
assertEquals(0, status); assertEquals(0, status);
status = jedis.pfcount(bHll); status = jedis.pfcount(bHll);
assertEquals(3, status); assertEquals(3, status);
} }
@Test @Test
public void pfmerge() { public void pfmerge() {
long status = jedis.pfadd("hll1", "foo", "bar", "zap", "a"); long status = jedis.pfadd("hll1", "foo", "bar", "zap", "a");
assertEquals(1, status); assertEquals(1, status);
status = jedis.pfadd("hll2", "a", "b", "c", "foo"); status = jedis.pfadd("hll2", "a", "b", "c", "foo");
assertEquals(1, status); assertEquals(1, status);
String mergeStatus = jedis.pfmerge("hll3", "hll1", "hll2"); String mergeStatus = jedis.pfmerge("hll3", "hll1", "hll2");
assertEquals("OK", mergeStatus); assertEquals("OK", mergeStatus);
status = jedis.pfcount("hll3"); status = jedis.pfcount("hll3");
assertEquals(6, status); assertEquals(6, status);
} }
@Test @Test
public void pfmergeBinary() { public void pfmergeBinary() {
byte[] bHll1 = SafeEncoder.encode("hll1"); byte[] bHll1 = SafeEncoder.encode("hll1");
@@ -114,16 +113,16 @@ public class HyperLogLogCommandsTest extends JedisCommandTestBase {
byte[] bA = SafeEncoder.encode("a"); byte[] bA = SafeEncoder.encode("a");
byte[] bB = SafeEncoder.encode("b"); byte[] bB = SafeEncoder.encode("b");
byte[] bC = SafeEncoder.encode("c"); byte[] bC = SafeEncoder.encode("c");
long status = jedis.pfadd(bHll1, bFoo, bBar, bZap, bA); long status = jedis.pfadd(bHll1, bFoo, bBar, bZap, bA);
assertEquals(1, status); assertEquals(1, status);
status = jedis.pfadd(bHll2, bA, bB, bC, bFoo); status = jedis.pfadd(bHll2, bA, bB, bC, bFoo);
assertEquals(1, status); assertEquals(1, status);
String mergeStatus = jedis.pfmerge(bHll3, bHll1, bHll2); String mergeStatus = jedis.pfmerge(bHll3, bHll1, bHll2);
assertEquals("OK", mergeStatus); assertEquals("OK", mergeStatus);
status = jedis.pfcount("hll3"); status = jedis.pfcount("hll3");
assertEquals(6, status); assertEquals(6, status);
} }

View File

@@ -64,64 +64,68 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase {
} }
}, "foo"); }, "foo");
} }
@Test @Test
public void pubSubChannels(){ public void pubSubChannels() {
final List<String> expectedActiveChannels = Arrays.asList("testchan1", "testchan2", "testchan3"); final List<String> expectedActiveChannels = Arrays.asList("testchan1",
"testchan2", "testchan3");
jedis.subscribe(new JedisPubSub() { jedis.subscribe(new JedisPubSub() {
private int count = 0; private int count = 0;
@Override
public void onUnsubscribe(String channel, int subscribedChannels) {
}
@Override
public void onSubscribe(String channel, int subscribedChannels) {
count++;
//All channels are subscribed
if (count == 3) {
Jedis otherJedis = createJedis();
List<String> activeChannels = otherJedis.pubsubChannels("test*");
assertTrue(expectedActiveChannels.containsAll(activeChannels));
unsubscribe();
}
}
@Override
public void onPUnsubscribe(String pattern, int subscribedChannels) {
}
@Override
public void onPSubscribe(String pattern, int subscribedChannels) {
}
@Override
public void onPMessage(String pattern, String channel, String message) {
}
@Override
public void onMessage(String channel, String message) {
}
}, "testchan1", "testchan2", "testchan3");
}
@Test
public void pubSubNumPat(){
jedis.psubscribe(new JedisPubSub() {
private int count=0;
@Override @Override
public void onUnsubscribe(String channel, int subscribedChannels) { public void onUnsubscribe(String channel, int subscribedChannels) {
} }
@Override @Override
public void onSubscribe(String channel, int subscribedChannels) { public void onSubscribe(String channel, int subscribedChannels) {
count++;
// All channels are subscribed
if (count == 3) {
Jedis otherJedis = createJedis();
List<String> activeChannels = otherJedis
.pubsubChannels("test*");
assertTrue(expectedActiveChannels
.containsAll(activeChannels));
unsubscribe();
}
} }
@Override @Override
public void onPUnsubscribe(String pattern, int subscribedChannels) { public void onPUnsubscribe(String pattern, int subscribedChannels) {
} }
@Override
public void onPSubscribe(String pattern, int subscribedChannels) {
}
@Override
public void onPMessage(String pattern, String channel,
String message) {
}
@Override
public void onMessage(String channel, String message) {
}
}, "testchan1", "testchan2", "testchan3");
}
@Test
public void pubSubNumPat() {
jedis.psubscribe(new JedisPubSub() {
private int count = 0;
@Override
public void onUnsubscribe(String channel, int subscribedChannels) {
}
@Override
public void onSubscribe(String channel, int subscribedChannels) {
}
@Override
public void onPUnsubscribe(String pattern, int subscribedChannels) {
}
@Override @Override
public void onPSubscribe(String pattern, int subscribedChannels) { public void onPSubscribe(String pattern, int subscribedChannels) {
count++; count++;
@@ -132,51 +136,55 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase {
punsubscribe(); punsubscribe();
} }
} }
@Override @Override
public void onPMessage(String pattern, String channel, String message) { public void onPMessage(String pattern, String channel,
String message) {
} }
@Override @Override
public void onMessage(String channel, String message) { public void onMessage(String channel, String message) {
} }
}, "test*", "test*", "chan*"); }, "test*", "test*", "chan*");
} }
@Test @Test
public void pubSubNumSub(){ public void pubSubNumSub() {
final Map<String, String> expectedNumSub = new HashMap<String, String>(); final Map<String, String> expectedNumSub = new HashMap<String, String>();
expectedNumSub.put("testchannel2", "1"); expectedNumSub.put("testchannel2", "1");
expectedNumSub.put("testchannel1", "1"); expectedNumSub.put("testchannel1", "1");
jedis.subscribe(new JedisPubSub() { jedis.subscribe(new JedisPubSub() {
private int count=0; private int count = 0;
@Override @Override
public void onUnsubscribe(String channel, int subscribedChannels) { public void onUnsubscribe(String channel, int subscribedChannels) {
} }
@Override @Override
public void onSubscribe(String channel, int subscribedChannels) { public void onSubscribe(String channel, int subscribedChannels) {
count++; count++;
if (count == 2) { if (count == 2) {
Jedis otherJedis = createJedis(); Jedis otherJedis = createJedis();
Map<String, String> numSub = otherJedis.pubsubNumSub("testchannel1", "testchannel2"); Map<String, String> numSub = otherJedis.pubsubNumSub(
"testchannel1", "testchannel2");
assertEquals(expectedNumSub, numSub); assertEquals(expectedNumSub, numSub);
unsubscribe(); unsubscribe();
} }
} }
@Override @Override
public void onPUnsubscribe(String pattern, int subscribedChannels) { public void onPUnsubscribe(String pattern, int subscribedChannels) {
} }
@Override @Override
public void onPSubscribe(String pattern, int subscribedChannels) { public void onPSubscribe(String pattern, int subscribedChannels) {
} }
@Override @Override
public void onPMessage(String pattern, String channel, String message) { public void onPMessage(String pattern, String channel,
String message) {
} }
@Override @Override
public void onMessage(String channel, String message) { public void onMessage(String channel, String message) {
} }

View File

@@ -1,16 +1,17 @@
package redis.clients.jedis.tests.commands; package redis.clients.jedis.tests.commands;
import org.hamcrest.CoreMatchers; import static org.hamcrest.CoreMatchers.equalTo;
import org.hamcrest.Matcher;
import org.junit.Test;
import redis.clients.jedis.BinaryJedis;
import redis.clients.jedis.exceptions.JedisDataException;
import redis.clients.util.SafeEncoder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static org.hamcrest.CoreMatchers.equalTo; import org.hamcrest.CoreMatchers;
import org.hamcrest.Matcher;
import org.junit.Test;
import redis.clients.jedis.BinaryJedis;
import redis.clients.jedis.exceptions.JedisDataException;
import redis.clients.util.SafeEncoder;
public class ScriptingCommandsTest extends JedisCommandTestBase { public class ScriptingCommandsTest extends JedisCommandTestBase {
@@ -183,7 +184,8 @@ public class ScriptingCommandsTest extends JedisCommandTestBase {
@Test @Test
public void scriptEvalReturnNullValues() { public void scriptEvalReturnNullValues() {
String script = "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}"; String script = "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}";
List<String> results = (List<String>) jedis.eval(script, 2, "key1", "key2", "1", "2"); List<String> results = (List<String>) jedis.eval(script, 2, "key1",
"key2", "1", "2");
assertEquals("key1", results.get(0)); assertEquals("key1", results.get(0));
assertEquals("key2", results.get(1)); assertEquals("key2", results.get(1));
assertEquals("1", results.get(2)); assertEquals("1", results.get(2));
@@ -194,7 +196,8 @@ public class ScriptingCommandsTest extends JedisCommandTestBase {
public void scriptEvalShaReturnNullValues() { public void scriptEvalShaReturnNullValues() {
String script = "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}"; String script = "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}";
String sha = jedis.scriptLoad(script); String sha = jedis.scriptLoad(script);
List<String> results = (List<String>) jedis.evalsha(sha, 2, "key1", "key2", "1", "2"); List<String> results = (List<String>) jedis.evalsha(sha, 2, "key1",
"key2", "1", "2");
assertEquals("key1", results.get(0)); assertEquals("key1", results.get(0));
assertEquals("key2", results.get(1)); assertEquals("key2", results.get(1));
assertEquals("1", results.get(2)); assertEquals("1", results.get(2));
@@ -202,6 +205,6 @@ public class ScriptingCommandsTest extends JedisCommandTestBase {
} }
private <T> Matcher<Iterable<? super T>> listWithItem(T expected) { private <T> Matcher<Iterable<? super T>> listWithItem(T expected) {
return CoreMatchers.<T>hasItem(equalTo(expected)); return CoreMatchers.<T> hasItem(equalTo(expected));
} }
} }

View File

@@ -1,5 +1,8 @@
package redis.clients.jedis.tests.commands; package redis.clients.jedis.tests.commands;
import static redis.clients.jedis.ScanParams.SCAN_POINTER_START;
import static redis.clients.jedis.ScanParams.SCAN_POINTER_START_BINARY;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
@@ -8,8 +11,6 @@ import org.junit.Test;
import redis.clients.jedis.ScanParams; import redis.clients.jedis.ScanParams;
import redis.clients.jedis.ScanResult; import redis.clients.jedis.ScanResult;
import static redis.clients.jedis.ScanParams.SCAN_POINTER_START;
import static redis.clients.jedis.ScanParams.SCAN_POINTER_START_BINARY;
public class SetCommandsTest extends JedisCommandTestBase { public class SetCommandsTest extends JedisCommandTestBase {
final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 };
@@ -20,7 +21,7 @@ public class SetCommandsTest extends JedisCommandTestBase {
final byte[] bc = { 0x0C }; final byte[] bc = { 0x0C };
final byte[] bd = { 0x0D }; final byte[] bd = { 0x0D };
final byte[] bx = { 0x42 }; final byte[] bx = { 0x42 };
final byte[] bbar1 = { 0x05, 0x06, 0x07, 0x08, 0x0A }; final byte[] bbar1 = { 0x05, 0x06, 0x07, 0x08, 0x0A };
final byte[] bbar2 = { 0x05, 0x06, 0x07, 0x08, 0x0B }; final byte[] bbar2 = { 0x05, 0x06, 0x07, 0x08, 0x0B };
final byte[] bbar3 = { 0x05, 0x06, 0x07, 0x08, 0x0C }; final byte[] bbar3 = { 0x05, 0x06, 0x07, 0x08, 0x0C };
@@ -468,11 +469,12 @@ public class SetCommandsTest extends JedisCommandTestBase {
assertEquals(SCAN_POINTER_START, result.getCursor()); assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty()); assertFalse(result.getResult().isEmpty());
// binary // binary
jedis.sadd(bfoo, ba, bb); jedis.sadd(bfoo, ba, bb);
ScanResult<byte[]> bResult = jedis.sscan(bfoo, SCAN_POINTER_START_BINARY); ScanResult<byte[]> bResult = jedis.sscan(bfoo,
SCAN_POINTER_START_BINARY);
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty()); assertFalse(bResult.getResult().isEmpty());
@@ -484,17 +486,19 @@ public class SetCommandsTest extends JedisCommandTestBase {
params.match("a*"); params.match("a*");
jedis.sadd("foo", "b", "a", "aa"); jedis.sadd("foo", "b", "a", "aa");
ScanResult<String> result = jedis.sscan("foo", SCAN_POINTER_START, params); ScanResult<String> result = jedis.sscan("foo", SCAN_POINTER_START,
params);
assertEquals(SCAN_POINTER_START, result.getCursor()); assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty()); assertFalse(result.getResult().isEmpty());
// binary // binary
params = new ScanParams(); params = new ScanParams();
params.match(bbarstar); params.match(bbarstar);
jedis.sadd(bfoo, bbar1, bbar2, bbar3); jedis.sadd(bfoo, bbar1, bbar2, bbar3);
ScanResult<byte[]> bResult = jedis.sscan(bfoo, SCAN_POINTER_START_BINARY, params); ScanResult<byte[]> bResult = jedis.sscan(bfoo,
SCAN_POINTER_START_BINARY, params);
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty()); assertFalse(bResult.getResult().isEmpty());
@@ -507,16 +511,18 @@ public class SetCommandsTest extends JedisCommandTestBase {
jedis.sadd("foo", "a1", "a2", "a3", "a4", "a5"); jedis.sadd("foo", "a1", "a2", "a3", "a4", "a5");
ScanResult<String> result = jedis.sscan("foo", SCAN_POINTER_START, params); ScanResult<String> result = jedis.sscan("foo", SCAN_POINTER_START,
params);
assertFalse(result.getResult().isEmpty()); assertFalse(result.getResult().isEmpty());
// binary // binary
params = new ScanParams(); params = new ScanParams();
params.count(2); params.count(2);
jedis.sadd(bfoo, bbar1, bbar2, bbar3); jedis.sadd(bfoo, bbar1, bbar2, bbar3);
ScanResult<byte[]> bResult = jedis.sscan(bfoo, SCAN_POINTER_START_BINARY, params); ScanResult<byte[]> bResult = jedis.sscan(bfoo,
SCAN_POINTER_START_BINARY, params);
assertFalse(bResult.getResult().isEmpty()); assertFalse(bResult.getResult().isEmpty());
} }

View File

@@ -1,5 +1,8 @@
package redis.clients.jedis.tests.commands; package redis.clients.jedis.tests.commands;
import static redis.clients.jedis.ScanParams.SCAN_POINTER_START;
import static redis.clients.jedis.ScanParams.SCAN_POINTER_START_BINARY;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.Set; import java.util.Set;
@@ -10,8 +13,6 @@ import redis.clients.jedis.ScanResult;
import redis.clients.jedis.Tuple; import redis.clients.jedis.Tuple;
import redis.clients.jedis.ZParams; import redis.clients.jedis.ZParams;
import redis.clients.util.SafeEncoder; import redis.clients.util.SafeEncoder;
import static redis.clients.jedis.ScanParams.SCAN_POINTER_START;
import static redis.clients.jedis.ScanParams.SCAN_POINTER_START_BINARY;
public class SortedSetCommandsTest extends JedisCommandTestBase { public class SortedSetCommandsTest extends JedisCommandTestBase {
final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 };
@@ -20,11 +21,11 @@ public class SortedSetCommandsTest extends JedisCommandTestBase {
final byte[] ba = { 0x0A }; final byte[] ba = { 0x0A };
final byte[] bb = { 0x0B }; final byte[] bb = { 0x0B };
final byte[] bc = { 0x0C }; final byte[] bc = { 0x0C };
final byte[] bInclusiveB = { 0x5B, 0x0B }; final byte[] bInclusiveB = { 0x5B, 0x0B };
final byte[] bExclusiveC = { 0x28, 0x0C }; final byte[] bExclusiveC = { 0x28, 0x0C };
final byte[] bLexMinusInf = { 0x2D }; final byte[] bLexMinusInf = { 0x2D };
final byte[] bLexPlusInf = { 0x2B }; final byte[] bLexPlusInf = { 0x2B };
final byte[] bbar1 = { 0x05, 0x06, 0x07, 0x08, 0x0A }; final byte[] bbar1 = { 0x05, 0x06, 0x07, 0x08, 0x0A };
final byte[] bbar2 = { 0x05, 0x06, 0x07, 0x08, 0x0B }; final byte[] bbar2 = { 0x05, 0x06, 0x07, 0x08, 0x0B };
final byte[] bbar3 = { 0x05, 0x06, 0x07, 0x08, 0x0C }; final byte[] bbar3 = { 0x05, 0x06, 0x07, 0x08, 0x0C };
@@ -58,7 +59,7 @@ public class SortedSetCommandsTest extends JedisCommandTestBase {
assertEquals(0, bstatus); assertEquals(0, bstatus);
} }
@Test @Test
public void zrange() { public void zrange() {
jedis.zadd("foo", 1d, "a"); jedis.zadd("foo", 1d, "a");
@@ -95,29 +96,29 @@ public class SortedSetCommandsTest extends JedisCommandTestBase {
assertEquals(bexpected, brange); assertEquals(bexpected, brange);
} }
@Test @Test
public void zrangeByLex() { public void zrangeByLex() {
jedis.zadd("foo", 1, "aa"); jedis.zadd("foo", 1, "aa");
jedis.zadd("foo", 1, "c"); jedis.zadd("foo", 1, "c");
jedis.zadd("foo", 1, "bb"); jedis.zadd("foo", 1, "bb");
jedis.zadd("foo", 1, "d"); jedis.zadd("foo", 1, "d");
Set<String> expected = new LinkedHashSet<String>(); Set<String> expected = new LinkedHashSet<String>();
expected.add("bb"); expected.add("bb");
expected.add("c"); expected.add("c");
// exclusive aa ~ inclusive c // exclusive aa ~ inclusive c
assertEquals(expected, jedis.zrangeByLex("foo", "(aa", "[c")); assertEquals(expected, jedis.zrangeByLex("foo", "(aa", "[c"));
expected.clear(); expected.clear();
expected.add("bb"); expected.add("bb");
expected.add("c"); expected.add("c");
// with LIMIT // with LIMIT
assertEquals(expected, jedis.zrangeByLex("foo", "-", "+", 1, 2)); assertEquals(expected, jedis.zrangeByLex("foo", "-", "+", 1, 2));
} }
@Test @Test
public void zrangeByLexBinary() { public void zrangeByLexBinary() {
// binary // binary
@@ -128,56 +129,60 @@ public class SortedSetCommandsTest extends JedisCommandTestBase {
Set<byte[]> bExpected = new LinkedHashSet<byte[]>(); Set<byte[]> bExpected = new LinkedHashSet<byte[]>();
bExpected.add(bb); bExpected.add(bb);
assertEquals(bExpected, jedis.zrangeByLex(bfoo, bInclusiveB, bExclusiveC)); assertEquals(bExpected,
jedis.zrangeByLex(bfoo, bInclusiveB, bExclusiveC));
bExpected.clear(); bExpected.clear();
bExpected.add(ba); bExpected.add(ba);
bExpected.add(bb); bExpected.add(bb);
// with LIMIT // with LIMIT
assertEquals(bExpected, jedis.zrangeByLex(bfoo, bLexMinusInf, bLexPlusInf, 0, 2)); assertEquals(bExpected,
jedis.zrangeByLex(bfoo, bLexMinusInf, bLexPlusInf, 0, 2));
} }
@Test @Test
public void zrevrangeByLex() { public void zrevrangeByLex() {
jedis.zadd("foo", 1, "aa"); jedis.zadd("foo", 1, "aa");
jedis.zadd("foo", 1, "c"); jedis.zadd("foo", 1, "c");
jedis.zadd("foo", 1, "bb"); jedis.zadd("foo", 1, "bb");
jedis.zadd("foo", 1, "d"); jedis.zadd("foo", 1, "d");
Set<String> expected = new LinkedHashSet<String>(); Set<String> expected = new LinkedHashSet<String>();
expected.add("c"); expected.add("c");
expected.add("bb"); expected.add("bb");
// exclusive aa ~ inclusive c // exclusive aa ~ inclusive c
assertEquals(expected, jedis.zrevrangeByLex("foo", "[c", "(aa")); assertEquals(expected, jedis.zrevrangeByLex("foo", "[c", "(aa"));
expected.clear(); expected.clear();
expected.add("c"); expected.add("c");
expected.add("bb"); expected.add("bb");
// with LIMIT // with LIMIT
assertEquals(expected, jedis.zrevrangeByLex("foo", "+", "-", 1, 2)); assertEquals(expected, jedis.zrevrangeByLex("foo", "+", "-", 1, 2));
} }
@Test @Test
public void zrevrangeByLexBinary() { public void zrevrangeByLexBinary() {
// binary // binary
jedis.zadd(bfoo, 1, ba); jedis.zadd(bfoo, 1, ba);
jedis.zadd(bfoo, 1, bc); jedis.zadd(bfoo, 1, bc);
jedis.zadd(bfoo, 1, bb); jedis.zadd(bfoo, 1, bb);
Set<byte[]> bExpected = new LinkedHashSet<byte[]>(); Set<byte[]> bExpected = new LinkedHashSet<byte[]>();
bExpected.add(bb); bExpected.add(bb);
assertEquals(bExpected, jedis.zrevrangeByLex(bfoo, bExclusiveC, bInclusiveB)); assertEquals(bExpected,
jedis.zrevrangeByLex(bfoo, bExclusiveC, bInclusiveB));
bExpected.clear(); bExpected.clear();
bExpected.add(bb); bExpected.add(bb);
bExpected.add(ba); bExpected.add(ba);
// with LIMIT // with LIMIT
assertEquals(bExpected, jedis.zrevrangeByLex(bfoo, bLexPlusInf, bLexMinusInf, 0, 2)); assertEquals(bExpected,
jedis.zrevrangeByLex(bfoo, bLexPlusInf, bLexMinusInf, 0, 2));
} }
@Test @Test
@@ -489,7 +494,7 @@ public class SortedSetCommandsTest extends JedisCommandTestBase {
assertEquals(3, bresult); assertEquals(3, bresult);
} }
@Test @Test
public void zlexcount() { public void zlexcount() {
jedis.zadd("foo", 1, "a"); jedis.zadd("foo", 1, "a");
@@ -502,14 +507,14 @@ public class SortedSetCommandsTest extends JedisCommandTestBase {
result = jedis.zlexcount("foo", "-", "+"); result = jedis.zlexcount("foo", "-", "+");
assertEquals(4, result); assertEquals(4, result);
result = jedis.zlexcount("foo", "-", "(c"); result = jedis.zlexcount("foo", "-", "(c");
assertEquals(3, result); assertEquals(3, result);
result = jedis.zlexcount("foo", "[aa", "+"); result = jedis.zlexcount("foo", "[aa", "+");
assertEquals(3, result); assertEquals(3, result);
} }
@Test @Test
public void zlexcountBinary() { public void zlexcountBinary() {
// Binary // Binary
@@ -861,7 +866,7 @@ public class SortedSetCommandsTest extends JedisCommandTestBase {
assertEquals(bexpected, jedis.zrange(bfoo, 0, 100)); assertEquals(bexpected, jedis.zrange(bfoo, 0, 100));
} }
@Test @Test
public void zremrangeByLex() { public void zremrangeByLex() {
jedis.zadd("foo", 1, "a"); jedis.zadd("foo", 1, "a");
@@ -879,22 +884,23 @@ public class SortedSetCommandsTest extends JedisCommandTestBase {
assertEquals(expected, jedis.zrangeByLex("foo", "-", "+")); assertEquals(expected, jedis.zrangeByLex("foo", "-", "+"));
} }
@Test @Test
public void zremrangeByLexBinary() { public void zremrangeByLexBinary() {
jedis.zadd(bfoo, 1, ba); jedis.zadd(bfoo, 1, ba);
jedis.zadd(bfoo, 1, bc); jedis.zadd(bfoo, 1, bc);
jedis.zadd(bfoo, 1, bb); jedis.zadd(bfoo, 1, bb);
long bresult = jedis.zremrangeByLex(bfoo, bInclusiveB, bExclusiveC); long bresult = jedis.zremrangeByLex(bfoo, bInclusiveB, bExclusiveC);
assertEquals(1, bresult); assertEquals(1, bresult);
Set<byte[]> bexpected = new LinkedHashSet<byte[]>(); Set<byte[]> bexpected = new LinkedHashSet<byte[]>();
bexpected.add(ba); bexpected.add(ba);
bexpected.add(bc); bexpected.add(bc);
assertEquals(bexpected, jedis.zrangeByLex(bfoo, bLexMinusInf, bLexPlusInf)); assertEquals(bexpected,
jedis.zrangeByLex(bfoo, bLexMinusInf, bLexPlusInf));
} }
@Test @Test
@@ -1062,12 +1068,13 @@ public class SortedSetCommandsTest extends JedisCommandTestBase {
assertEquals(SCAN_POINTER_START, result.getCursor()); assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty()); assertFalse(result.getResult().isEmpty());
// binary // binary
jedis.zadd(bfoo, 1, ba); jedis.zadd(bfoo, 1, ba);
jedis.zadd(bfoo, 1, bb); jedis.zadd(bfoo, 1, bb);
ScanResult<Tuple> bResult = jedis.zscan(bfoo, SCAN_POINTER_START_BINARY); ScanResult<Tuple> bResult = jedis
.zscan(bfoo, SCAN_POINTER_START_BINARY);
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty()); assertFalse(bResult.getResult().isEmpty());
@@ -1081,11 +1088,12 @@ public class SortedSetCommandsTest extends JedisCommandTestBase {
jedis.zadd("foo", 2, "b"); jedis.zadd("foo", 2, "b");
jedis.zadd("foo", 1, "a"); jedis.zadd("foo", 1, "a");
jedis.zadd("foo", 11, "aa"); jedis.zadd("foo", 11, "aa");
ScanResult<Tuple> result = jedis.zscan("foo", SCAN_POINTER_START, params); ScanResult<Tuple> result = jedis.zscan("foo", SCAN_POINTER_START,
params);
assertEquals(SCAN_POINTER_START, result.getCursor()); assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty()); assertFalse(result.getResult().isEmpty());
// binary // binary
params = new ScanParams(); params = new ScanParams();
params.match(bbarstar); params.match(bbarstar);
@@ -1093,11 +1101,12 @@ public class SortedSetCommandsTest extends JedisCommandTestBase {
jedis.zadd(bfoo, 2, bbar1); jedis.zadd(bfoo, 2, bbar1);
jedis.zadd(bfoo, 1, bbar2); jedis.zadd(bfoo, 1, bbar2);
jedis.zadd(bfoo, 11, bbar3); jedis.zadd(bfoo, 11, bbar3);
ScanResult<Tuple> bResult = jedis.zscan(bfoo, SCAN_POINTER_START_BINARY, params); ScanResult<Tuple> bResult = jedis.zscan(bfoo,
SCAN_POINTER_START_BINARY, params);
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty()); assertFalse(bResult.getResult().isEmpty());
} }
@Test @Test
@@ -1111,19 +1120,21 @@ public class SortedSetCommandsTest extends JedisCommandTestBase {
jedis.zadd("foo", 4, "a4"); jedis.zadd("foo", 4, "a4");
jedis.zadd("foo", 5, "a5"); jedis.zadd("foo", 5, "a5");
ScanResult<Tuple> result = jedis.zscan("foo", SCAN_POINTER_START, params); ScanResult<Tuple> result = jedis.zscan("foo", SCAN_POINTER_START,
params);
assertFalse(result.getResult().isEmpty()); assertFalse(result.getResult().isEmpty());
// binary // binary
params = new ScanParams(); params = new ScanParams();
params.count(2); params.count(2);
jedis.zadd(bfoo, 2, bbar1); jedis.zadd(bfoo, 2, bbar1);
jedis.zadd(bfoo, 1, bbar2); jedis.zadd(bfoo, 1, bbar2);
jedis.zadd(bfoo, 11, bbar3); jedis.zadd(bfoo, 11, bbar3);
ScanResult<Tuple> bResult = jedis.zscan(bfoo, SCAN_POINTER_START_BINARY, params); ScanResult<Tuple> bResult = jedis.zscan(bfoo,
SCAN_POINTER_START_BINARY, params);
assertFalse(bResult.getResult().isEmpty()); assertFalse(bResult.getResult().isEmpty());
} }

View File

@@ -125,8 +125,8 @@ public class StringValuesCommandsTest extends JedisCommandTestBase {
@Test(expected = JedisDataException.class) @Test(expected = JedisDataException.class)
public void incrByFloatWrongValue() { public void incrByFloatWrongValue() {
jedis.set("foo", "bar"); jedis.set("foo", "bar");
jedis.incrByFloat("foo", 2d); jedis.incrByFloat("foo", 2d);
} }
@Test(expected = JedisDataException.class) @Test(expected = JedisDataException.class)

View File

@@ -16,16 +16,19 @@ public class JedisClusterCRC16Test {
@Test @Test
public void testGetCRC16() throws Exception { public void testGetCRC16() throws Exception {
Map<String, Integer> solutions = prepareSolutionSet(); Map<String, Integer> solutions = prepareSolutionSet();
for (Entry<String, Integer> entry : solutions.entrySet()) { for (Entry<String, Integer> entry : solutions.entrySet()) {
// string version // string version
assertEquals(entry.getValue().intValue(), JedisClusterCRC16.getCRC16(entry.getKey())); assertEquals(entry.getValue().intValue(),
JedisClusterCRC16.getCRC16(entry.getKey()));
// byte array version // byte array version
assertEquals(entry.getValue().intValue(), JedisClusterCRC16.getCRC16(SafeEncoder.encode(entry.getKey()))); assertEquals(entry.getValue().intValue(),
JedisClusterCRC16.getCRC16(SafeEncoder.encode(entry
.getKey())));
} }
} }
@Test @Test
public void testGetSlot() { public void testGetSlot() {
assertEquals(7186, JedisClusterCRC16.getSlot("51")); assertEquals(7186, JedisClusterCRC16.getSlot("51"));

View File

@@ -5,7 +5,8 @@ import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisException; import redis.clients.jedis.exceptions.JedisException;
public class JedisClusterTestUtil { public class JedisClusterTestUtil {
public static void waitForClusterReady(Jedis...nodes) throws InterruptedException { public static void waitForClusterReady(Jedis... nodes)
throws InterruptedException {
boolean clusterOk = false; boolean clusterOk = false;
while (!clusterOk) { while (!clusterOk) {
boolean isOk = true; boolean isOk = true;
@@ -15,7 +16,7 @@ public class JedisClusterTestUtil {
break; break;
} }
} }
if (isOk) { if (isOk) {
clusterOk = true; clusterOk = true;
} }
@@ -23,7 +24,7 @@ public class JedisClusterTestUtil {
Thread.sleep(50); Thread.sleep(50);
} }
} }
public static String getNodeId(String infoOutput) { public static String getNodeId(String infoOutput) {
for (String infoLine : infoOutput.split("\n")) { for (String infoLine : infoOutput.split("\n")) {
if (infoLine.contains("myself")) { if (infoLine.contains("myself")) {
@@ -32,9 +33,9 @@ public class JedisClusterTestUtil {
} }
return ""; return "";
} }
public static String getNodeId(String infoOutput,HostAndPort node){ public static String getNodeId(String infoOutput, HostAndPort node) {
for (String infoLine : infoOutput.split("\n")) { for (String infoLine : infoOutput.split("\n")) {
if (infoLine.contains(node.toString())) { if (infoLine.contains(node.toString())) {
return infoLine.split(" ")[0]; return infoLine.split(" ")[0];
@@ -42,31 +43,34 @@ public class JedisClusterTestUtil {
} }
return ""; return "";
} }
public static void assertNodeIsKnown(Jedis node, String targetNodeId, int timeoutMs) { public static void assertNodeIsKnown(Jedis node, String targetNodeId,
int timeoutMs) {
assertNodeRecognizedStatus(node, targetNodeId, true, timeoutMs); assertNodeRecognizedStatus(node, targetNodeId, true, timeoutMs);
} }
public static void assertNodeIsUnknown(Jedis node, String targetNodeId, int timeoutMs) { public static void assertNodeIsUnknown(Jedis node, String targetNodeId,
int timeoutMs) {
assertNodeRecognizedStatus(node, targetNodeId, false, timeoutMs); assertNodeRecognizedStatus(node, targetNodeId, false, timeoutMs);
} }
private static void assertNodeRecognizedStatus(Jedis node, String targetNodeId, boolean shouldRecognized, int timeoutMs) { private static void assertNodeRecognizedStatus(Jedis node,
String targetNodeId, boolean shouldRecognized, int timeoutMs) {
int sleepInterval = 100; int sleepInterval = 100;
for (int sleepTime = 0 ; sleepTime <= timeoutMs ; sleepTime += sleepInterval) { for (int sleepTime = 0; sleepTime <= timeoutMs; sleepTime += sleepInterval) {
boolean known = isKnownNode(node, targetNodeId); boolean known = isKnownNode(node, targetNodeId);
if (shouldRecognized == known) if (shouldRecognized == known)
return; return;
try { try {
Thread.sleep(sleepInterval); Thread.sleep(sleepInterval);
} catch (InterruptedException e) { } catch (InterruptedException e) {
} }
} }
throw new JedisException("Node recognize check error"); throw new JedisException("Node recognize check error");
} }
private static boolean isKnownNode(Jedis node, String nodeId) { private static boolean isKnownNode(Jedis node, String nodeId) {
String infoOutput = node.clusterNodes(); String infoOutput = node.clusterNodes();
for (String infoLine : infoOutput.split("\n")) { for (String infoLine : infoOutput.split("\n")) {
@@ -76,6 +80,5 @@ public class JedisClusterTestUtil {
} }
return false; return false;
} }
} }

View File

@@ -5,13 +5,12 @@ import java.util.concurrent.atomic.AtomicReference;
import redis.clients.jedis.HostAndPort; import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis; import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub; import redis.clients.jedis.JedisPubSub;
import redis.clients.jedis.tests.utils.FailoverAbortedException;
public class JedisSentinelTestUtil { public class JedisSentinelTestUtil {
public static HostAndPort waitForNewPromotedMaster(final String masterName, public static HostAndPort waitForNewPromotedMaster(final String masterName,
final Jedis sentinelJedis, final Jedis commandJedis) final Jedis sentinelJedis, final Jedis commandJedis)
throws InterruptedException { throws InterruptedException {
final AtomicReference<String> newmaster = new AtomicReference<String>( final AtomicReference<String> newmaster = new AtomicReference<String>(
""); "");
@@ -29,8 +28,9 @@ public class JedisSentinelTestUtil {
punsubscribe(); punsubscribe();
} else if (channel.startsWith("-failover-abort")) { } else if (channel.startsWith("-failover-abort")) {
punsubscribe(); punsubscribe();
throw new FailoverAbortedException("Unfortunately sentinel cannot failover... reason(channel) : " + throw new FailoverAbortedException(
channel + " / message : " + message); "Unfortunately sentinel cannot failover... reason(channel) : "
+ channel + " / message : " + message);
} }
} }
@@ -48,7 +48,7 @@ public class JedisSentinelTestUtil {
@Override @Override
public void onPSubscribe(String pattern, int subscribedChannels) { public void onPSubscribe(String pattern, int subscribedChannels) {
commandJedis.sentinelFailover(masterName); commandJedis.sentinelFailover(masterName);
} }
}, "*"); }, "*");