From 610f7d454615db23cb56089bff076feddd12910a Mon Sep 17 00:00:00 2001 From: Eric Treworgy Date: Mon, 7 Jan 2013 12:33:19 -0800 Subject: [PATCH 001/120] Added incrByFloat and hincrByFloat commands (binary and standard) + support for pipelining and sharding --- .../redis/clients/jedis/BinaryClient.java | 8 +++ .../java/redis/clients/jedis/BinaryJedis.java | 56 +++++++++++++++++++ .../clients/jedis/BinaryJedisCommands.java | 4 ++ .../clients/jedis/BinaryShardedJedis.java | 10 ++++ src/main/java/redis/clients/jedis/Client.java | 8 +++ .../java/redis/clients/jedis/Commands.java | 4 ++ src/main/java/redis/clients/jedis/Jedis.java | 51 +++++++++++++++++ .../java/redis/clients/jedis/Pipeline.java | 20 +++++++ .../java/redis/clients/jedis/Protocol.java | 2 +- .../redis/clients/jedis/ShardedJedis.java | 10 ++++ .../clients/jedis/ShardedJedisPipeline.java | 14 +++++ .../tests/commands/HashesCommandsTest.java | 19 +++++++ .../tests/commands/ScriptingCommandsTest.java | 2 +- .../commands/StringValuesCommandsTest.java | 16 ++++++ 14 files changed, 222 insertions(+), 2 deletions(-) diff --git a/src/main/java/redis/clients/jedis/BinaryClient.java b/src/main/java/redis/clients/jedis/BinaryClient.java index a5323d2..56be470 100644 --- a/src/main/java/redis/clients/jedis/BinaryClient.java +++ b/src/main/java/redis/clients/jedis/BinaryClient.java @@ -192,6 +192,10 @@ public class BinaryClient extends Connection { sendCommand(INCRBY, key, toByteArray(integer)); } + public void incrByFloat(final byte[] key, final double value) { + sendCommand(INCRBYFLOAT, key, toByteArray(value)); + } + public void incr(final byte[] key) { sendCommand(INCR, key); } @@ -238,6 +242,10 @@ public class BinaryClient extends Connection { sendCommand(HINCRBY, key, field, toByteArray(value)); } + public void hincrByFloat(final byte[] key, final byte[] field, final double value) { + sendCommand(HINCRBYFLOAT, key, field, toByteArray(value)); + } + public void hexists(final byte[] key, final byte[] field) { sendCommand(HEXISTS, key, field); } diff --git a/src/main/java/redis/clients/jedis/BinaryJedis.java b/src/main/java/redis/clients/jedis/BinaryJedis.java index 5403e70..c959f47 100644 --- a/src/main/java/redis/clients/jedis/BinaryJedis.java +++ b/src/main/java/redis/clients/jedis/BinaryJedis.java @@ -602,6 +602,36 @@ public class BinaryJedis implements BinaryJedisCommands { return client.getIntegerReply(); } + /** + * INCRBYFLOAT work just like {@link #incrBy(byte[]) INCRBY} but increments + * by floats instead of integers. + *

+ * INCRBYFLOAT commands are limited to double precision floating point values. + *

+ * Note: this is actually a string operation, that is, in Redis there are + * not "double" types. Simply the string stored at the key is parsed as a + * base double precision floating point value, incremented, and then converted + * back as a string. There is no DECRYBYFLOAT but providing a negative + * value will work as expected. + *

+ * Time complexity: O(1) + * + * @see #incr(byte[]) + * @see #decr(byte[]) + * @see #decrBy(byte[], long) + * + * @param key + * @param integer + * @return Integer reply, this commands will reply with the new value of key + * after the increment. + */ + public Double incrByFloat(final byte[] key, final double integer) { + checkIsInMulti(); + client.incrByFloat(key, integer); + String dval = client.getBulkReply(); + return (dval != null ? new Double(dval) : null); + } + /** * Increment the number stored at key by one. If the key does not exist or * contains a value of a wrong type, set the key to the value of "0" before @@ -794,6 +824,32 @@ public class BinaryJedis implements BinaryJedisCommands { return client.getIntegerReply(); } + /** + * Increment the number stored at field in the hash at key by a double + * precision floating point value. If key does not exist, + * a new key holding a hash is created. If field does not + * exist or holds a string, the value is set to 0 before applying the + * operation. Since the value argument is signed you can use this command to + * perform both increments and decrements. + *

+ * The range of values supported by HINCRBYFLOAT is limited to + * double precision floating point values. + *

+ * Time complexity: O(1) + * + * @param key + * @param field + * @param value + * @return Double precision floating point reply The new value at field after the increment + * operation. + */ + public Double hincrByFloat(final byte[] key, final byte[] field, final double value) { + checkIsInMulti(); + client.hincrByFloat(key, field, value); + final String dval = client.getBulkReply(); + return (dval != null ? new Double(dval) : null); + } + /** * Test for existence of a specified field in a hash. * diff --git a/src/main/java/redis/clients/jedis/BinaryJedisCommands.java b/src/main/java/redis/clients/jedis/BinaryJedisCommands.java index 77189f7..1a5f079 100644 --- a/src/main/java/redis/clients/jedis/BinaryJedisCommands.java +++ b/src/main/java/redis/clients/jedis/BinaryJedisCommands.java @@ -37,6 +37,8 @@ public interface BinaryJedisCommands { Long incrBy(byte[] key, long integer); + Double incrByFloat(byte[] key, double value); + Long incr(byte[] key); Long append(byte[] key, byte[] value); @@ -55,6 +57,8 @@ public interface BinaryJedisCommands { Long hincrBy(byte[] key, byte[] field, long value); + Double hincrByFloat(byte[] key, byte[] field, double value); + Boolean hexists(byte[] key, byte[] field); Long hdel(byte[] key, byte[]... field); diff --git a/src/main/java/redis/clients/jedis/BinaryShardedJedis.java b/src/main/java/redis/clients/jedis/BinaryShardedJedis.java index 23fd6d6..1b6ad9a 100644 --- a/src/main/java/redis/clients/jedis/BinaryShardedJedis.java +++ b/src/main/java/redis/clients/jedis/BinaryShardedJedis.java @@ -110,6 +110,11 @@ public class BinaryShardedJedis extends Sharded return j.incrBy(key, integer); } + public Double incrByFloat(byte[] key, double integer) { + Jedis j = getShard(key); + return j.incrByFloat(key, integer); + } + public Long incr(byte[] key) { Jedis j = getShard(key); return j.incr(key); @@ -155,6 +160,11 @@ public class BinaryShardedJedis extends Sharded return j.hincrBy(key, field, value); } + public Double hincrByFloat(byte[] key, byte[] field, double value) { + Jedis j = getShard(key); + return j.hincrByFloat(key, field, value); + } + public Boolean hexists(byte[] key, byte[] field) { Jedis j = getShard(key); return j.hexists(key, field); diff --git a/src/main/java/redis/clients/jedis/Client.java b/src/main/java/redis/clients/jedis/Client.java index 39aae12..992d10d 100644 --- a/src/main/java/redis/clients/jedis/Client.java +++ b/src/main/java/redis/clients/jedis/Client.java @@ -117,6 +117,10 @@ public class Client extends BinaryClient implements Commands { incrBy(SafeEncoder.encode(key), integer); } + public void incrByFloat(final String key, final double value) { + incrByFloat(SafeEncoder.encode(key), value); + } + public void incr(final String key) { incr(SafeEncoder.encode(key)); } @@ -165,6 +169,10 @@ public class Client extends BinaryClient implements Commands { hincrBy(SafeEncoder.encode(key), SafeEncoder.encode(field), value); } + public void hincrByFloat(final String key, final String field, final double value) { + hincrByFloat(SafeEncoder.encode(key), SafeEncoder.encode(field), value); + } + public void hexists(final String key, final String field) { hexists(SafeEncoder.encode(key), SafeEncoder.encode(field)); } diff --git a/src/main/java/redis/clients/jedis/Commands.java b/src/main/java/redis/clients/jedis/Commands.java index 7881909..3776342 100644 --- a/src/main/java/redis/clients/jedis/Commands.java +++ b/src/main/java/redis/clients/jedis/Commands.java @@ -56,6 +56,8 @@ public interface Commands { public void incrBy(final String key, final long integer); + public void incrByFloat(final String key, final double value); + public void incr(final String key); public void append(final String key, final String value); @@ -74,6 +76,8 @@ public interface Commands { 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 hexists(final String key, final String field); public void hdel(final String key, final String... fields); diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index f27c2bc..62040f9 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -572,6 +572,31 @@ public class Jedis extends BinaryJedis implements JedisCommands { return client.getIntegerReply(); } + /** + * INCRBYFLOAT + *

+ * INCRBYFLOAT commands are limited to double precision floating point values. + *

+ * Note: this is actually a string operation, that is, in Redis there are + * not "double" types. Simply the string stored at the key is parsed as a + * base double precision floating point value, incremented, and then + * converted back as a string. There is no DECRYBYFLOAT but providing a + * negative value will work as expected. + *

+ * Time complexity: O(1) + * + * @param key + * @param value + * @return Double reply, this commands will reply with the new value of key + * after the increment. + */ + public Double incrByFloat(final String key, final double value) { + checkIsInMulti(); + client.incrByFloat(key, value); + String dval = client.getBulkReply(); + return (dval != null ? new Double(dval) : null); + } + /** * Increment the number stored at key by one. If the key does not exist or * contains a value of a wrong type, set the key to the value of "0" before @@ -764,6 +789,32 @@ public class Jedis extends BinaryJedis implements JedisCommands { return client.getIntegerReply(); } + /** + * Increment the number stored at field in the hash at key by a double + * precision floating point value. If key does not exist, + * a new key holding a hash is created. If field does not + * exist or holds a string, the value is set to 0 before applying the + * operation. Since the value argument is signed you can use this command to + * perform both increments and decrements. + *

+ * The range of values supported by HINCRBYFLOAT is limited to + * double precision floating point values. + *

+ * Time complexity: O(1) + * + * @param key + * @param field + * @param value + * @return Double precision floating point reply The new value at field after the increment + * operation. + */ + public Double hincrByFloat(final String key, final String field, final double value) { + checkIsInMulti(); + client.hincrByFloat(key, field, value); + final String dval = client.getBulkReply(); + return (dval != null ? new Double(dval) : null); + } + /** * Test for existence of a specified field in a hash. * diff --git a/src/main/java/redis/clients/jedis/Pipeline.java b/src/main/java/redis/clients/jedis/Pipeline.java index d89efea..cd1ecaa 100644 --- a/src/main/java/redis/clients/jedis/Pipeline.java +++ b/src/main/java/redis/clients/jedis/Pipeline.java @@ -275,6 +275,16 @@ public class Pipeline extends Queable { return getResponse(BuilderFactory.LONG); } + public Response hincrByFloat(String key, String field, double value) { + client.hincrByFloat(key, field, value); + return getResponse(BuilderFactory.DOUBLE); + } + + public Response hincrByFloat(byte[] key, byte[] field, double value) { + client.hincrByFloat(key, field, value); + return getResponse(BuilderFactory.DOUBLE); + } + public Response> hkeys(String key) { client.hkeys(key); return getResponse(BuilderFactory.STRING_SET); @@ -365,6 +375,16 @@ public class Pipeline extends Queable { return getResponse(BuilderFactory.LONG); } + public Response incrByFloat(String key, double value) { + client.incrByFloat(key, value); + return getResponse(BuilderFactory.DOUBLE); + } + + public Response incrByFloat(byte[] key, double value) { + client.incrByFloat(key, value); + return getResponse(BuilderFactory.DOUBLE); + } + public Response> keys(String pattern) { client.keys(pattern); return getResponse(BuilderFactory.STRING_SET); diff --git a/src/main/java/redis/clients/jedis/Protocol.java b/src/main/java/redis/clients/jedis/Protocol.java index b1e391d..e061ae5 100644 --- a/src/main/java/redis/clients/jedis/Protocol.java +++ b/src/main/java/redis/clients/jedis/Protocol.java @@ -144,7 +144,7 @@ public final class Protocol { } public static enum Command { - PING, SET, GET, QUIT, EXISTS, DEL, TYPE, FLUSHDB, KEYS, RANDOMKEY, RENAME, RENAMENX, RENAMEX, DBSIZE, EXPIRE, EXPIREAT, TTL, SELECT, MOVE, FLUSHALL, GETSET, MGET, SETNX, SETEX, MSET, MSETNX, DECRBY, DECR, INCRBY, INCR, APPEND, SUBSTR, HSET, HGET, HSETNX, HMSET, HMGET, HINCRBY, HEXISTS, HDEL, HLEN, HKEYS, HVALS, HGETALL, RPUSH, LPUSH, LLEN, LRANGE, LTRIM, LINDEX, LSET, LREM, LPOP, RPOP, RPOPLPUSH, SADD, SMEMBERS, SREM, SPOP, SMOVE, SCARD, SISMEMBER, SINTER, SINTERSTORE, SUNION, SUNIONSTORE, SDIFF, SDIFFSTORE, SRANDMEMBER, ZADD, ZRANGE, ZREM, ZINCRBY, ZRANK, ZREVRANK, ZREVRANGE, ZCARD, ZSCORE, MULTI, DISCARD, EXEC, WATCH, UNWATCH, SORT, BLPOP, BRPOP, AUTH, SUBSCRIBE, PUBLISH, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, ZCOUNT, ZRANGEBYSCORE, ZREVRANGEBYSCORE, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZUNIONSTORE, ZINTERSTORE, SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE, SHUTDOWN, INFO, MONITOR, SLAVEOF, CONFIG, STRLEN, SYNC, LPUSHX, PERSIST, RPUSHX, ECHO, LINSERT, DEBUG, BRPOPLPUSH, SETBIT, GETBIT, SETRANGE, GETRANGE, EVAL, EVALSHA, SCRIPT, SLOWLOG, OBJECT; + PING, SET, GET, QUIT, EXISTS, DEL, TYPE, FLUSHDB, KEYS, RANDOMKEY, RENAME, RENAMENX, RENAMEX, DBSIZE, EXPIRE, EXPIREAT, TTL, SELECT, MOVE, FLUSHALL, GETSET, MGET, SETNX, SETEX, MSET, MSETNX, DECRBY, DECR, INCRBY, INCRBYFLOAT, INCR, APPEND, SUBSTR, HSET, HGET, HSETNX, HMSET, HMGET, HINCRBY, HINCRBYFLOAT, HEXISTS, HDEL, HLEN, HKEYS, HVALS, HGETALL, RPUSH, LPUSH, LLEN, LRANGE, LTRIM, LINDEX, LSET, LREM, LPOP, RPOP, RPOPLPUSH, SADD, SMEMBERS, SREM, SPOP, SMOVE, SCARD, SISMEMBER, SINTER, SINTERSTORE, SUNION, SUNIONSTORE, SDIFF, SDIFFSTORE, SRANDMEMBER, ZADD, ZRANGE, ZREM, ZINCRBY, ZRANK, ZREVRANK, ZREVRANGE, ZCARD, ZSCORE, MULTI, DISCARD, EXEC, WATCH, UNWATCH, SORT, BLPOP, BRPOP, AUTH, SUBSCRIBE, PUBLISH, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, ZCOUNT, ZRANGEBYSCORE, ZREVRANGEBYSCORE, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZUNIONSTORE, ZINTERSTORE, SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE, SHUTDOWN, INFO, MONITOR, SLAVEOF, CONFIG, STRLEN, SYNC, LPUSHX, PERSIST, RPUSHX, ECHO, LINSERT, DEBUG, BRPOPLPUSH, SETBIT, GETBIT, SETRANGE, GETRANGE, EVAL, EVALSHA, SCRIPT, SLOWLOG, OBJECT; public final byte[] raw; diff --git a/src/main/java/redis/clients/jedis/ShardedJedis.java b/src/main/java/redis/clients/jedis/ShardedJedis.java index ea2f11e..6e45e26 100644 --- a/src/main/java/redis/clients/jedis/ShardedJedis.java +++ b/src/main/java/redis/clients/jedis/ShardedJedis.java @@ -118,6 +118,11 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands { return j.incrBy(key, integer); } + public Double incrByFloat(String key, double integer) { + Jedis j = getShard(key); + return j.incrByFloat(key, integer); + } + public Long incr(String key) { Jedis j = getShard(key); return j.incr(key); @@ -163,6 +168,11 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands { return j.hincrBy(key, field, value); } + public Double hincrByFloat(String key, String field, double value) { + Jedis j = getShard(key); + return j.hincrByFloat(key, field, value); + } + public Boolean hexists(String key, String field) { Jedis j = getShard(key); return j.hexists(key, field); diff --git a/src/main/java/redis/clients/jedis/ShardedJedisPipeline.java b/src/main/java/redis/clients/jedis/ShardedJedisPipeline.java index af416c0..e8eeed7 100644 --- a/src/main/java/redis/clients/jedis/ShardedJedisPipeline.java +++ b/src/main/java/redis/clients/jedis/ShardedJedisPipeline.java @@ -123,6 +123,13 @@ public class ShardedJedisPipeline extends Queable { return getResponse(BuilderFactory.LONG); } + public Response incrByFloat(String key, double value) { + Client c = getClient(key); + c.incrByFloat(key, value); + results.add(new FutureResult(c)); + return getResponse(BuilderFactory.DOUBLE); + } + public Response incr(String key) { Client c = getClient(key); c.incr(key); @@ -186,6 +193,13 @@ public class ShardedJedisPipeline extends Queable { return getResponse(BuilderFactory.LONG); } + public Response hincrByFloat(String key, String field, double value) { + Client c = getClient(key); + c.hincrByFloat(key, field, value); + results.add(new FutureResult(c)); + return getResponse(BuilderFactory.DOUBLE); + } + public Response hexists(String key, String field) { Client c = getClient(key); c.hexists(key, field); diff --git a/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java index fbcbca3..aa303dd 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java @@ -143,6 +143,25 @@ public class HashesCommandsTest extends JedisCommandTestBase { } + @Test + public void hincrByFloat() { + Double value = jedis.hincrByFloat("foo", "bar", 1.5d); + assertEquals((Double) 1.5d, value); + value = jedis.hincrByFloat("foo", "bar", -1.5d); + assertEquals((Double) 0d, value); + value = jedis.hincrByFloat("foo", "bar", -10.7d); + assertEquals(Double.compare(-10.7d, value), 0); + + // Binary + double bvalue = jedis.hincrByFloat(bfoo, bbar, 1.5d); + assertEquals(Double.compare(1.5d, bvalue), 0); + bvalue = jedis.hincrByFloat(bfoo, bbar, -1.5d); + assertEquals(Double.compare(0d, bvalue), 0); + bvalue = jedis.hincrByFloat(bfoo, bbar, -10.7d); + assertEquals(Double.compare(-10.7d, value), 0); + + } + @Test public void hexists() { Map hash = new HashMap(); diff --git a/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java index acee2cf..0a059cd 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java @@ -132,7 +132,7 @@ public class ScriptingCommandsTest extends JedisCommandTestBase { jedis.scriptKill(); } catch(JedisDataException e) { - assertEquals("ERR No scripts in execution right now.", e.getMessage()); + assertTrue(e.getMessage().contains("No scripts in execution right now.")); } } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/commands/StringValuesCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/StringValuesCommandsTest.java index fcf9f99..6b19d32 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/StringValuesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/StringValuesCommandsTest.java @@ -123,6 +123,22 @@ public class StringValuesCommandsTest extends JedisCommandTestBase { assertEquals(4, value); } + @Test(expected = JedisDataException.class) + public void incrByFloatWrongValue() { + jedis.set("foo", "bar"); + jedis.incrByFloat("foo", 2d); + } + + @Test + public void incrByFloat() { + Double value = jedis.incrByFloat("foo", 2d); + assertEquals((Double)2d, value); + value = jedis.incrByFloat("foo", 2.5d); + assertEquals((Double)4.5d, value); + value = jedis.incrByFloat("foo", -6.5d); + assertEquals(Double.compare(-2d, value), 0); + } + @Test(expected = JedisDataException.class) public void decrWrongValue() { jedis.set("foo", "bar"); From 5e2cdb9c088fc4c36bbf80d1d76ab414d973f4cc Mon Sep 17 00:00:00 2001 From: Darren Shepherd Date: Fri, 29 Mar 2013 22:28:01 -0700 Subject: [PATCH 002/120] When writing a negative sign the write(char) method goes directly to the output stream and by-passes the internal RedisOutputStream buffer causing random corruption of the output. Casting the char to a byte ensures write(byte) is called which will properly buffer the output. --- src/main/java/redis/clients/util/RedisOutputStream.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/redis/clients/util/RedisOutputStream.java b/src/main/java/redis/clients/util/RedisOutputStream.java index 5708d43..5398f36 100644 --- a/src/main/java/redis/clients/util/RedisOutputStream.java +++ b/src/main/java/redis/clients/util/RedisOutputStream.java @@ -187,7 +187,7 @@ public final class RedisOutputStream extends FilterOutputStream { public void writeIntCrLf(int value) throws IOException { if (value < 0) { - write('-'); + write((byte)'-'); value = -value; } From 17f6ee63dc95ddd6d9f17fbacd220212a50a4c07 Mon Sep 17 00:00:00 2001 From: Daniel Josefsson Date: Fri, 8 Nov 2013 22:25:37 +0000 Subject: [PATCH 003/120] Added support for nested lists, and longs in lists. --- src/main/java/redis/clients/jedis/Jedis.java | 11 ++++---- .../tests/commands/ScriptingCommandsTest.java | 27 +++++++++++++++---- 2 files changed, 28 insertions(+), 10 deletions(-) diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index 6d0c986..082b197 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -2783,17 +2783,18 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand } private Object getEvalResult() { - Object result = client.getOne(); - + return evalResult(client.getOne()); + } + + private Object evalResult(Object result) { if (result instanceof byte[]) return SafeEncoder.encode((byte[]) result); if (result instanceof List) { List list = (List) result; - List listResult = new ArrayList(list.size()); + List listResult = new ArrayList(list.size()); for (Object bin : list) { - listResult.add((bin == null ? null : SafeEncoder - .encode((byte[]) bin))); + listResult.add(evalResult(bin)); } return listResult; diff --git a/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java index 90677ee..354bd4f 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java @@ -1,12 +1,17 @@ package redis.clients.jedis.tests.commands; +import org.hamcrest.CoreMatchers; +import org.hamcrest.core.CombinableMatcher; +import org.junit.Test; +import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.util.SafeEncoder; + import java.util.ArrayList; import java.util.List; -import org.junit.Test; - -import redis.clients.jedis.exceptions.JedisDataException; -import redis.clients.util.SafeEncoder; +import static org.hamcrest.CoreMatchers.both; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.hasItem; public class ScriptingCommandsTest extends JedisCommandTestBase { @@ -57,6 +62,15 @@ public class ScriptingCommandsTest extends JedisCommandTestBase { assertEquals(new Long(2), response); } + @Test + public void evalNestedLists() { + String script = "return { {KEYS[1]} , {2} }"; + List results = (List) jedis.eval(script, 1, "key1"); + + assertThat((List) results.get(0), listWithItem("key1")); + assertThat((List) results.get(1), listWithItem(2L)); + } + @Test public void evalNoArgs() { String script = "return KEYS[1]"; @@ -156,7 +170,10 @@ public class ScriptingCommandsTest extends JedisCommandTestBase { assertEquals(results.get(1), "key2"); assertEquals(results.get(2), "1"); assertEquals(results.get(3), "2"); - } + + private CombinableMatcher> listWithItem(T expected) { + return both(CoreMatchers.>instanceOf(List.class)).and(hasItem(equalTo(expected))); + } } From 4fb85d0d609500fe45b0a064286e2777393b0418 Mon Sep 17 00:00:00 2001 From: Daniel Josefsson Date: Fri, 8 Nov 2013 22:54:27 +0000 Subject: [PATCH 004/120] Fixed the ordering of arguments in assertions for a couple of older tests. --- .../tests/commands/ScriptingCommandsTest.java | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java index 354bd4f..b634b2c 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java @@ -151,26 +151,26 @@ public class ScriptingCommandsTest extends JedisCommandTestBase { } } - @Test - public void scriptEvalReturnNullValues() { - String script = "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}"; - List results = (List) jedis.eval(script, 2, "key1", "key2", "1", "2"); - assertEquals(results.get(0), "key1"); - assertEquals(results.get(1), "key2"); - assertEquals(results.get(2), "1"); - assertEquals(results.get(3), "2"); - } + @Test + public void scriptEvalReturnNullValues() { + String script = "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}"; + List results = (List) jedis.eval(script, 2, "key1", "key2", "1", "2"); + assertEquals("key1", results.get(0)); + assertEquals("key2", results.get(1)); + assertEquals("1", results.get(2)); + assertEquals("2", results.get(3)); + } - @Test - public void scriptEvalShaReturnNullValues() { - String script = "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}"; - String sha = jedis.scriptLoad(script); - List results = (List) jedis.evalsha(sha, 2, "key1", "key2", "1", "2"); - assertEquals(results.get(0), "key1"); - assertEquals(results.get(1), "key2"); - assertEquals(results.get(2), "1"); - assertEquals(results.get(3), "2"); - } + @Test + public void scriptEvalShaReturnNullValues() { + String script = "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}"; + String sha = jedis.scriptLoad(script); + List results = (List) jedis.evalsha(sha, 2, "key1", "key2", "1", "2"); + assertEquals("key1", results.get(0)); + assertEquals("key2", results.get(1)); + assertEquals("1", results.get(2)); + assertEquals("2", results.get(3)); + } private CombinableMatcher> listWithItem(T expected) { return both(CoreMatchers.>instanceOf(List.class)).and(hasItem(equalTo(expected))); From 10c131bbf0629d5a1a30c7968926b9bee99cc949 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Mon, 9 Dec 2013 10:54:53 +0900 Subject: [PATCH 005/120] BinaryJedis.multi(TransactionBlock) should not call discard when exception occurred * In BinaryJedis.multi(TransactionBlock), multi & exec already fired before exception occured, so sending discard has no effect, and made another error ** add unit test (error inside TransactionBlock) *** Transaction with error - Redis discards transaction automatically (execabort) *** Transaction with error - Redis doesn't roll back (force to execute all) --- .../java/redis/clients/jedis/BinaryJedis.java | 10 ++-- .../commands/TransactionCommandsTest.java | 49 ++++++++++++++++++- 2 files changed, 51 insertions(+), 8 deletions(-) diff --git a/src/main/java/redis/clients/jedis/BinaryJedis.java b/src/main/java/redis/clients/jedis/BinaryJedis.java index 92a99a2..a7f3dba 100644 --- a/src/main/java/redis/clients/jedis/BinaryJedis.java +++ b/src/main/java/redis/clients/jedis/BinaryJedis.java @@ -1685,13 +1685,9 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey public List multi(final TransactionBlock jedisTransaction) { List results = null; jedisTransaction.setClient(client); - try { - client.multi(); - jedisTransaction.execute(); - results = jedisTransaction.exec(); - } catch (Exception ex) { - jedisTransaction.discard(); - } + client.multi(); + jedisTransaction.execute(); + results = jedisTransaction.exec(); return results; } diff --git a/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java index 565c1a4..8b1daa9 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java @@ -4,6 +4,7 @@ import java.io.IOException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashMap; import java.util.List; import java.util.Set; @@ -16,6 +17,7 @@ import redis.clients.jedis.Response; import redis.clients.jedis.Transaction; import redis.clients.jedis.TransactionBlock; import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.exceptions.JedisException; public class TransactionCommandsTest extends JedisCommandTestBase { final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; @@ -104,6 +106,50 @@ public class TransactionCommandsTest extends JedisCommandTestBase { assertEquals(expected, response); } + + @Test + public void multiBlockWithErrorRedisDiscardsTransaction() throws Exception { + // Transaction with error - Redis discards transaction automatically (Syntax Error, etc.) + TransactionBlock tb = new TransactionBlock() { + + @Override + public void execute() throws JedisException { + del("hello"); + hmset("hello", new HashMap()); + } + }; + + try { + jedis.multi(tb); + } catch (JedisDataException e) { + assertTrue(e.getMessage().contains("EXECABORT")); + } catch (Exception e) { + throw e; + } + } + + @Test + public void multiBlockWithErrorRedisForceToExecuteAllCommands() throws Exception { + // Transaction with error - Redis doesn't roll back (Type Error, Deletion of non-exist key, etc.) + jedis.del("hello2"); + TransactionBlock tb2 = new TransactionBlock() { + + @Override + public void execute() throws JedisException { + del("hello2"); + set("hello2", "hello"); + sadd("hello2", "hello2"); + } + }; + + List responses = jedis.multi(tb2); + assertEquals("OK", responses.get(1)); + assertEquals(JedisDataException.class, responses.get(2).getClass()); + + Exception exc = (JedisDataException) responses.get(2); + assertTrue(exc.getMessage().contains("WRONGTYPE")); + } + @Test public void watch() throws UnknownHostException, IOException { @@ -294,4 +340,5 @@ public class TransactionCommandsTest extends JedisCommandTestBase { assertNull(results); } -} \ No newline at end of file + +} From 3073f778b4edab3205b922c22f29cfed490c494e Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Sat, 21 Dec 2013 01:33:46 +0900 Subject: [PATCH 006/120] JedisPool / JedisSentinelPool resets returning object's state (watched, multi) * BinaryClient / BinaryJedis : added feature to reset its state (watched, multi) * JedisPool / JedisSentinelPool : calls new feature (reset state) when Jedis object returns to pool * Unit Test included --- .../redis/clients/jedis/BinaryClient.java | 20 +++++++- .../java/redis/clients/jedis/BinaryJedis.java | 5 ++ .../java/redis/clients/jedis/JedisPool.java | 1 + .../clients/jedis/JedisSentinelPool.java | 1 + .../clients/jedis/tests/JedisPoolTest.java | 22 +++++++++ .../jedis/tests/JedisSentinelPoolTest.java | 22 +++++++++ .../commands/TransactionCommandsTest.java | 46 +++++++++++++++++++ 7 files changed, 116 insertions(+), 1 deletion(-) diff --git a/src/main/java/redis/clients/jedis/BinaryClient.java b/src/main/java/redis/clients/jedis/BinaryClient.java index dff1e76..abf0dc3 100644 --- a/src/main/java/redis/clients/jedis/BinaryClient.java +++ b/src/main/java/redis/clients/jedis/BinaryClient.java @@ -29,15 +29,21 @@ public class BinaryClient extends Connection { } private boolean isInMulti; - + private String password; private long db; + private boolean isInWatch; + public boolean isInMulti() { return isInMulti; } + public boolean isInWatch() { + return isInWatch; + } + public BinaryClient(final String host) { super(host); } @@ -447,19 +453,23 @@ public class BinaryClient extends Connection { public void discard() { sendCommand(DISCARD); isInMulti = false; + isInWatch = false; } public void exec() { sendCommand(EXEC); isInMulti = false; + isInWatch = false; } public void watch(final byte[]... keys) { sendCommand(WATCH, keys); + isInWatch = true; } public void unwatch() { sendCommand(UNWATCH); + isInWatch = false; } public void sort(final byte[] key) { @@ -912,6 +922,14 @@ public class BinaryClient extends Connection { db = 0; super.disconnect(); } + + public void resetState() { + if (isInMulti()) + discard(); + + if (isInWatch()) + unwatch(); + } private void sendEvalCommand(Command command, byte[] script, byte[] keyCount, byte[][] params) { diff --git a/src/main/java/redis/clients/jedis/BinaryJedis.java b/src/main/java/redis/clients/jedis/BinaryJedis.java index 92a99a2..6a318ce 100644 --- a/src/main/java/redis/clients/jedis/BinaryJedis.java +++ b/src/main/java/redis/clients/jedis/BinaryJedis.java @@ -1709,6 +1709,11 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey public void disconnect() { client.disconnect(); } + + public void resetState() { + client.resetState(); + client.getAll(); + } public String watch(final byte[]... keys) { client.watch(keys); diff --git a/src/main/java/redis/clients/jedis/JedisPool.java b/src/main/java/redis/clients/jedis/JedisPool.java index 58212ba..946863b 100644 --- a/src/main/java/redis/clients/jedis/JedisPool.java +++ b/src/main/java/redis/clients/jedis/JedisPool.java @@ -84,6 +84,7 @@ public class JedisPool extends Pool { } public void returnResource(final Jedis resource) { + resource.resetState(); returnResourceObject(resource); } } diff --git a/src/main/java/redis/clients/jedis/JedisSentinelPool.java b/src/main/java/redis/clients/jedis/JedisSentinelPool.java index e4c6e3b..9190225 100644 --- a/src/main/java/redis/clients/jedis/JedisSentinelPool.java +++ b/src/main/java/redis/clients/jedis/JedisSentinelPool.java @@ -79,6 +79,7 @@ public class JedisSentinelPool extends Pool { } public void returnResource(final Jedis resource) { + resource.resetState(); returnResourceObject(resource); } diff --git a/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java b/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java index 652de92..c62e3bd 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java @@ -11,6 +11,7 @@ import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; +import redis.clients.jedis.Transaction; import redis.clients.jedis.exceptions.JedisConnectionException; public class JedisPoolTest extends Assert { @@ -176,4 +177,25 @@ public class JedisPoolTest extends Assert { pool0.returnResource(jedis); pool0.destroy(); } + + @Test + public void returnResourceShouldResetState() { + GenericObjectPoolConfig config = new GenericObjectPoolConfig(); + config.setMaxTotal(1); + config.setBlockWhenExhausted(false); + JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(), + 2000, "foobared"); + + Jedis jedis = pool.getResource(); + jedis.set("hello", "jedis"); + Transaction t = jedis.multi(); + t.set("hello", "world"); + pool.returnResource(jedis); + + Jedis jedis2 = pool.getResource(); + assertTrue(jedis == jedis2); + assertEquals("jedis", jedis2.get("hello")); + pool.returnResource(jedis2); + pool.destroy(); + } } diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java index c3a72a0..c0752e2 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java @@ -11,8 +11,10 @@ import org.junit.Test; import redis.clients.jedis.DebugParams; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPubSub; import redis.clients.jedis.JedisSentinelPool; +import redis.clients.jedis.Transaction; public class JedisSentinelPoolTest extends JedisTestBase { private static final String MASTER_NAME = "mymaster"; @@ -149,4 +151,24 @@ public class JedisSentinelPoolTest extends JedisTestBase { } } + @Test + public void returnResourceShouldResetState() { + GenericObjectPoolConfig config = new GenericObjectPoolConfig(); + config.setMaxTotal(1); + config.setBlockWhenExhausted(false); + JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels, + config, 1000, "foobared", 2); + + Jedis jedis = pool.getResource(); + jedis.set("hello", "jedis"); + Transaction t = jedis.multi(); + t.set("hello", "world"); + pool.returnResource(jedis); + + Jedis jedis2 = pool.getResource(); + assertTrue(jedis == jedis2); + assertEquals("jedis", jedis2.get("hello")); + pool.returnResource(jedis2); + pool.destroy(); + } } diff --git a/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java index 565c1a4..fb52063 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java @@ -12,10 +12,12 @@ import org.junit.Test; import redis.clients.jedis.Jedis; import redis.clients.jedis.Protocol.Keyword; +import redis.clients.jedis.Pipeline; import redis.clients.jedis.Response; import redis.clients.jedis.Transaction; import redis.clients.jedis.TransactionBlock; import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.exceptions.JedisException; public class TransactionCommandsTest extends JedisCommandTestBase { final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; @@ -294,4 +296,48 @@ public class TransactionCommandsTest extends JedisCommandTestBase { assertNull(results); } + + @Test + public void testResetStateWhenInMulti() { + jedis.auth("foobared"); + + Transaction t = jedis.multi(); + t.set("foooo", "barrr"); + + jedis.resetState(); + assertEquals(null, jedis.get("foooo")); + } + + @Test + public void testResetStateWhenInMultiWithinPipeline() { + jedis.auth("foobared"); + + Pipeline p = jedis.pipelined(); + p.multi(); + p.set("foooo", "barrr"); + + jedis.resetState(); + assertEquals(null, jedis.get("foooo")); + } + + @Test + public void testResetStateWhenInWatch() { + jedis.watch("mykey", "somekey"); + + // state reset : unwatch + jedis.resetState(); + + Transaction t = jedis.multi(); + + nj.connect(); + nj.auth("foobared"); + nj.set("mykey", "bar"); + nj.disconnect(); + + t.set("mykey", "foo"); + List resp = t.exec(); + assertNotNull(resp); + assertEquals(1, resp.size()); + assertEquals("foo", jedis.get("mykey")); + } } \ No newline at end of file From 53b3e041f3346e4c3ab879decc27673e9344a066 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Mon, 23 Dec 2013 14:19:28 +0900 Subject: [PATCH 007/120] Fix BinaryJedis.eval() method bug (argument) * append unit test for BinaryJedis --- .../java/redis/clients/jedis/BinaryJedis.java | 3 +- .../tests/commands/ScriptingCommandsTest.java | 33 +++++++++++++++++-- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/main/java/redis/clients/jedis/BinaryJedis.java b/src/main/java/redis/clients/jedis/BinaryJedis.java index 92a99a2..2b469d0 100644 --- a/src/main/java/redis/clients/jedis/BinaryJedis.java +++ b/src/main/java/redis/clients/jedis/BinaryJedis.java @@ -3140,12 +3140,13 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey private byte[][] getParams(List keys, List args) { int keyCount = keys.size(); + int argCount = args.size(); byte[][] params = new byte[keyCount + args.size()][]; for (int i = 0; i < keyCount; i++) params[i] = keys.get(i); - for (int i = 0; i < keys.size(); i++) + for (int i = 0; i < argCount; i++) params[keyCount + i] = args.get(i); return params; diff --git a/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java index 90677ee..aca4899 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java @@ -5,6 +5,7 @@ import java.util.List; import org.junit.Test; +import redis.clients.jedis.BinaryJedis; import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.util.SafeEncoder; @@ -13,7 +14,7 @@ public class ScriptingCommandsTest extends JedisCommandTestBase { @SuppressWarnings("unchecked") @Test public void evalMultiBulk() { - String script = "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}"; + String script = "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2],ARGV[3]}"; List keys = new ArrayList(); keys.add("key1"); keys.add("key2"); @@ -21,14 +22,42 @@ public class ScriptingCommandsTest extends JedisCommandTestBase { List args = new ArrayList(); args.add("first"); args.add("second"); + args.add("third"); List response = (List) jedis.eval(script, keys, args); - assertEquals(4, response.size()); + assertEquals(5, response.size()); assertEquals("key1", response.get(0)); assertEquals("key2", response.get(1)); assertEquals("first", response.get(2)); assertEquals("second", response.get(3)); + assertEquals("third", response.get(4)); + } + + @SuppressWarnings("unchecked") + @Test + public void evalMultiBulkWithBinaryJedis() { + String script = "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2],ARGV[3]}"; + List keys = new ArrayList(); + keys.add("key1".getBytes()); + keys.add("key2".getBytes()); + + List args = new ArrayList(); + args.add("first".getBytes()); + args.add("second".getBytes()); + args.add("third".getBytes()); + + BinaryJedis binaryJedis = new BinaryJedis(hnp.getHost(), hnp.getPort(), 500); + binaryJedis.connect(); + binaryJedis.auth("foobared"); + + List responses = (List) binaryJedis.eval(script.getBytes(), keys, args); + assertEquals(5, responses.size()); + assertEquals("key1", new String(responses.get(0))); + assertEquals("key2", new String(responses.get(1))); + assertEquals("first", new String(responses.get(2))); + assertEquals("second", new String(responses.get(3))); + assertEquals("third", new String(responses.get(4))); } @Test From f11c1622de1d529cad509b7793977714229f4883 Mon Sep 17 00:00:00 2001 From: Darren Shepherd Date: Thu, 16 Jan 2014 21:57:22 -0700 Subject: [PATCH 008/120] Allow safe multi-threaded access to JedisPubSub If Thread A calls a subscribe method on Jedis it will block on a socket read call waiting for messages or subscription notifications. Thread B is now free to call additional methods on JedisPubSub to change the current subscriptions that thread A is waiting for. Essentially Thread A will do reads on the socket and Thread B will do writes. An issue occurs in that while Thread A is doing reads, in the getObjectMultiBulkReply() method there is an implicit flush() call. This means both Thread A and Thread B may do a write to the socket. Under this situation if Thread A does a flush while Thread B is writing the internal buffer will be corrupted. The fix is to make thread A never call flush(). This allows Thread A to be solely reads and Thread B to be solely writes. Additionally since Thread B is sending commands, the internal pipeline count is incremented and never decremented. So when Thread A terminates it's read it resets the pipeline count. --- .../java/redis/clients/jedis/Connection.java | 10 +++++- .../java/redis/clients/jedis/JedisPubSub.java | 34 +++++++++++++++++-- 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/src/main/java/redis/clients/jedis/Connection.java b/src/main/java/redis/clients/jedis/Connection.java index 1c42b94..9d4c762 100644 --- a/src/main/java/redis/clients/jedis/Connection.java +++ b/src/main/java/redis/clients/jedis/Connection.java @@ -202,11 +202,19 @@ public class Connection { return (List) Protocol.read(inputStream); } + public void resetPipelinedCount() { + pipelinedCommands = 0; + } + @SuppressWarnings("unchecked") + public List getRawObjectMultiBulkReply() { + return (List) Protocol.read(inputStream); + } + public List getObjectMultiBulkReply() { flush(); pipelinedCommands--; - return (List) Protocol.read(inputStream); + return getRawObjectMultiBulkReply(); } @SuppressWarnings("unchecked") diff --git a/src/main/java/redis/clients/jedis/JedisPubSub.java b/src/main/java/redis/clients/jedis/JedisPubSub.java index d07a409..41ae53b 100644 --- a/src/main/java/redis/clients/jedis/JedisPubSub.java +++ b/src/main/java/redis/clients/jedis/JedisPubSub.java @@ -16,7 +16,7 @@ import redis.clients.util.SafeEncoder; public abstract class JedisPubSub { private int subscribedChannels = 0; - private Client client; + private volatile Client client; public abstract void onMessage(String channel, String message); @@ -41,26 +41,46 @@ public abstract class JedisPubSub { } public void unsubscribe(String... channels) { + if (client == null) { + throw new JedisConnectionException( + "JedisPubSub is not subscribed to a Jedis instance."); + } client.unsubscribe(channels); client.flush(); } public void subscribe(String... channels) { + if (client == null) { + throw new JedisConnectionException( + "JedisPubSub is not subscribed to a Jedis instance."); + } client.subscribe(channels); client.flush(); } public void psubscribe(String... patterns) { + if (client == null) { + throw new JedisConnectionException( + "JedisPubSub is not subscribed to a Jedis instance."); + } client.psubscribe(patterns); client.flush(); } public void punsubscribe() { + if (client == null) { + throw new JedisConnectionException( + "JedisPubSub is not subscribed to a Jedis instance."); + } client.punsubscribe(); client.flush(); } public void punsubscribe(String... patterns) { + if (client == null) { + throw new JedisConnectionException( + "JedisPubSub is not subscribed to a Jedis instance."); + } client.punsubscribe(patterns); client.flush(); } @@ -85,7 +105,7 @@ public abstract class JedisPubSub { private void process(Client client) { do { - List reply = client.getObjectMultiBulkReply(); + List reply = client.getRawObjectMultiBulkReply(); final Object firstObj = reply.get(0); if (!(firstObj instanceof byte[])) { throw new JedisException("Unknown message type: " + firstObj); @@ -138,9 +158,17 @@ public abstract class JedisPubSub { throw new JedisException("Unknown message type: " + firstObj); } } while (isSubscribed()); + + /* Invalidate instance since this thread is no longer listening */ + this.client = null; + + /* Reset pipeline count because subscribe() calls would have + * increased it but nothing decremented it. + */ + client.resetPipelinedCount(); } public int getSubscribedChannels() { return subscribedChannels; } -} \ No newline at end of file +} From a50cf3b15e36c78023baf85894c721fc612f041e Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Wed, 22 Jan 2014 00:23:40 +0900 Subject: [PATCH 009/120] Apply Sentinel runtime configuration API introduced on Redis 2.8.4 * Implements new sentinel commands (failover, monitor, remove, set) * unit test included ** added 2 redis-server and 1 sentinel for failover test * with some refactoring ** SentinelCommands : refactor to have interface ** HostAndPortUtil : same format to cluster setup --- Makefile | 50 +++++++ pom.xml | 4 +- src/main/java/redis/clients/jedis/Jedis.java | 38 ++++- .../java/redis/clients/jedis/Protocol.java | 4 + .../redis/clients/jedis/SentinelCommands.java | 22 +++ .../clients/jedis/tests/HostAndPortUtil.java | 48 ++----- .../jedis/tests/JedisSentinelTest.java | 136 +++++++++++++++--- .../tests/utils/JedisSentinelTestUtil.java | 7 +- 8 files changed, 244 insertions(+), 65 deletions(-) create mode 100644 src/main/java/redis/clients/jedis/SentinelCommands.java diff --git a/Makefile b/Makefile index e00fb83..b1d4507 100644 --- a/Makefile +++ b/Makefile @@ -65,6 +65,29 @@ appendonly no slaveof localhost 6379 endef +define REDIS7_CONF +daemonize yes +port 6385 +requirepass foobared +masterauth foobared +pidfile /tmp/redis7.pid +logfile /tmp/redis7.log +save "" +appendonly no +endef + +define REDIS8_CONF +daemonize yes +port 6386 +requirepass foobared +masterauth foobared +pidfile /tmp/redis8.pid +logfile /tmp/redis8.log +save "" +appendonly no +slaveof localhost 6385 +endef + # SENTINELS define REDIS_SENTINEL1 port 26379 @@ -102,6 +125,18 @@ pidfile /tmp/sentinel3.pid logfile /tmp/sentinel3.log endef +define REDIS_SENTINEL4 +port 26382 +daemonize yes +sentinel monitor mymasterfailover 127.0.0.1 6385 1 +sentinel auth-pass mymasterfailover foobared +sentinel down-after-milliseconds mymasterfailover 3000 +sentinel failover-timeout mymasterfailover 900000 +sentinel parallel-syncs mymasterfailover 1 +pidfile /tmp/sentinel4.pid +logfile /tmp/sentinel4.log +endef + # CLUSTER REDIS NODES define REDIS_CLUSTER_NODE1_CONF daemonize yes @@ -142,9 +177,12 @@ export REDIS3_CONF export REDIS4_CONF export REDIS5_CONF export REDIS6_CONF +export REDIS7_CONF +export REDIS8_CONF export REDIS_SENTINEL1 export REDIS_SENTINEL2 export REDIS_SENTINEL3 +export REDIS_SENTINEL4 export REDIS_CLUSTER_NODE1_CONF export REDIS_CLUSTER_NODE2_CONF export REDIS_CLUSTER_NODE3_CONF @@ -156,17 +194,22 @@ start: cleanup echo "$$REDIS4_CONF" | redis-server - echo "$$REDIS5_CONF" | redis-server - echo "$$REDIS6_CONF" | redis-server - + echo "$$REDIS7_CONF" | redis-server - + echo "$$REDIS8_CONF" | redis-server - echo "$$REDIS_SENTINEL1" > /tmp/sentinel1.conf && redis-server /tmp/sentinel1.conf --sentinel @sleep 0.5 echo "$$REDIS_SENTINEL2" > /tmp/sentinel2.conf && redis-server /tmp/sentinel2.conf --sentinel @sleep 0.5 echo "$$REDIS_SENTINEL3" > /tmp/sentinel3.conf && redis-server /tmp/sentinel3.conf --sentinel + @sleep 0.5 + echo "$$REDIS_SENTINEL4" > /tmp/sentinel4.conf && redis-server /tmp/sentinel4.conf --sentinel echo "$$REDIS_CLUSTER_NODE1_CONF" | redis-server - echo "$$REDIS_CLUSTER_NODE2_CONF" | redis-server - echo "$$REDIS_CLUSTER_NODE3_CONF" | redis-server - cleanup: rm -vf /tmp/redis_cluster_node*.conf + rm -vf /tmp/sentinel*.conf stop: kill `cat /tmp/redis1.pid` @@ -176,12 +219,19 @@ stop: kill `cat /tmp/redis4.pid` || true kill `cat /tmp/redis5.pid` || true kill `cat /tmp/redis6.pid` || true + kill `cat /tmp/redis7.pid` + kill `cat /tmp/redis8.pid` kill `cat /tmp/sentinel1.pid` kill `cat /tmp/sentinel2.pid` kill `cat /tmp/sentinel3.pid` + kill `cat /tmp/sentinel4.pid` kill `cat /tmp/redis_cluster_node1.pid` || true kill `cat /tmp/redis_cluster_node2.pid` || true kill `cat /tmp/redis_cluster_node3.pid` || true + rm -f /tmp/sentinel1.conf + rm -f /tmp/sentinel2.conf + rm -f /tmp/sentinel3.conf + rm -f /tmp/sentinel4.conf rm -f /tmp/redis_cluster_node1.conf rm -f /tmp/redis_cluster_node2.conf rm -f /tmp/redis_cluster_node3.conf diff --git a/pom.xml b/pom.xml index f6575eb..58c250d 100644 --- a/pom.xml +++ b/pom.xml @@ -45,8 +45,8 @@ - localhost:6379,localhost:6380,localhost:6381,localhost:6382,localhost:6383,localhost:6384 - localhost:26379,localhost:26380,localhost:26381 + localhost:6379,localhost:6380,localhost:6381,localhost:6382,localhost:6383,localhost:6384,localhost:6385,localhost:6386 + localhost:26379,localhost:26380,localhost:26381,localhost:26382 localhost:7379,localhost:7380,localhost:7381 github diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index f5f6bdd..abfeaf9 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -8,15 +8,14 @@ import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Set; import redis.clients.jedis.BinaryClient.LIST_POSITION; import redis.clients.util.SafeEncoder; import redis.clients.util.Slowlog; -import java.net.URI; -import java.util.*; -public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommands, AdvancedJedisCommands, ScriptingCommands, BasicCommands, ClusterCommands { +public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommands, AdvancedJedisCommands, ScriptingCommands, BasicCommands, ClusterCommands, SentinelCommands { public Jedis(final String host) { super(host); } @@ -3006,6 +3005,38 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand return slaves; } + public String sentinelFailover(String masterName) { + client.sentinel(Protocol.SENTINEL_FAILOVER, masterName); + return client.getStatusCodeReply(); + } + + public String sentinelMonitor(String masterName, String ip, int port, + int quorum) { + client.sentinel(Protocol.SENTINEL_MONITOR, masterName, ip, String.valueOf(port), String.valueOf(quorum)); + return client.getStatusCodeReply(); + } + + public String sentinelRemove(String masterName) { + client.sentinel(Protocol.SENTINEL_REMOVE, masterName); + return client.getStatusCodeReply(); + } + + public String sentinelSet(String masterName, Map parameterMap) { + int index = 0; + int paramsLength = parameterMap.size() * 2 + 2; + String[] params = new String[paramsLength]; + + params[index++] = Protocol.SENTINEL_SET; + params[index++] = masterName; + for (Entry entry : parameterMap.entrySet()) { + params[index++] = entry.getKey(); + params[index++] = entry.getValue(); + } + + client.sentinel(params); + return client.getStatusCodeReply(); + } + public byte[] dump(final String key) { checkIsInMulti(); client.dump(key); @@ -3214,4 +3245,5 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand client.asking(); return client.getStatusCodeReply(); } + } diff --git a/src/main/java/redis/clients/jedis/Protocol.java b/src/main/java/redis/clients/jedis/Protocol.java index a5e08c6..c1cb39c 100644 --- a/src/main/java/redis/clients/jedis/Protocol.java +++ b/src/main/java/redis/clients/jedis/Protocol.java @@ -33,6 +33,10 @@ public final class Protocol { public static final String SENTINEL_GET_MASTER_ADDR_BY_NAME = "get-master-addr-by-name"; public static final String SENTINEL_RESET = "reset"; public static final String SENTINEL_SLAVES = "slaves"; + public static final String SENTINEL_FAILOVER = "failover"; + public static final String SENTINEL_MONITOR = "monitor"; + public static final String SENTINEL_REMOVE = "remove"; + public static final String SENTINEL_SET = "set"; public static final String CLUSTER_NODES = "nodes"; public static final String CLUSTER_MEET = "meet"; diff --git a/src/main/java/redis/clients/jedis/SentinelCommands.java b/src/main/java/redis/clients/jedis/SentinelCommands.java new file mode 100644 index 0000000..21ef3f9 --- /dev/null +++ b/src/main/java/redis/clients/jedis/SentinelCommands.java @@ -0,0 +1,22 @@ +package redis.clients.jedis; + +import java.util.List; +import java.util.Map; + +public interface SentinelCommands { + public List> sentinelMasters(); + + public List sentinelGetMasterAddrByName(String masterName); + + public Long sentinelReset(String pattern); + + public List> sentinelSlaves(String masterName); + + public String sentinelFailover(String masterName); + + public String sentinelMonitor(String masterName, String ip, int port, int quorum); + + public String sentinelRemove(String masterName); + + public String sentinelSet(String masterName, Map parameterMap); +} diff --git a/src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java b/src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java index c7be599..491f0a3 100644 --- a/src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java +++ b/src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java @@ -12,42 +12,18 @@ public class HostAndPortUtil { private static List clusterHostAndPortList = new ArrayList(); static { - - HostAndPort defaulthnp1 = new HostAndPort("localhost", - Protocol.DEFAULT_PORT); - redisHostAndPortList.add(defaulthnp1); - - HostAndPort defaulthnp2 = new HostAndPort("localhost", - Protocol.DEFAULT_PORT + 1); - redisHostAndPortList.add(defaulthnp2); - - HostAndPort defaulthnp3 = new HostAndPort("localhost", - Protocol.DEFAULT_PORT + 2); - redisHostAndPortList.add(defaulthnp3); - - HostAndPort defaulthnp4 = new HostAndPort("localhost", - Protocol.DEFAULT_PORT + 3); - redisHostAndPortList.add(defaulthnp4); - - HostAndPort defaulthnp5 = new HostAndPort("localhost", - Protocol.DEFAULT_PORT + 4); - redisHostAndPortList.add(defaulthnp5); - - HostAndPort defaulthnp6 = new HostAndPort("localhost", - Protocol.DEFAULT_PORT + 5); - redisHostAndPortList.add(defaulthnp6); - - HostAndPort defaulthnp7 = new HostAndPort("localhost", - Protocol.DEFAULT_SENTINEL_PORT); - sentinelHostAndPortList.add(defaulthnp7); - - HostAndPort defaulthnp8 = new HostAndPort("localhost", - Protocol.DEFAULT_SENTINEL_PORT + 1); - sentinelHostAndPortList.add(defaulthnp8); - - HostAndPort defaulthnp9 = new HostAndPort("localhost", - Protocol.DEFAULT_SENTINEL_PORT + 2); - sentinelHostAndPortList.add(defaulthnp9); + redisHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_PORT)); + redisHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_PORT + 1)); + redisHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_PORT + 2)); + redisHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_PORT + 3)); + redisHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_PORT + 4)); + redisHostAndPortList.add(new HostAndPort("localhost", 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", 7380)); diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java b/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java index f8267c8..ad70954 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java @@ -1,5 +1,6 @@ package redis.clients.jedis.tests; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -9,24 +10,28 @@ import org.junit.Test; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; +import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.tests.utils.JedisSentinelTestUtil; public class JedisSentinelTest extends JedisTestBase { private static final String MASTER_NAME = "mymaster"; + private static final String MONITOR_MASTER_NAME = "mymastermonitor"; + private static final String REMOVE_MASTER_NAME = "mymasterremove"; + private static final String FAILOVER_MASTER_NAME = "mymasterfailover"; + private static final String MASTER_IP = "127.0.0.1"; protected static HostAndPort master = HostAndPortUtil.getRedisServers() .get(0); - protected static HostAndPort slave = HostAndPortUtil.getRedisServers().get( - 5); + protected static HostAndPort slave = HostAndPortUtil.getRedisServers().get(5); protected static HostAndPort sentinel = HostAndPortUtil .getSentinelServers().get(0); - - protected static Jedis masterJedis; - protected static Jedis slaveJedis; - protected static Jedis sentinelJedis; - + + protected static HostAndPort sentinelForFailover = HostAndPortUtil.getSentinelServers() + .get(3); + protected static HostAndPort masterForFailover = HostAndPortUtil.getRedisServers().get(6); + @Before public void setup() throws InterruptedException { - } @After @@ -36,30 +41,117 @@ public class JedisSentinelTest extends JedisTestBase { // to restore it (demote) // so, promote(slaveof) slave to master has no effect, not same to old // Sentinel's behavior + ensureRemoved(MONITOR_MASTER_NAME); + ensureRemoved(REMOVE_MASTER_NAME); } @Test public void sentinel() { - Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); + Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); List> masters = j.sentinelMasters(); - final String masterName = masters.get(0).get("name"); - - assertEquals(MASTER_NAME, masterName); - - List masterHostAndPort = j - .sentinelGetMasterAddrByName(masterName); + + boolean inMasters = false; + for (Map master : masters) + if (MASTER_NAME.equals(master.get("name"))) + inMasters = true; + + assertTrue(inMasters); + + List masterHostAndPort = j.sentinelGetMasterAddrByName(MASTER_NAME); HostAndPort masterFromSentinel = new HostAndPort( masterHostAndPort.get(0), Integer.parseInt(masterHostAndPort .get(1))); assertEquals(master, masterFromSentinel); - - List> slaves = j.sentinelSlaves(masterName); + + List> slaves = j.sentinelSlaves(MASTER_NAME); assertTrue(slaves.size() > 0); - assertEquals(master.getPort(), - Integer.parseInt(slaves.get(0).get("master-port"))); - + assertEquals(master.getPort(), Integer.parseInt(slaves.get(0).get("master-port"))); + // DO NOT RE-RUN TEST TOO FAST, RESET TAKES SOME TIME TO... RESET - assertEquals(Long.valueOf(1), j.sentinelReset(masterName)); - assertEquals(Long.valueOf(0), j.sentinelReset("woof" + masterName)); + assertEquals(Long.valueOf(1), j.sentinelReset(MASTER_NAME)); + assertEquals(Long.valueOf(0), j.sentinelReset("woof" + MASTER_NAME)); } + + @Test + public void sentinelFailover() throws InterruptedException { + Jedis j = new Jedis(sentinelForFailover.getHost(), sentinelForFailover.getPort()); + + HostAndPort currentMaster = new HostAndPort(masterForFailover.getHost(), masterForFailover.getPort()); + + List masterHostAndPort = j.sentinelGetMasterAddrByName(FAILOVER_MASTER_NAME); + String result = j.sentinelFailover(FAILOVER_MASTER_NAME); + assertEquals("OK", result); + + JedisSentinelTestUtil.waitForNewPromotedMaster(sentinelForFailover, FAILOVER_MASTER_NAME, currentMaster); + + masterHostAndPort = j.sentinelGetMasterAddrByName(FAILOVER_MASTER_NAME); + HostAndPort newMaster = new HostAndPort(masterHostAndPort.get(0), + Integer.parseInt(masterHostAndPort.get(1))); + + assertNotEquals(newMaster, currentMaster); + } + + @Test + public void sentinelMonitor() { + Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); + + // monitor new master + String result = j.sentinelMonitor(MONITOR_MASTER_NAME, MASTER_IP, master.getPort(), 1); + assertEquals("OK", result); + + // already monitored + try { + j.sentinelMonitor(MONITOR_MASTER_NAME, MASTER_IP, master.getPort(), 1); + fail(); + } catch (JedisDataException e) { + // pass + } + } + + @Test + public void sentinelRemove() { + Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); + + ensureMonitored(sentinel, REMOVE_MASTER_NAME, MASTER_IP, master.getPort(), 1); + + String result = j.sentinelRemove(REMOVE_MASTER_NAME); + assertEquals("OK", result); + + // not exist + try { + result = j.sentinelRemove(REMOVE_MASTER_NAME); + assertNotEquals("OK", result); + fail(); + } catch (JedisDataException e) { + // pass + } + } + + @Test + public void sentinelSet() { + Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); + + Map parameterMap = new HashMap(); + parameterMap.put("down-after-milliseconds", String.valueOf(3000)); + parameterMap.put("parallel-syncs", String.valueOf(1)); + j.sentinelSet(MASTER_NAME, parameterMap); + + // cannot test "sentinel set" because there is no command "sentinel get" + } + + private void ensureMonitored(HostAndPort sentinel, String masterName, String ip, int port, int quorum) { + Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); + try { + j.sentinelMonitor(masterName, ip, port, quorum); + } catch (JedisDataException e) { + } + } + + private void ensureRemoved(String masterName) { + Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); + try { + j.sentinelRemove(masterName); + } catch (JedisDataException e) { + } + } } diff --git a/src/test/java/redis/clients/jedis/tests/utils/JedisSentinelTestUtil.java b/src/test/java/redis/clients/jedis/tests/utils/JedisSentinelTestUtil.java index cd8fdc6..9ac4a85 100644 --- a/src/test/java/redis/clients/jedis/tests/utils/JedisSentinelTestUtil.java +++ b/src/test/java/redis/clients/jedis/tests/utils/JedisSentinelTestUtil.java @@ -46,8 +46,11 @@ public class JedisSentinelTestUtil { List sentinelMasterInfos = sentinelJedis .sentinelGetMasterAddrByName(masterName); - if (sentinelMasterInfos == null) - continue; + if (sentinelMasterInfos == null) { + System.out + .println("Cannot retrieve Sentinel's master address info, sleep..."); + continue; + } newMaster = new HostAndPort(sentinelMasterInfos.get(0), Integer.parseInt(sentinelMasterInfos.get(1))); From 68356eb8022ebbe54342dc32e567b78951a79635 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Wed, 22 Jan 2014 00:40:37 +0900 Subject: [PATCH 010/120] make sentinel set command unit test stronger --- .../redis/clients/jedis/tests/JedisSentinelTest.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java b/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java index ad70954..833151e 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java @@ -132,11 +132,17 @@ public class JedisSentinelTest extends JedisTestBase { Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); Map parameterMap = new HashMap(); - parameterMap.put("down-after-milliseconds", String.valueOf(3000)); - parameterMap.put("parallel-syncs", String.valueOf(1)); + parameterMap.put("down-after-milliseconds", String.valueOf(1234)); + parameterMap.put("parallel-syncs", String.valueOf(3)); j.sentinelSet(MASTER_NAME, parameterMap); - // cannot test "sentinel set" because there is no command "sentinel get" + List> masters = j.sentinelMasters(); + for (Map master : masters) { + if (master.get("name").equals(MASTER_NAME)) { + assertEquals(1234, Integer.parseInt(master.get("down-after-milliseconds"))); + assertEquals(3, Integer.parseInt(master.get("parallel-syncs"))); + } + } } private void ensureMonitored(HostAndPort sentinel, String masterName, String ip, int port, int quorum) { From 5f5b80e6e33f93b99874de71174a2297256d0abe Mon Sep 17 00:00:00 2001 From: Mayank Kakodkar Date: Thu, 23 Jan 2014 21:03:46 +0530 Subject: [PATCH 011/120] Corrected documentation for Jedis.get(), it returns a Java null, not (nil) --- src/main/java/redis/clients/jedis/Jedis.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index f5f6bdd..2503d50 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -71,8 +71,8 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand } /** - * Get the value of the specified key. If the key does not exist the special - * value 'nil' is returned. If the value stored at key is not a string an + * Get the value of the specified key. If the key does not exist null + * is returned. If the value stored at key is not a string an * error is returned because GET can only handle string values. *

* Time complexity: O(1) From b05d9adfb0c4a9fe430149bc75f0615ad9a56f97 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Sun, 26 Jan 2014 13:53:34 -0300 Subject: [PATCH 012/120] Change zadd parameter order to allow duplicated scoremembers but not members --- .../redis/clients/jedis/BinaryClient.java | 27 +++++++-------- .../java/redis/clients/jedis/BinaryJedis.java | 2 +- .../clients/jedis/BinaryJedisCommands.java | 34 ++++++++++--------- .../clients/jedis/BinaryShardedJedis.java | 2 +- src/main/java/redis/clients/jedis/Client.java | 18 +++++----- .../java/redis/clients/jedis/Commands.java | 4 +-- src/main/java/redis/clients/jedis/Jedis.java | 8 ++--- .../redis/clients/jedis/JedisCluster.java | 2 +- .../redis/clients/jedis/JedisCommands.java | 2 +- .../redis/clients/jedis/PipelineBase.java | 2 +- .../redis/clients/jedis/ShardedJedis.java | 8 ++--- .../tests/commands/VariadicCommandsTest.java | 20 +++++------ 12 files changed, 66 insertions(+), 63 deletions(-) diff --git a/src/main/java/redis/clients/jedis/BinaryClient.java b/src/main/java/redis/clients/jedis/BinaryClient.java index f1b167a..5e20ce1 100644 --- a/src/main/java/redis/clients/jedis/BinaryClient.java +++ b/src/main/java/redis/clients/jedis/BinaryClient.java @@ -376,23 +376,22 @@ public class BinaryClient extends Connection { public void zadd(final byte[] key, final double score, final byte[] member) { sendCommand(ZADD, key, toByteArray(score), member); } + + public void zaddBinary(final byte[] key, final Map< byte[], Double> scoreMembers) { + + ArrayList args = new ArrayList(scoreMembers.size() * 2 + 1); + args.add(key); - public void zaddBinary(final byte[] key, Map scoreMembers) { - ArrayList args = new ArrayList( - scoreMembers.size() * 2 + 1); + for (Map.Entry entry : scoreMembers.entrySet()) { + args.add(toByteArray(entry.getValue())); + args.add(entry.getKey()); + } - args.add(key); + byte[][] argsArray = new byte[args.size()][]; + args.toArray(argsArray); - for (Map.Entry entry : scoreMembers.entrySet()) { - args.add(toByteArray(entry.getKey())); - args.add(entry.getValue()); - } - - byte[][] argsArray = new byte[args.size()][]; - args.toArray(argsArray); - - sendCommand(ZADD, argsArray); - } + sendCommand(ZADD, argsArray); + } public void zrange(final byte[] key, final long start, final long end) { sendCommand(ZRANGE, key, toByteArray(start), toByteArray(end)); diff --git a/src/main/java/redis/clients/jedis/BinaryJedis.java b/src/main/java/redis/clients/jedis/BinaryJedis.java index 7c7debf..0aebaf5 100644 --- a/src/main/java/redis/clients/jedis/BinaryJedis.java +++ b/src/main/java/redis/clients/jedis/BinaryJedis.java @@ -1502,7 +1502,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey return client.getIntegerReply(); } - public Long zadd(final byte[] key, final Map scoreMembers) { + public Long zadd(final byte[] key, final Map scoreMembers) { checkIsInMulti(); client.zaddBinary(key, scoreMembers); return client.getIntegerReply(); diff --git a/src/main/java/redis/clients/jedis/BinaryJedisCommands.java b/src/main/java/redis/clients/jedis/BinaryJedisCommands.java index aed3011..3e44f9c 100644 --- a/src/main/java/redis/clients/jedis/BinaryJedisCommands.java +++ b/src/main/java/redis/clients/jedis/BinaryJedisCommands.java @@ -5,6 +5,8 @@ import java.util.List; import java.util.Map; import java.util.Set; +import redis.clients.jedis.BinaryClient.LIST_POSITION; + /** * Common interface for sharded and non-sharded BinaryJedis */ @@ -114,8 +116,8 @@ public interface BinaryJedisCommands { Long strlen(byte[] key); Long zadd(byte[] key, double score, byte[] member); - - Long zadd(byte[] key, Map scoreMembers); + + Long zadd(byte[] key, Map scoreMembers); Set zrange(byte[] key, long start, long end); @@ -157,45 +159,45 @@ public interface BinaryJedisCommands { Set zrevrangeByScore(byte[] key, byte[] max, byte[] min); Set zrangeByScore(byte[] key, byte[] min, byte[] max, int offset, - int count); + int count); Set zrevrangeByScore(byte[] key, double max, double min, - int offset, int count); + int offset, int count); Set zrangeByScoreWithScores(byte[] key, double min, double max); Set zrevrangeByScoreWithScores(byte[] key, double max, double min); Set zrangeByScoreWithScores(byte[] key, double min, double max, - int offset, int count); - + int offset, int count); + Set zrevrangeByScore(byte[] key, byte[] max, byte[] min, - int offset, int count); + int offset, int count); Set zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max); - + Set zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min); Set zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max, - int offset, int count); + int offset, int count); Set zrevrangeByScoreWithScores(byte[] key, double max, double min, - int offset, int count); - + int offset, int count); + Set zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min, - int offset, int count); + int offset, int count); Long zremrangeByRank(byte[] key, long start, long end); Long zremrangeByScore(byte[] key, double start, double end); - + Long zremrangeByScore(byte[] key, byte[] start, byte[] end); Long linsert(byte[] key, Client.LIST_POSITION where, byte[] pivot, - byte[] value); - + byte[] value); + Long lpushx(byte[] key, byte[]... arg); - + Long rpushx(byte[] key, byte[]... arg); List blpop(byte[] arg); diff --git a/src/main/java/redis/clients/jedis/BinaryShardedJedis.java b/src/main/java/redis/clients/jedis/BinaryShardedJedis.java index da934a4..382d48b 100644 --- a/src/main/java/redis/clients/jedis/BinaryShardedJedis.java +++ b/src/main/java/redis/clients/jedis/BinaryShardedJedis.java @@ -295,7 +295,7 @@ public class BinaryShardedJedis extends Sharded return j.zadd(key, score, member); } - public Long zadd(byte[] key, Map scoreMembers) { + public Long zadd(byte[] key, Map scoreMembers) { Jedis j = getShard(key); return j.zadd(key, scoreMembers); } diff --git a/src/main/java/redis/clients/jedis/Client.java b/src/main/java/redis/clients/jedis/Client.java index 1353a1b..a2ec464 100644 --- a/src/main/java/redis/clients/jedis/Client.java +++ b/src/main/java/redis/clients/jedis/Client.java @@ -709,17 +709,19 @@ public class Client extends BinaryClient implements Commands { public void scriptLoad(String script) { scriptLoad(SafeEncoder.encode(script)); } + + public void zadd(String key, Map scoreMembers) { + + HashMap binaryScoreMembers = new HashMap(); - public void zadd(String key, Map scoreMembers) { - HashMap binaryScoreMembers = new HashMap(); - - for (Map.Entry entry : scoreMembers.entrySet()) { - binaryScoreMembers.put(entry.getKey(), - SafeEncoder.encode(entry.getValue())); + for (Map.Entry entry : scoreMembers.entrySet()) { + + binaryScoreMembers.put(SafeEncoder.encode(entry.getKey()), entry.getValue()); + } + + zaddBinary(SafeEncoder.encode(key), binaryScoreMembers); } - zaddBinary(SafeEncoder.encode(key), binaryScoreMembers); - } public void objectRefcount(String key) { objectRefcount(SafeEncoder.encode(key)); diff --git a/src/main/java/redis/clients/jedis/Commands.java b/src/main/java/redis/clients/jedis/Commands.java index e4e22ec..c6b26f7 100644 --- a/src/main/java/redis/clients/jedis/Commands.java +++ b/src/main/java/redis/clients/jedis/Commands.java @@ -143,8 +143,8 @@ public interface Commands { public void srandmember(final String key); public void zadd(final String key, final double score, final String member); - - public void zadd(final String key, final Map scoreMembers); + + public void zadd(final String key, final Map scoreMembers); public void zrange(final String key, final long start, final long end); diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index 2503d50..cdc3918 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -1415,10 +1415,10 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand return client.getIntegerReply(); } - public Long zadd(final String key, final Map scoreMembers) { - checkIsInMulti(); - client.zadd(key, scoreMembers); - return client.getIntegerReply(); + public Long zadd(final String key, final Map scoreMembers) { + checkIsInMulti(); + client.zadd(key, scoreMembers); + return client.getIntegerReply(); } public Set zrange(final String key, final long start, final long end) { diff --git a/src/main/java/redis/clients/jedis/JedisCluster.java b/src/main/java/redis/clients/jedis/JedisCluster.java index ed60b5a..ffa1115 100644 --- a/src/main/java/redis/clients/jedis/JedisCluster.java +++ b/src/main/java/redis/clients/jedis/JedisCluster.java @@ -635,7 +635,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { } @Override - public Long zadd(final String key, final Map scoreMembers) { + public Long zadd(final String key, final Map scoreMembers) { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override diff --git a/src/main/java/redis/clients/jedis/JedisCommands.java b/src/main/java/redis/clients/jedis/JedisCommands.java index d027361..4f9af0d 100644 --- a/src/main/java/redis/clients/jedis/JedisCommands.java +++ b/src/main/java/redis/clients/jedis/JedisCommands.java @@ -115,7 +115,7 @@ public interface Long zadd(String key, double score, String member); - Long zadd(String key, Map scoreMembers); + Long zadd(String key, Map scoreMembers); Set zrange(String key, long start, long end); diff --git a/src/main/java/redis/clients/jedis/PipelineBase.java b/src/main/java/redis/clients/jedis/PipelineBase.java index b89ea07..9ebcc9e 100644 --- a/src/main/java/redis/clients/jedis/PipelineBase.java +++ b/src/main/java/redis/clients/jedis/PipelineBase.java @@ -654,7 +654,7 @@ abstract class PipelineBase extends Queable implements return getResponse(BuilderFactory.LONG); } - public Response zadd(String key, Map scoreMembers) { + public Response zadd(String key, Map scoreMembers) { getClient(key).zadd(key, scoreMembers); return getResponse(BuilderFactory.LONG); } diff --git a/src/main/java/redis/clients/jedis/ShardedJedis.java b/src/main/java/redis/clients/jedis/ShardedJedis.java index a63a7d0..f3d2f72 100644 --- a/src/main/java/redis/clients/jedis/ShardedJedis.java +++ b/src/main/java/redis/clients/jedis/ShardedJedis.java @@ -326,10 +326,10 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands { Jedis j = getShard(key); return j.zadd(key, score, member); } - - public Long zadd(String key, Map scoreMembers) { - Jedis j = getShard(key); - return j.zadd(key, scoreMembers); + + public Long zadd(String key, Map scoreMembers) { + Jedis j = getShard(key); + return j.zadd(key, scoreMembers); } public Set zrange(String key, long start, long end) { diff --git a/src/test/java/redis/clients/jedis/tests/commands/VariadicCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/VariadicCommandsTest.java index fd63859..5e84ec9 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/VariadicCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/VariadicCommandsTest.java @@ -117,30 +117,30 @@ public class VariadicCommandsTest extends JedisCommandTestBase { @Test public void zadd() { - Map scoreMembers = new HashMap(); - scoreMembers.put(1d, "bar"); - scoreMembers.put(10d, "foo"); + Map scoreMembers = new HashMap(); + scoreMembers.put("bar", 1d); + scoreMembers.put("foo", 10d); long status = jedis.zadd("foo", scoreMembers); assertEquals(2, status); scoreMembers.clear(); - scoreMembers.put(0.1d, "car"); - scoreMembers.put(2d, "bar"); + scoreMembers.put("car", 0.1d); + scoreMembers.put("bar", 2d); status = jedis.zadd("foo", scoreMembers); assertEquals(1, status); - Map bscoreMembers = new HashMap(); - bscoreMembers.put(1d, bbar); - bscoreMembers.put(10d, bfoo); + Map bscoreMembers = new HashMap(); + bscoreMembers.put(bbar, 1d); + bscoreMembers.put(bfoo, 10d); status = jedis.zadd(bfoo, bscoreMembers); assertEquals(2, status); bscoreMembers.clear(); - bscoreMembers.put(0.1d, bcar); - bscoreMembers.put(2d, bbar); + bscoreMembers.put(bcar, 0.1d); + bscoreMembers.put(bbar, 2d); status = jedis.zadd(bfoo, bscoreMembers); assertEquals(1, status); From 642cec66d5d833490bc7b17adbdfa37e46a2c676 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Mon, 27 Jan 2014 12:47:21 +0900 Subject: [PATCH 013/120] Fix ControlCommandsTest to don't hang from monitor test because of timing issue * In monitor command test, input thread waits for monitor thread to monitor ** Monitor command test sometimes hang when input thread run earlier than monitor thread. --- .../clients/jedis/tests/commands/ControlCommandsTest.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/test/java/redis/clients/jedis/tests/commands/ControlCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/ControlCommandsTest.java index 832cd6c..bba56c1 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ControlCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ControlCommandsTest.java @@ -61,6 +61,11 @@ public class ControlCommandsTest extends JedisCommandTestBase { public void monitor() { new Thread(new Runnable() { public void run() { + try { + // sleep 100ms to make sure that monitor thread runs first + Thread.sleep(100); + } catch (InterruptedException e) { + } Jedis j = new Jedis("localhost"); j.auth("foobared"); for (int i = 0; i < 5; i++) { From 1844e29569635d5d005ae36f55f3e67cae67b863 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Tue, 28 Jan 2014 11:04:21 -0300 Subject: [PATCH 014/120] Fix typo in cluster snippet from README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b5b7219..0a05970 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,7 @@ Redis cluster [specification](http://redis.io/topics/cluster-spec) (still under ```java Set jedisClusterNodes = new HashSet(); //Jedis Cluster will attempt to discover cluster nodes automatically -jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); +jedisClusterNodes.add(new HostAndPort("127.0.0.1", 7379)); JedisCluster jc = new JedisCluster(jedisClusterNode); jc.set("foo", "bar"); String value = jc.get("foo"); From 105ca9f5bb813ff71ccf16450dcb12796955f306 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Fri, 31 Jan 2014 11:24:06 -0500 Subject: [PATCH 015/120] Reformat all files in the project according to java conventions. --- .../jedis/AdvancedBinaryJedisCommands.java | 1 - .../clients/jedis/AdvancedJedisCommands.java | 3 +- .../redis/clients/jedis/BasicCommands.java | 4 +- .../clients/jedis/BasicRedisPipeline.java | 1 - .../redis/clients/jedis/BinaryClient.java | 468 ++++--- .../java/redis/clients/jedis/BinaryJedis.java | 469 ++++--- .../clients/jedis/BinaryJedisCommands.java | 32 +- .../clients/jedis/BinaryJedisPubSub.java | 114 +- .../clients/jedis/BinaryRedisPipeline.java | 60 +- .../jedis/BinaryScriptingCommands.java | 3 +- src/main/java/redis/clients/jedis/BitOP.java | 5 +- .../redis/clients/jedis/BuilderFactory.java | 369 ++--- src/main/java/redis/clients/jedis/Client.java | 197 +-- .../java/redis/clients/jedis/Commands.java | 4 +- .../java/redis/clients/jedis/Connection.java | 252 ++-- .../java/redis/clients/jedis/HostAndPort.java | 77 +- src/main/java/redis/clients/jedis/Jedis.java | 438 +++--- .../clients/jedis/JedisClusterCommand.java | 87 +- .../jedis/JedisClusterConnectionHandler.java | 128 +- .../redis/clients/jedis/JedisCommands.java | 43 +- .../redis/clients/jedis/JedisMonitor.java | 12 +- .../java/redis/clients/jedis/JedisPool.java | 4 +- .../redis/clients/jedis/JedisPoolConfig.java | 10 +- .../java/redis/clients/jedis/JedisPubSub.java | 162 +-- .../jedis/JedisRandomConnectionHandler.java | 21 +- .../clients/jedis/JedisSentinelPool.java | 15 +- .../JedisSlotBasedConnectionHandler.java | 74 +- .../clients/jedis/MultiKeyBinaryCommands.java | 1 - .../jedis/MultiKeyBinaryRedisPipeline.java | 9 +- .../redis/clients/jedis/MultiKeyCommands.java | 4 +- .../jedis/MultiKeyCommandsPipeline.java | 8 +- .../clients/jedis/MultiKeyPipelineBase.java | 356 ++--- .../java/redis/clients/jedis/Pipeline.java | 137 +- .../redis/clients/jedis/PipelineBase.java | 1188 +++++++++-------- .../redis/clients/jedis/PipelineBlock.java | 1 - .../java/redis/clients/jedis/Protocol.java | 63 +- .../java/redis/clients/jedis/Queable.java | 18 +- .../redis/clients/jedis/RedisPipeline.java | 45 +- .../java/redis/clients/jedis/Response.java | 38 +- .../redis/clients/jedis/ShardedJedis.java | 44 +- .../clients/jedis/ShardedJedisPipeline.java | 68 +- .../redis/clients/jedis/SortingParams.java | 56 +- .../java/redis/clients/jedis/Transaction.java | 75 +- .../redis/clients/jedis/TransactionBlock.java | 2 +- src/main/java/redis/clients/jedis/Tuple.java | 86 +- .../java/redis/clients/jedis/ZParams.java | 28 +- .../exceptions/JedisAskDataException.java | 19 +- .../exceptions/JedisClusterException.java | 13 +- .../JedisClusterMaxRedirectionsException.java | 13 +- .../exceptions/JedisConnectionException.java | 6 +- .../jedis/exceptions/JedisDataException.java | 6 +- .../jedis/exceptions/JedisException.java | 7 +- .../exceptions/JedisMovedDataException.java | 17 +- .../exceptions/JedisRedirectionException.java | 42 +- src/main/java/redis/clients/util/Hashing.java | 40 +- .../redis/clients/util/JedisByteHashMap.java | 140 +- .../redis/clients/util/JedisClusterCRC16.java | 34 +- .../java/redis/clients/util/MurmurHash.java | 126 +- .../redis/clients/util/RedisInputStream.java | 118 +- .../redis/clients/util/RedisOutputStream.java | 330 +++-- .../java/redis/clients/util/SafeEncoder.java | 42 +- .../java/redis/clients/util/ShardInfo.java | 6 +- src/main/java/redis/clients/util/Sharded.java | 86 +- src/main/java/redis/clients/util/Slowlog.java | 80 +- .../jedis/tests/BuilderFactoryTest.java | 4 +- .../clients/jedis/tests/ConnectionTest.java | 18 +- .../tests/FragmentedByteArrayInputStream.java | 20 +- .../clients/jedis/tests/JedisPoolTest.java | 116 +- .../jedis/tests/JedisSentinelPoolTest.java | 35 +- .../clients/jedis/tests/JedisTestBase.java | 20 +- .../clients/jedis/tests/PipeliningTest.java | 476 +++---- .../clients/jedis/tests/ProtocolTest.java | 94 +- .../clients/jedis/tests/ShardedJedisTest.java | 442 +++--- .../tests/benchmark/GetSetBenchmark.java | 2 +- .../tests/benchmark/HashingBenchmark.java | 45 +- .../benchmark/PipelinedGetSetBenchmark.java | 32 +- .../tests/benchmark/SafeEncoderBenchmark.java | 32 +- .../tests/benchmark/ShardedBenchmark.java | 32 +- .../commands/BinaryValuesCommandsTest.java | 286 ++-- .../jedis/tests/commands/BitCommandsTest.java | 102 +- .../tests/commands/ClusterCommandsTest.java | 57 +- .../ConnectionHandlingCommandsTest.java | 6 +- .../tests/commands/ControlCommandsTest.java | 14 +- .../tests/commands/HashesCommandsTest.java | 6 +- .../tests/commands/JedisCommandTestBase.java | 94 +- .../tests/commands/ListCommandsTest.java | 748 ++++++----- .../PublishSubscribeCommandsTest.java | 23 +- .../tests/commands/ScriptingCommandsTest.java | 83 +- .../jedis/tests/commands/SetCommandsTest.java | 516 ++++--- .../tests/commands/SlowlogCommandsTest.java | 68 +- .../tests/commands/SortedSetCommandsTest.java | 1098 +++++++-------- .../tests/commands/SortingCommandsTest.java | 362 ++--- .../commands/StringValuesCommandsTest.java | 204 +-- .../commands/TransactionCommandsTest.java | 65 +- .../tests/commands/VariadicCommandsTest.java | 266 ++-- 95 files changed, 5946 insertions(+), 5825 deletions(-) diff --git a/src/main/java/redis/clients/jedis/AdvancedBinaryJedisCommands.java b/src/main/java/redis/clients/jedis/AdvancedBinaryJedisCommands.java index 51b4879..224dd11 100644 --- a/src/main/java/redis/clients/jedis/AdvancedBinaryJedisCommands.java +++ b/src/main/java/redis/clients/jedis/AdvancedBinaryJedisCommands.java @@ -1,6 +1,5 @@ package redis.clients.jedis; - import java.util.List; public interface AdvancedBinaryJedisCommands { diff --git a/src/main/java/redis/clients/jedis/AdvancedJedisCommands.java b/src/main/java/redis/clients/jedis/AdvancedJedisCommands.java index 5ed50eb..45e825b 100644 --- a/src/main/java/redis/clients/jedis/AdvancedJedisCommands.java +++ b/src/main/java/redis/clients/jedis/AdvancedJedisCommands.java @@ -1,9 +1,8 @@ package redis.clients.jedis; -import redis.clients.util.Slowlog; - import java.util.List; +import redis.clients.util.Slowlog; public interface AdvancedJedisCommands { List configGet(String pattern); diff --git a/src/main/java/redis/clients/jedis/BasicCommands.java b/src/main/java/redis/clients/jedis/BasicCommands.java index 5b7e995..c201e41 100644 --- a/src/main/java/redis/clients/jedis/BasicCommands.java +++ b/src/main/java/redis/clients/jedis/BasicCommands.java @@ -27,7 +27,7 @@ public interface BasicCommands { String shutdown(); String info(); - + String info(String section); String slaveof(String host, int port); @@ -39,6 +39,6 @@ public interface BasicCommands { String debug(DebugParams params); String configResetStat(); - + Long waitReplicas(int replicas, long timeout); } diff --git a/src/main/java/redis/clients/jedis/BasicRedisPipeline.java b/src/main/java/redis/clients/jedis/BasicRedisPipeline.java index a667ce9..bec6e8c 100644 --- a/src/main/java/redis/clients/jedis/BasicRedisPipeline.java +++ b/src/main/java/redis/clients/jedis/BasicRedisPipeline.java @@ -1,6 +1,5 @@ package redis.clients.jedis; - /** * Pipelined responses for all of the low level, non key related commands */ diff --git a/src/main/java/redis/clients/jedis/BinaryClient.java b/src/main/java/redis/clients/jedis/BinaryClient.java index 56f97af..e80754f 100644 --- a/src/main/java/redis/clients/jedis/BinaryClient.java +++ b/src/main/java/redis/clients/jedis/BinaryClient.java @@ -1,22 +1,26 @@ package redis.clients.jedis; -import redis.clients.jedis.Protocol.Command; -import redis.clients.jedis.Protocol.Keyword; -import redis.clients.util.SafeEncoder; +import static redis.clients.jedis.Protocol.toByteArray; +import static redis.clients.jedis.Protocol.Command.*; +import static redis.clients.jedis.Protocol.Keyword.ENCODING; +import static redis.clients.jedis.Protocol.Keyword.IDLETIME; +import static redis.clients.jedis.Protocol.Keyword.LEN; +import static redis.clients.jedis.Protocol.Keyword.LIMIT; +import static redis.clients.jedis.Protocol.Keyword.NO; +import static redis.clients.jedis.Protocol.Keyword.ONE; +import static redis.clients.jedis.Protocol.Keyword.REFCOUNT; +import static redis.clients.jedis.Protocol.Keyword.RESET; +import static redis.clients.jedis.Protocol.Keyword.STORE; +import static redis.clients.jedis.Protocol.Keyword.WITHSCORES; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; -import static redis.clients.jedis.Protocol.Command.*; -import static redis.clients.jedis.Protocol.Command.EXISTS; -import static redis.clients.jedis.Protocol.Command.PSUBSCRIBE; -import static redis.clients.jedis.Protocol.Command.PUNSUBSCRIBE; -import static redis.clients.jedis.Protocol.Command.SUBSCRIBE; -import static redis.clients.jedis.Protocol.Command.UNSUBSCRIBE; -import static redis.clients.jedis.Protocol.Keyword.*; -import static redis.clients.jedis.Protocol.toByteArray; +import redis.clients.jedis.Protocol.Command; +import redis.clients.jedis.Protocol.Keyword; +import redis.clients.util.SafeEncoder; public class BinaryClient extends Connection { public enum LIST_POSITION { @@ -29,19 +33,19 @@ public class BinaryClient extends Connection { } private boolean isInMulti; - + private String password; private long db; - private boolean isInWatch; + private boolean isInWatch; public boolean isInMulti() { return isInMulti; } public boolean isInWatch() { - return isInWatch; + return isInWatch; } public BinaryClient(final String host) { @@ -88,11 +92,11 @@ public class BinaryClient extends Connection { sendCommand(Command.SET, key, value); } - public void set(final byte[] key, final byte[] value, final byte[] nxxx, final byte[] expx, final long time) { - sendCommand(Command.SET, key, value, nxxx, expx, toByteArray(time)); + public void set(final byte[] key, final byte[] value, final byte[] nxxx, + final byte[] expx, final long time) { + sendCommand(Command.SET, key, value, nxxx, expx, toByteArray(time)); } - public void get(final byte[] key) { sendCommand(Command.GET, key); } @@ -382,22 +386,24 @@ public class BinaryClient extends Connection { public void zadd(final byte[] key, final double score, final byte[] member) { sendCommand(ZADD, key, toByteArray(score), member); } - - public void zaddBinary(final byte[] key, final Map< byte[], Double> scoreMembers) { - - ArrayList args = new ArrayList(scoreMembers.size() * 2 + 1); - args.add(key); - for (Map.Entry entry : scoreMembers.entrySet()) { - args.add(toByteArray(entry.getValue())); - args.add(entry.getKey()); - } + public void zaddBinary(final byte[] key, + final Map scoreMembers) { - byte[][] argsArray = new byte[args.size()][]; - args.toArray(argsArray); + ArrayList args = new ArrayList( + scoreMembers.size() * 2 + 1); + args.add(key); - sendCommand(ZADD, argsArray); - } + for (Map.Entry entry : scoreMembers.entrySet()) { + args.add(toByteArray(entry.getValue())); + args.add(entry.getKey()); + } + + byte[][] argsArray = new byte[args.size()][]; + args.toArray(argsArray); + + sendCommand(ZADD, argsArray); + } public void zrange(final byte[] key, final long start, final long end) { sendCommand(ZRANGE, key, toByteArray(start), toByteArray(end)); @@ -485,14 +491,14 @@ public class BinaryClient extends Connection { public void blpop(final byte[][] args) { sendCommand(BLPOP, args); } - + public void blpop(final int timeout, final byte[]... keys) { - final List args = new ArrayList(); - for (final byte[] arg : keys) { - args.add(arg); - } - args.add(Protocol.toByteArray(timeout)); - blpop(args.toArray(new byte[args.size()][])); + final List args = new ArrayList(); + for (final byte[] arg : keys) { + args.add(arg); + } + args.add(Protocol.toByteArray(timeout)); + blpop(args.toArray(new byte[args.size()][])); } public void sort(final byte[] key, final SortingParams sortingParameters, @@ -512,14 +518,14 @@ public class BinaryClient extends Connection { public void brpop(final byte[][] args) { sendCommand(BRPOP, args); } - + public void brpop(final int timeout, final byte[]... keys) { - final List args = new ArrayList(); - for (final byte[] arg : keys) { - args.add(arg); - } - args.add(Protocol.toByteArray(timeout)); - brpop(args.toArray(new byte[args.size()][])); + final List args = new ArrayList(); + for (final byte[] arg : keys) { + args.add(arg); + } + args.add(Protocol.toByteArray(timeout)); + brpop(args.toArray(new byte[args.size()][])); } public void auth(final String password) { @@ -552,32 +558,36 @@ public class BinaryClient extends Connection { } public void punsubscribe(final byte[]... patterns) { - sendCommand(PUNSUBSCRIBE, patterns); + sendCommand(PUNSUBSCRIBE, patterns); } public void zcount(final byte[] key, final double min, final double max) { - byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); - byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); + byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf" + .getBytes() : toByteArray(min); + byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf" + .getBytes() : toByteArray(max); - sendCommand(ZCOUNT, key, byteArrayMin, byteArrayMax); + sendCommand(ZCOUNT, key, byteArrayMin, byteArrayMax); } public void zcount(final byte[] key, final byte min[], final byte max[]) { - sendCommand(ZCOUNT, key, min, max); + sendCommand(ZCOUNT, key, min, max); } public void zcount(final byte[] key, final String min, final String max) { - sendCommand(ZCOUNT, key, min.getBytes(), max.getBytes()); + sendCommand(ZCOUNT, key, min.getBytes(), max.getBytes()); } public void zrangeByScore(final byte[] key, final double min, - final double max) { + final double max) { - byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); - byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); + byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf" + .getBytes() : toByteArray(min); + byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf" + .getBytes() : toByteArray(max); - sendCommand(ZRANGEBYSCORE, key, byteArrayMin, byteArrayMax); + sendCommand(ZRANGEBYSCORE, key, byteArrayMin, byteArrayMax); } public void zrangeByScore(final byte[] key, final byte[] min, @@ -586,17 +596,19 @@ public class BinaryClient extends Connection { } public void zrangeByScore(final byte[] key, final String min, - final String max) { - sendCommand(ZRANGEBYSCORE, key, min.getBytes(), max.getBytes()); + final String max) { + sendCommand(ZRANGEBYSCORE, key, min.getBytes(), max.getBytes()); } public void zrevrangeByScore(final byte[] key, final double max, - final double min) { + final double min) { - byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); - byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); + byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf" + .getBytes() : toByteArray(min); + byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf" + .getBytes() : toByteArray(max); - sendCommand(ZREVRANGEBYSCORE, key, byteArrayMax, byteArrayMin); + sendCommand(ZREVRANGEBYSCORE, key, byteArrayMax, byteArrayMin); } public void zrevrangeByScore(final byte[] key, final byte[] max, @@ -605,114 +617,125 @@ public class BinaryClient extends Connection { } public void zrevrangeByScore(final byte[] key, final String max, - final String min) { - sendCommand(ZREVRANGEBYSCORE, key, max.getBytes(), min.getBytes()); + final String min) { + sendCommand(ZREVRANGEBYSCORE, key, max.getBytes(), min.getBytes()); } public void zrangeByScore(final byte[] key, final double min, - final double max, final int offset, int count) { + final double max, final int offset, int count) { - byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); - byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); + byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf" + .getBytes() : toByteArray(min); + byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf" + .getBytes() : toByteArray(max); - sendCommand(ZRANGEBYSCORE, key, byteArrayMin, byteArrayMax, - LIMIT.raw, toByteArray(offset), toByteArray(count)); + sendCommand(ZRANGEBYSCORE, key, byteArrayMin, byteArrayMax, LIMIT.raw, + toByteArray(offset), toByteArray(count)); } - - public void zrangeByScore(final byte[] key, final String min, - final String max, final int offset, int count) { - sendCommand(ZRANGEBYSCORE, key, min.getBytes(), max.getBytes(), - LIMIT.raw, toByteArray(offset), toByteArray(count)); + public void zrangeByScore(final byte[] key, final String min, + final String max, final int offset, int count) { + + sendCommand(ZRANGEBYSCORE, key, min.getBytes(), max.getBytes(), + LIMIT.raw, toByteArray(offset), toByteArray(count)); } public void zrevrangeByScore(final byte[] key, final double max, - final double min, final int offset, int count) { + final double min, final int offset, int count) { - byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); - byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); + byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf" + .getBytes() : toByteArray(min); + byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf" + .getBytes() : toByteArray(max); - sendCommand(ZREVRANGEBYSCORE, key, byteArrayMax, byteArrayMin, - LIMIT.raw, toByteArray(offset), toByteArray(count)); - } + sendCommand(ZREVRANGEBYSCORE, key, byteArrayMax, byteArrayMin, + LIMIT.raw, toByteArray(offset), toByteArray(count)); + } public void zrevrangeByScore(final byte[] key, final String max, - final String min, final int offset, int count) { + final String min, final int offset, int count) { - sendCommand(ZREVRANGEBYSCORE, key, max.getBytes(), min.getBytes(), - LIMIT.raw, toByteArray(offset), toByteArray(count)); + sendCommand(ZREVRANGEBYSCORE, key, max.getBytes(), min.getBytes(), + LIMIT.raw, toByteArray(offset), toByteArray(count)); } public void zrangeByScoreWithScores(final byte[] key, final double min, - final double max) { + final double max) { - byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); - byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); + byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf" + .getBytes() : toByteArray(min); + byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf" + .getBytes() : toByteArray(max); - sendCommand(ZRANGEBYSCORE, key, byteArrayMin, byteArrayMax, - WITHSCORES.raw); + sendCommand(ZRANGEBYSCORE, key, byteArrayMin, byteArrayMax, + WITHSCORES.raw); } public void zrangeByScoreWithScores(final byte[] key, final String min, - final String max) { + final String max) { - sendCommand(ZRANGEBYSCORE, key, min.getBytes(), max.getBytes(), - WITHSCORES.raw); + sendCommand(ZRANGEBYSCORE, key, min.getBytes(), max.getBytes(), + WITHSCORES.raw); } public void zrevrangeByScoreWithScores(final byte[] key, final double max, - final double min) { + final double min) { - byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); - byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); + byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf" + .getBytes() : toByteArray(min); + byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf" + .getBytes() : toByteArray(max); - sendCommand(ZREVRANGEBYSCORE, key, byteArrayMax, byteArrayMin, - WITHSCORES.raw); + sendCommand(ZREVRANGEBYSCORE, key, byteArrayMax, byteArrayMin, + WITHSCORES.raw); } public void zrevrangeByScoreWithScores(final byte[] key, final String max, - final String min) { - sendCommand(ZREVRANGEBYSCORE, key, max.getBytes(), min.getBytes(), - WITHSCORES.raw); + final String min) { + sendCommand(ZREVRANGEBYSCORE, key, max.getBytes(), min.getBytes(), + WITHSCORES.raw); } public void zrangeByScoreWithScores(final byte[] key, final double min, - final double max, final int offset, final int count) { + final double max, final int offset, final int count) { - byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); - byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); + byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf" + .getBytes() : toByteArray(min); + byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf" + .getBytes() : toByteArray(max); - sendCommand(ZRANGEBYSCORE, key, byteArrayMin, byteArrayMax, - LIMIT.raw, toByteArray(offset), toByteArray(count), - WITHSCORES.raw); + sendCommand(ZRANGEBYSCORE, key, byteArrayMin, byteArrayMax, LIMIT.raw, + toByteArray(offset), toByteArray(count), WITHSCORES.raw); } public void zrangeByScoreWithScores(final byte[] key, final String min, - final String max, final int offset, final int count) { - sendCommand(ZRANGEBYSCORE, key, min.getBytes(), max.getBytes(), - LIMIT.raw, toByteArray(offset), toByteArray(count), - WITHSCORES.raw); + final String max, final int offset, final int count) { + sendCommand(ZRANGEBYSCORE, key, min.getBytes(), max.getBytes(), + LIMIT.raw, toByteArray(offset), toByteArray(count), + WITHSCORES.raw); } public void zrevrangeByScoreWithScores(final byte[] key, final double max, - final double min, final int offset, final int count) { + final double min, final int offset, final int count) { - byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); - byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); + byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf" + .getBytes() : toByteArray(min); + byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf" + .getBytes() : toByteArray(max); - sendCommand(ZREVRANGEBYSCORE, key, byteArrayMax, byteArrayMin, - LIMIT.raw, toByteArray(offset), toByteArray(count), - WITHSCORES.raw); + sendCommand(ZREVRANGEBYSCORE, key, byteArrayMax, byteArrayMin, + LIMIT.raw, toByteArray(offset), toByteArray(count), + WITHSCORES.raw); } public void zrevrangeByScoreWithScores(final byte[] key, final String max, - final String min, final int offset, final int count) { + final String min, final int offset, final int count) { - sendCommand(ZREVRANGEBYSCORE, key, max.getBytes(), min.getBytes(), - LIMIT.raw, toByteArray(offset), toByteArray(count), - WITHSCORES.raw); + sendCommand(ZREVRANGEBYSCORE, key, max.getBytes(), min.getBytes(), + LIMIT.raw, toByteArray(offset), toByteArray(count), + WITHSCORES.raw); } - + public void zrangeByScore(final byte[] key, final byte[] min, final byte[] max, final int offset, int count) { sendCommand(ZRANGEBYSCORE, key, min, max, LIMIT.raw, @@ -755,11 +778,11 @@ public class BinaryClient extends Connection { public void zremrangeByScore(final byte[] key, final byte[] start, final byte[] end) { sendCommand(ZREMRANGEBYSCORE, key, start, end); - } + } public void zremrangeByScore(final byte[] key, final String start, - final String end) { - sendCommand(ZREMRANGEBYSCORE, key, start.getBytes(), end.getBytes()); + final String end) { + sendCommand(ZREMRANGEBYSCORE, key, start.getBytes(), end.getBytes()); } public void zunionstore(final byte[] dstkey, final byte[]... sets) { @@ -825,7 +848,7 @@ public class BinaryClient extends Connection { public void info() { sendCommand(INFO); } - + public void info(final String section) { sendCommand(INFO, section); } @@ -897,7 +920,7 @@ public class BinaryClient extends Connection { } public void setbit(byte[] key, long offset, boolean value) { - sendCommand(SETBIT, key, toByteArray(offset), toByteArray(value)); + sendCommand(SETBIT, key, toByteArray(offset), toByteArray(value)); } public void getbit(byte[] key, long offset) { @@ -921,13 +944,13 @@ public class BinaryClient extends Connection { db = 0; super.disconnect(); } - + public void resetState() { - if (isInMulti()) - discard(); - - if (isInWatch()) - unwatch(); + if (isInMulti()) + discard(); + + if (isInWatch()) + unwatch(); } private void sendEvalCommand(Command command, byte[] script, @@ -949,7 +972,7 @@ public class BinaryClient extends Connection { } public void eval(byte[] script, int keyCount, byte[]... params) { - eval(script, toByteArray(keyCount), params); + eval(script, toByteArray(keyCount), params); } public void evalsha(byte[] sha1, byte[] keyCount, byte[]... params) { @@ -957,7 +980,7 @@ public class BinaryClient extends Connection { } public void evalsha(byte[] sha1, int keyCount, byte[]... params) { - sendEvalCommand(EVALSHA, sha1, toByteArray(keyCount), params); + sendEvalCommand(EVALSHA, sha1, toByteArray(keyCount), params); } public void scriptFlush() { @@ -1010,153 +1033,160 @@ public class BinaryClient extends Connection { } public void bitcount(byte[] key) { - sendCommand(BITCOUNT, key); + sendCommand(BITCOUNT, key); } public void bitcount(byte[] key, long start, long end) { - sendCommand(BITCOUNT, key, toByteArray(start), toByteArray(end)); + sendCommand(BITCOUNT, key, toByteArray(start), toByteArray(end)); } public void bitop(BitOP op, byte[] destKey, byte[]... srcKeys) { - Keyword kw = Keyword.AND; - int len = srcKeys.length; - switch (op) { - case AND: - kw = Keyword.AND; - break; - case OR: - kw = Keyword.OR; - break; - case XOR: - kw = Keyword.XOR; - break; - case NOT: - kw = Keyword.NOT; - len = Math.min(1, len); - break; - } + Keyword kw = Keyword.AND; + int len = srcKeys.length; + switch (op) { + case AND: + kw = Keyword.AND; + break; + case OR: + kw = Keyword.OR; + break; + case XOR: + kw = Keyword.XOR; + break; + case NOT: + kw = Keyword.NOT; + len = Math.min(1, len); + break; + } - byte[][] bargs = new byte[len + 2][]; - bargs[0] = kw.raw; - bargs[1] = destKey; - for (int i = 0; i < len; ++i) { - bargs[i + 2] = srcKeys[i]; - } + byte[][] bargs = new byte[len + 2][]; + bargs[0] = kw.raw; + bargs[1] = destKey; + for (int i = 0; i < len; ++i) { + bargs[i + 2] = srcKeys[i]; + } - sendCommand(BITOP, bargs); + sendCommand(BITOP, bargs); } public void sentinel(final byte[]... args) { - sendCommand(SENTINEL, args); + sendCommand(SENTINEL, args); } - + public void dump(final byte[] key) { - sendCommand(DUMP, key); + sendCommand(DUMP, key); } - - public void restore(final byte[] key, final int ttl, final byte[] serializedValue) { - sendCommand(RESTORE, key, toByteArray(ttl), serializedValue); + + public void restore(final byte[] key, final int ttl, + final byte[] serializedValue) { + sendCommand(RESTORE, key, toByteArray(ttl), serializedValue); } - + public void pexpire(final byte[] key, final int milliseconds) { - sendCommand(PEXPIRE, key, toByteArray(milliseconds)); + sendCommand(PEXPIRE, key, toByteArray(milliseconds)); } - + public void pexpireAt(final byte[] key, final long millisecondsTimestamp) { - sendCommand(PEXPIREAT, key, toByteArray(millisecondsTimestamp)); + sendCommand(PEXPIREAT, key, toByteArray(millisecondsTimestamp)); } - + public void pttl(final byte[] key) { - sendCommand(PTTL, key); + sendCommand(PTTL, key); } - + public void incrByFloat(final byte[] key, final double increment) { - sendCommand(INCRBYFLOAT, key, toByteArray(increment)); + sendCommand(INCRBYFLOAT, key, toByteArray(increment)); } - - public void psetex(final byte[] key, final int milliseconds, final byte[] value) { - sendCommand(PSETEX, key, toByteArray(milliseconds), value); + + public void psetex(final byte[] key, final int milliseconds, + final byte[] value) { + sendCommand(PSETEX, key, toByteArray(milliseconds), value); } - + public void set(final byte[] key, final byte[] value, final byte[] nxxx) { - sendCommand(Command.SET, key, value, nxxx); + sendCommand(Command.SET, key, value, nxxx); } - - public void set(final byte[] key, final byte[] value, final byte[] nxxx, final byte[] expx, final int time) { - sendCommand(Command.SET, key, value, nxxx, expx, toByteArray(time)); + + public void set(final byte[] key, final byte[] value, final byte[] nxxx, + final byte[] expx, final int time) { + sendCommand(Command.SET, key, value, nxxx, expx, toByteArray(time)); } - + public void srandmember(final byte[] key, final int count) { - sendCommand(SRANDMEMBER, key, toByteArray(count)); + sendCommand(SRANDMEMBER, key, toByteArray(count)); } - + public void clientKill(final byte[] client) { - sendCommand(CLIENT, Keyword.KILL.raw, client); + sendCommand(CLIENT, Keyword.KILL.raw, client); } - + public void clientGetname() { - sendCommand(CLIENT, Keyword.GETNAME.raw); + sendCommand(CLIENT, Keyword.GETNAME.raw); } - + public void clientList() { - sendCommand(CLIENT, Keyword.LIST.raw); + sendCommand(CLIENT, Keyword.LIST.raw); } - + public void clientSetname(final byte[] name) { - sendCommand(CLIENT, Keyword.SETNAME.raw, name); + sendCommand(CLIENT, Keyword.SETNAME.raw, name); } - + public void time() { - sendCommand(TIME); + sendCommand(TIME); } - - public void migrate(final byte[] host, final int port, final byte[] key, final int destinationDb, final int timeout) { - sendCommand(MIGRATE, host, toByteArray(port), key, toByteArray(destinationDb), toByteArray(timeout)); + + public void migrate(final byte[] host, final int port, final byte[] key, + final int destinationDb, final int timeout) { + sendCommand(MIGRATE, host, toByteArray(port), key, + toByteArray(destinationDb), toByteArray(timeout)); } - - public void hincrByFloat(final byte[] key, final byte[] field, double increment) { - sendCommand(HINCRBYFLOAT, key, field, toByteArray(increment)); + + public void hincrByFloat(final byte[] key, final byte[] field, + double increment) { + sendCommand(HINCRBYFLOAT, key, field, toByteArray(increment)); } - + public void scan(int cursor, final ScanParams params) { final List args = new ArrayList(); args.add(toByteArray(cursor)); args.addAll(params.getParams()); sendCommand(SCAN, args.toArray(new byte[args.size()][])); } - + public void hscan(final byte[] key, int cursor, final ScanParams params) { - final List args = new ArrayList(); - args.add(key); - args.add(toByteArray(cursor)); - args.addAll(params.getParams()); - sendCommand(HSCAN, args.toArray(new byte[args.size()][])); + final List args = new ArrayList(); + args.add(key); + args.add(toByteArray(cursor)); + args.addAll(params.getParams()); + sendCommand(HSCAN, args.toArray(new byte[args.size()][])); } - + public void sscan(final byte[] key, int cursor, final ScanParams params) { - final List args = new ArrayList(); - args.add(key); - args.add(toByteArray(cursor)); - args.addAll(params.getParams()); - sendCommand(SSCAN, args.toArray(new byte[args.size()][])); + final List args = new ArrayList(); + args.add(key); + args.add(toByteArray(cursor)); + args.addAll(params.getParams()); + sendCommand(SSCAN, args.toArray(new byte[args.size()][])); } - + public void zscan(final byte[] key, int cursor, final ScanParams params) { - final List args = new ArrayList(); - args.add(key); - args.add(toByteArray(cursor)); - args.addAll(params.getParams()); - sendCommand(ZSCAN, args.toArray(new byte[args.size()][])); + final List args = new ArrayList(); + args.add(key); + args.add(toByteArray(cursor)); + args.addAll(params.getParams()); + sendCommand(ZSCAN, args.toArray(new byte[args.size()][])); } - + public void waitReplicas(int replicas, long timeout) { sendCommand(WAIT, toByteArray(replicas), toByteArray(timeout)); } public void cluster(final byte[]... args) { - sendCommand(CLUSTER, args); + sendCommand(CLUSTER, args); } + public void asking() { - sendCommand(Command.ASKING); + sendCommand(Command.ASKING); } } diff --git a/src/main/java/redis/clients/jedis/BinaryJedis.java b/src/main/java/redis/clients/jedis/BinaryJedis.java index 2f3d3c2..adac704 100644 --- a/src/main/java/redis/clients/jedis/BinaryJedis.java +++ b/src/main/java/redis/clients/jedis/BinaryJedis.java @@ -1,17 +1,25 @@ package redis.clients.jedis; +import static redis.clients.jedis.Protocol.toByteArray; + +import java.net.URI; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + import redis.clients.jedis.BinaryClient.LIST_POSITION; import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.exceptions.JedisException; import redis.clients.util.JedisByteHashMap; import redis.clients.util.SafeEncoder; -import java.net.URI; -import java.util.*; - -import static redis.clients.jedis.Protocol.toByteArray; - -public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKeyBinaryCommands, AdvancedBinaryJedisCommands, BinaryScriptingCommands { +public class BinaryJedis implements BasicCommands, BinaryJedisCommands, + MultiKeyBinaryCommands, AdvancedBinaryJedisCommands, + BinaryScriptingCommands { protected Client client = null; public BinaryJedis(final String host) { @@ -75,18 +83,23 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey /** * Set the string value as value of the key. The string can't be longer than * 1073741824 bytes (1 GB). + * * @param key * @param value - * @param nxxx NX|XX, NX -- Only set the key if it does not already exist. - * XX -- Only set the key if it already exist. - * @param expx EX|PX, expire time units: EX = seconds; PX = milliseconds - * @param time expire time in the units of {@param #expx} + * @param nxxx + * NX|XX, NX -- Only set the key if it does not already exist. XX + * -- Only set the key if it already exist. + * @param expx + * EX|PX, expire time units: EX = seconds; PX = milliseconds + * @param time + * expire time in the units of {@param #expx} * @return Status code reply */ - public String set(final byte[] key, final byte[] value, final byte[] nxxx, final byte[] expx, final long time) { - checkIsInMulti(); - client.set(key, value, nxxx, expx, time); - return client.getStatusCodeReply(); + public String set(final byte[] key, final byte[] value, final byte[] nxxx, + final byte[] expx, final long time) { + checkIsInMulti(); + client.set(key, value, nxxx, expx, time); + return client.getStatusCodeReply(); } /** @@ -147,9 +160,9 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey } public Long del(final byte[] key) { - checkIsInMulti(); - client.del(key); - return client.getIntegerReply(); + checkIsInMulti(); + client.del(key); + return client.getIntegerReply(); } /** @@ -1006,7 +1019,8 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey * @return Multi bulk reply, specifically a list of elements in the * specified range. */ - public List lrange(final byte[] key, final long start, final long end) { + public List lrange(final byte[] key, final long start, + final long end) { checkIsInMulti(); client.lrange(key, start, end); return client.getBinaryMultiBulkReply(); @@ -1468,11 +1482,11 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey client.srandmember(key); return client.getBinaryBulkReply(); } - + public List srandmember(final byte[] key, final int count) { - checkIsInMulti(); - client.srandmember(key, count); - return client.getBinaryMultiBulkReply(); + checkIsInMulti(); + client.srandmember(key, count); + return client.getBinaryMultiBulkReply(); } /** @@ -1697,7 +1711,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey protected void checkIsInMulti() { if (client.isInMulti()) { - throw new JedisDataException( + throw new JedisDataException( "Cannot use Jedis when in Multi. Please use JedisTransaction instead."); } } @@ -1709,7 +1723,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey public void disconnect() { client.disconnect(); } - + public void resetState() { client.resetState(); client.getAll(); @@ -2049,43 +2063,43 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey } public List blpop(byte[] arg) { - checkIsInMulti(); - byte[][] args = new byte[1][]; - args[0] = arg; - client.blpop(args); - client.setTimeoutInfinite(); - final List multiBulkReply = client.getBinaryMultiBulkReply(); - client.rollbackTimeout(); - return multiBulkReply; + checkIsInMulti(); + byte[][] args = new byte[1][]; + args[0] = arg; + client.blpop(args); + client.setTimeoutInfinite(); + final List multiBulkReply = client.getBinaryMultiBulkReply(); + client.rollbackTimeout(); + return multiBulkReply; } public List brpop(byte[] arg) { - checkIsInMulti(); - byte[][] args = new byte[1][]; - args[0] = arg; - client.brpop(args); - client.setTimeoutInfinite(); - final List multiBulkReply = client.getBinaryMultiBulkReply(); - client.rollbackTimeout(); - return multiBulkReply; + checkIsInMulti(); + byte[][] args = new byte[1][]; + args[0] = arg; + client.brpop(args); + client.setTimeoutInfinite(); + final List multiBulkReply = client.getBinaryMultiBulkReply(); + client.rollbackTimeout(); + return multiBulkReply; } public List blpop(byte[]... args) { - checkIsInMulti(); - client.blpop(args); - client.setTimeoutInfinite(); - final List multiBulkReply = client.getBinaryMultiBulkReply(); - client.rollbackTimeout(); - return multiBulkReply; + checkIsInMulti(); + client.blpop(args); + client.setTimeoutInfinite(); + final List multiBulkReply = client.getBinaryMultiBulkReply(); + client.rollbackTimeout(); + return multiBulkReply; } public List brpop(byte[]... args) { - checkIsInMulti(); - client.brpop(args); - client.setTimeoutInfinite(); - final List multiBulkReply = client.getBinaryMultiBulkReply(); - client.rollbackTimeout(); - return multiBulkReply; + checkIsInMulti(); + client.brpop(args); + client.setTimeoutInfinite(); + final List multiBulkReply = client.getBinaryMultiBulkReply(); + client.rollbackTimeout(); + return multiBulkReply; } /** @@ -2131,15 +2145,15 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey } public Long zcount(final byte[] key, final double min, final double max) { - return zcount(key, toByteArray(min), toByteArray(max)); + return zcount(key, toByteArray(min), toByteArray(max)); } - + public Long zcount(final byte[] key, final byte[] min, final byte[] max) { - checkIsInMulti(); - client.zcount(key, min, max); - return client.getIntegerReply(); + checkIsInMulti(); + client.zcount(key, min, max); + return client.getIntegerReply(); } - + /** * Return the all the elements in the sorted set at key with a score between * min and max (including elements with score equal to min or max). @@ -2199,7 +2213,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey public Set zrangeByScore(final byte[] key, final double min, final double max) { return zrangeByScore(key, toByteArray(min), toByteArray(max)); - } + } public Set zrangeByScore(final byte[] key, final byte[] min, final byte[] max) { @@ -2266,15 +2280,16 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey */ public Set zrangeByScore(final byte[] key, final double min, final double max, final int offset, final int count) { - return zrangeByScore(key, toByteArray(min),toByteArray(max),offset, count); + return zrangeByScore(key, toByteArray(min), toByteArray(max), offset, + count); } - + public Set zrangeByScore(final byte[] key, final byte[] min, - final byte[] max, final int offset, final int count) { - checkIsInMulti(); - client.zrangeByScore(key, min, max, offset, count); - return new LinkedHashSet(client.getBinaryMultiBulkReply()); - } + final byte[] max, final int offset, final int count) { + checkIsInMulti(); + client.zrangeByScore(key, min, max, offset, count); + return new LinkedHashSet(client.getBinaryMultiBulkReply()); + } /** * Return the all the elements in the sorted set at key with a score between @@ -2336,14 +2351,14 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey final double min, final double max) { return zrangeByScoreWithScores(key, toByteArray(min), toByteArray(max)); } - + public Set zrangeByScoreWithScores(final byte[] key, - final byte[] min, final byte[] max) { - checkIsInMulti(); - client.zrangeByScoreWithScores(key, min, max); - Set set = getBinaryTupledSet(); - return set; - } + final byte[] min, final byte[] max) { + checkIsInMulti(); + client.zrangeByScoreWithScores(key, min, max); + Set set = getBinaryTupledSet(); + return set; + } /** * Return the all the elements in the sorted set at key with a score between @@ -2404,17 +2419,18 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey public Set zrangeByScoreWithScores(final byte[] key, final double min, final double max, final int offset, final int count) { - return zrangeByScoreWithScores(key, toByteArray(min), toByteArray(max), offset, count); + return zrangeByScoreWithScores(key, toByteArray(min), toByteArray(max), + offset, count); } - + public Set zrangeByScoreWithScores(final byte[] key, - final byte[] min, final byte[] max, final int offset, - final int count) { - checkIsInMulti(); - client.zrangeByScoreWithScores(key, min, max, offset, count); - Set set = getBinaryTupledSet(); - return set; - } + final byte[] min, final byte[] max, final int offset, + final int count) { + checkIsInMulti(); + client.zrangeByScoreWithScores(key, min, max, offset, count); + Set set = getBinaryTupledSet(); + return set; + } private Set getBinaryTupledSet() { checkIsInMulti(); @@ -2442,29 +2458,32 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey public Set zrevrangeByScore(final byte[] key, final double max, final double min, final int offset, final int count) { - return zrevrangeByScore(key, toByteArray(max), toByteArray(min), offset, count); + return zrevrangeByScore(key, toByteArray(max), toByteArray(min), + offset, count); } - + public Set zrevrangeByScore(final byte[] key, final byte[] max, - final byte[] min, final int offset, final int count) { - checkIsInMulti(); - client.zrevrangeByScore(key, max, min, offset, count); - return new LinkedHashSet(client.getBinaryMultiBulkReply()); - } + final byte[] min, final int offset, final int count) { + checkIsInMulti(); + client.zrevrangeByScore(key, max, min, offset, count); + return new LinkedHashSet(client.getBinaryMultiBulkReply()); + } public Set zrevrangeByScoreWithScores(final byte[] key, final double max, final double min) { - return zrevrangeByScoreWithScores(key, toByteArray(max), toByteArray(min)); + return zrevrangeByScoreWithScores(key, toByteArray(max), + toByteArray(min)); } public Set zrevrangeByScoreWithScores(final byte[] key, final double max, final double min, final int offset, final int count) { - return zrevrangeByScoreWithScores(key, toByteArray(max), toByteArray(min), offset, count); + return zrevrangeByScoreWithScores(key, toByteArray(max), + toByteArray(min), offset, count); } - + public Set zrevrangeByScoreWithScores(final byte[] key, - final byte[] max, final byte[] min) { + final byte[] max, final byte[] min) { checkIsInMulti(); client.zrevrangeByScoreWithScores(key, max, min); Set set = getBinaryTupledSet(); @@ -2478,7 +2497,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey client.zrevrangeByScoreWithScores(key, max, min, offset, count); Set set = getBinaryTupledSet(); return set; - } + } /** * Remove all elements in the sorted set at key with rank between start and @@ -2493,7 +2512,8 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey * operation * */ - public Long zremrangeByRank(final byte[] key, final long start, final long end) { + public Long zremrangeByRank(final byte[] key, final long start, + final long end) { checkIsInMulti(); client.zremrangeByRank(key, start, end); return client.getIntegerReply(); @@ -2517,13 +2537,13 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey final double end) { return zremrangeByScore(key, toByteArray(start), toByteArray(end)); } - + public Long zremrangeByScore(final byte[] key, final byte[] start, - final byte[] end) { - checkIsInMulti(); - client.zremrangeByScore(key, start, end); - return client.getIntegerReply(); - } + final byte[] end) { + checkIsInMulti(); + client.zremrangeByScore(key, start, end); + return client.getIntegerReply(); + } /** * Creates a union or intersection of N sorted sets given by keys k1 through @@ -2847,7 +2867,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey client.info(); return client.getBulkReply(); } - + public String info(final String section) { client.info(section); return client.getBulkReply(); @@ -3083,8 +3103,8 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey } public Boolean setbit(byte[] key, long offset, byte[] value) { - client.setbit(key, offset, value); - return client.getIntegerReply() == 1; + client.setbit(key, offset, value); + return client.getIntegerReply() == 1; } /** @@ -3164,44 +3184,44 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey } public Object eval(byte[] script, int keyCount, byte[]... params) { - client.setTimeoutInfinite(); - client.eval(script, SafeEncoder.encode(Integer.toString(keyCount)), params); - return client.getOne(); + client.setTimeoutInfinite(); + client.eval(script, SafeEncoder.encode(Integer.toString(keyCount)), + params); + return client.getOne(); } public Object eval(byte[] script) { - client.setTimeoutInfinite(); - client.eval(script, 0); - return client.getOne(); + client.setTimeoutInfinite(); + client.eval(script, 0); + return client.getOne(); } public Object evalsha(byte[] sha1) { - client.setTimeoutInfinite(); - client.evalsha(sha1, 0); - return client.getOne(); + client.setTimeoutInfinite(); + client.evalsha(sha1, 0); + return client.getOne(); } - - public Object evalsha(byte[] sha1, List keys, List args) { - int keyCount = keys == null ? 0 : keys.size(); - int argCount = args == null ? 0 : args.size(); + public Object evalsha(byte[] sha1, List keys, List args) { - byte[][] params = new byte[keyCount + argCount][]; + int keyCount = keys == null ? 0 : keys.size(); + int argCount = args == null ? 0 : args.size(); - for (int i = 0; i < keyCount; i++) - params[i] = keys.get(i); + byte[][] params = new byte[keyCount + argCount][]; - for (int i = 0; i < argCount; i++) - params[keyCount + i] = args.get(i); + for (int i = 0; i < keyCount; i++) + params[i] = keys.get(i); + for (int i = 0; i < argCount; i++) + params[keyCount + i] = args.get(i); - return evalsha(sha1, keyCount, params); - } + return evalsha(sha1, keyCount, params); + } public Object evalsha(byte[] sha1, int keyCount, byte[]... params) { - client.setTimeoutInfinite(); - client.evalsha(sha1, keyCount, params); - return client.getOne(); + client.setTimeoutInfinite(); + client.evalsha(sha1, keyCount, params); + return client.getOne(); } public String scriptFlush() { @@ -3211,7 +3231,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey public List scriptExists(byte[]... sha1) { client.scriptExists(sha1); - return client.getIntegerMultiBulkReply(); + return client.getIntegerMultiBulkReply(); } public byte[] scriptLoad(byte[] script) { @@ -3243,133 +3263,138 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey client.slowlogGet(entries); return client.getBinaryMultiBulkReply(); } - - public Long objectRefcount(byte[] key) { - client.objectRefcount(key); - return client.getIntegerReply(); - } - - public byte[] objectEncoding(byte[] key) { - client.objectEncoding(key); - return client.getBinaryBulkReply(); - } - public Long objectIdletime(byte[] key) { - client.objectIdletime(key); - return client.getIntegerReply(); - } + public Long objectRefcount(byte[] key) { + client.objectRefcount(key); + return client.getIntegerReply(); + } + + public byte[] objectEncoding(byte[] key) { + client.objectEncoding(key); + return client.getBinaryBulkReply(); + } + + public Long objectIdletime(byte[] key) { + client.objectIdletime(key); + return client.getIntegerReply(); + } public Long bitcount(final byte[] key) { - client.bitcount(key); - return client.getIntegerReply(); + client.bitcount(key); + return client.getIntegerReply(); } public Long bitcount(final byte[] key, long start, long end) { - client.bitcount(key, start, end); - return client.getIntegerReply(); + client.bitcount(key, start, end); + return client.getIntegerReply(); } public Long bitop(BitOP op, final byte[] destKey, byte[]... srcKeys) { - client.bitop(op, destKey, srcKeys); - return client.getIntegerReply(); + client.bitop(op, destKey, srcKeys); + return client.getIntegerReply(); } - + public byte[] dump(final byte[] key) { - checkIsInMulti(); - client.dump(key); - return client.getBinaryBulkReply(); + checkIsInMulti(); + client.dump(key); + return client.getBinaryBulkReply(); } - - public String restore(final byte[] key, final int ttl, final byte[] serializedValue) { - checkIsInMulti(); - client.restore(key, ttl, serializedValue); - return client.getStatusCodeReply(); + + public String restore(final byte[] key, final int ttl, + final byte[] serializedValue) { + checkIsInMulti(); + client.restore(key, ttl, serializedValue); + return client.getStatusCodeReply(); } - + public Long pexpire(final byte[] key, final int milliseconds) { - checkIsInMulti(); - client.pexpire(key, milliseconds); - return client.getIntegerReply(); + checkIsInMulti(); + client.pexpire(key, milliseconds); + return client.getIntegerReply(); } - + public Long pexpireAt(final byte[] key, final long millisecondsTimestamp) { - checkIsInMulti(); - client.pexpireAt(key, millisecondsTimestamp); - return client.getIntegerReply(); + checkIsInMulti(); + client.pexpireAt(key, millisecondsTimestamp); + return client.getIntegerReply(); } - + public Long pttl(final byte[] key) { - checkIsInMulti(); - client.pttl(key); - return client.getIntegerReply(); + checkIsInMulti(); + client.pttl(key); + return client.getIntegerReply(); } - + public Double incrByFloat(final byte[] key, final double increment) { - checkIsInMulti(); - client.incrByFloat(key, increment); - String relpy = client.getBulkReply(); - return (relpy != null ? new Double(relpy) : null); + checkIsInMulti(); + client.incrByFloat(key, increment); + String relpy = client.getBulkReply(); + return (relpy != null ? new Double(relpy) : null); } - - public String psetex(final byte[] key, final int milliseconds, final byte[] value) { - checkIsInMulti(); - client.psetex(key, milliseconds, value); - return client.getStatusCodeReply(); + + public String psetex(final byte[] key, final int milliseconds, + final byte[] value) { + checkIsInMulti(); + client.psetex(key, milliseconds, value); + return client.getStatusCodeReply(); } - + public String set(final byte[] key, final byte[] value, final byte[] nxxx) { - checkIsInMulti(); - client.set(key, value, nxxx); - return client.getStatusCodeReply(); + checkIsInMulti(); + client.set(key, value, nxxx); + return client.getStatusCodeReply(); } - - public String set(final byte[] key, final byte[] value, final byte[] nxxx, final byte[] expx, final int time) { - checkIsInMulti(); - client.set(key, value, nxxx, expx, time); - return client.getStatusCodeReply(); + + public String set(final byte[] key, final byte[] value, final byte[] nxxx, + final byte[] expx, final int time) { + checkIsInMulti(); + client.set(key, value, nxxx, expx, time); + return client.getStatusCodeReply(); } - + public String clientKill(final byte[] client) { - checkIsInMulti(); - this.client.clientKill(client); - return this.client.getStatusCodeReply(); + checkIsInMulti(); + this.client.clientKill(client); + return this.client.getStatusCodeReply(); } - + public String clientGetname() { - checkIsInMulti(); - client.clientGetname(); - return client.getBulkReply(); + checkIsInMulti(); + client.clientGetname(); + return client.getBulkReply(); } - + public String clientList() { - checkIsInMulti(); - client.clientList(); - return client.getBulkReply(); + checkIsInMulti(); + client.clientList(); + return client.getBulkReply(); } - + public String clientSetname(final byte[] name) { - checkIsInMulti(); - client.clientSetname(name); - return client.getBulkReply(); + checkIsInMulti(); + client.clientSetname(name); + return client.getBulkReply(); } - + public List time() { - checkIsInMulti(); - client.time(); - return client.getMultiBulkReply(); + checkIsInMulti(); + client.time(); + return client.getMultiBulkReply(); } - - public String migrate(final byte[] host, final int port, final byte[] key, final int destinationDb, final int timeout) { - checkIsInMulti(); - client.migrate(host, port, key, destinationDb, timeout); - return client.getStatusCodeReply(); + + public String migrate(final byte[] host, final int port, final byte[] key, + final int destinationDb, final int timeout) { + checkIsInMulti(); + client.migrate(host, port, key, destinationDb, timeout); + return client.getStatusCodeReply(); } - - public Double hincrByFloat(final byte[] key, final byte[] field, double increment) { - checkIsInMulti(); - client.hincrByFloat(key, field, increment); - String relpy = client.getBulkReply(); - return (relpy != null ? new Double(relpy) : null); + + public Double hincrByFloat(final byte[] key, final byte[] field, + double increment) { + checkIsInMulti(); + client.hincrByFloat(key, field, increment); + String relpy = client.getBulkReply(); + return (relpy != null ? new Double(relpy) : null); } /** @@ -3380,9 +3405,9 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey * so I had to change the name of the method. Sorry :S */ public Long waitReplicas(int replicas, long timeout) { - checkIsInMulti(); - client.waitReplicas(replicas, timeout); - return client.getIntegerReply(); + checkIsInMulti(); + client.waitReplicas(replicas, timeout); + return client.getIntegerReply(); } } diff --git a/src/main/java/redis/clients/jedis/BinaryJedisCommands.java b/src/main/java/redis/clients/jedis/BinaryJedisCommands.java index 3e44f9c..b229f97 100644 --- a/src/main/java/redis/clients/jedis/BinaryJedisCommands.java +++ b/src/main/java/redis/clients/jedis/BinaryJedisCommands.java @@ -5,8 +5,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import redis.clients.jedis.BinaryClient.LIST_POSITION; - /** * Common interface for sharded and non-sharded BinaryJedis */ @@ -116,7 +114,7 @@ public interface BinaryJedisCommands { Long strlen(byte[] key); Long zadd(byte[] key, double score, byte[] member); - + Long zadd(byte[] key, Map scoreMembers); Set zrange(byte[] key, long start, long end); @@ -159,45 +157,45 @@ public interface BinaryJedisCommands { Set zrevrangeByScore(byte[] key, byte[] max, byte[] min); Set zrangeByScore(byte[] key, byte[] min, byte[] max, int offset, - int count); + int count); Set zrevrangeByScore(byte[] key, double max, double min, - int offset, int count); + int offset, int count); Set zrangeByScoreWithScores(byte[] key, double min, double max); Set zrevrangeByScoreWithScores(byte[] key, double max, double min); Set zrangeByScoreWithScores(byte[] key, double min, double max, - int offset, int count); - + int offset, int count); + Set zrevrangeByScore(byte[] key, byte[] max, byte[] min, - int offset, int count); + int offset, int count); Set zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max); - + Set zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min); Set zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max, - int offset, int count); + int offset, int count); Set zrevrangeByScoreWithScores(byte[] key, double max, double min, - int offset, int count); - + int offset, int count); + Set zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min, - int offset, int count); + int offset, int count); Long zremrangeByRank(byte[] key, long start, long end); Long zremrangeByScore(byte[] key, double start, double end); - + Long zremrangeByScore(byte[] key, byte[] start, byte[] end); Long linsert(byte[] key, Client.LIST_POSITION where, byte[] pivot, - byte[] value); - + byte[] value); + Long lpushx(byte[] key, byte[]... arg); - + Long rpushx(byte[] key, byte[]... arg); List blpop(byte[] arg); diff --git a/src/main/java/redis/clients/jedis/BinaryJedisPubSub.java b/src/main/java/redis/clients/jedis/BinaryJedisPubSub.java index 9f34b4a..c271305 100644 --- a/src/main/java/redis/clients/jedis/BinaryJedisPubSub.java +++ b/src/main/java/redis/clients/jedis/BinaryJedisPubSub.java @@ -19,7 +19,7 @@ public abstract class BinaryJedisPubSub { public abstract void onMessage(byte[] channel, byte[] message); public abstract void onPMessage(byte[] pattern, byte[] channel, - byte[] message); + byte[] message); public abstract void onSubscribe(byte[] channel, int subscribedChannels); @@ -30,91 +30,91 @@ public abstract class BinaryJedisPubSub { public abstract void onPSubscribe(byte[] pattern, int subscribedChannels); public void unsubscribe() { - client.unsubscribe(); - client.flush(); + client.unsubscribe(); + client.flush(); } public void unsubscribe(byte[]... channels) { - client.unsubscribe(channels); - client.flush(); + client.unsubscribe(channels); + client.flush(); } public void subscribe(byte[]... channels) { - client.subscribe(channels); - client.flush(); + client.subscribe(channels); + client.flush(); } public void psubscribe(byte[]... patterns) { - client.psubscribe(patterns); - client.flush(); + client.psubscribe(patterns); + client.flush(); } public void punsubscribe() { - client.punsubscribe(); - client.flush(); + client.punsubscribe(); + client.flush(); } public void punsubscribe(byte[]... patterns) { - client.punsubscribe(patterns); - client.flush(); + client.punsubscribe(patterns); + client.flush(); } public boolean isSubscribed() { - return subscribedChannels > 0; + return subscribedChannels > 0; } public void proceedWithPatterns(Client client, byte[]... patterns) { - this.client = client; - client.psubscribe(patterns); - process(client); + this.client = client; + client.psubscribe(patterns); + process(client); } public void proceed(Client client, byte[]... channels) { - this.client = client; - client.subscribe(channels); - process(client); + this.client = client; + client.subscribe(channels); + process(client); } private void process(Client client) { - do { - List reply = client.getObjectMultiBulkReply(); - final Object firstObj = reply.get(0); - if (!(firstObj instanceof byte[])) { - throw new JedisException("Unknown message type: " + firstObj); - } - final byte[] resp = (byte[]) firstObj; - if (Arrays.equals(SUBSCRIBE.raw, resp)) { - subscribedChannels = ((Long) reply.get(2)).intValue(); - final byte[] bchannel = (byte[]) reply.get(1); - onSubscribe(bchannel, subscribedChannels); - } else if (Arrays.equals(UNSUBSCRIBE.raw, resp)) { - subscribedChannels = ((Long) reply.get(2)).intValue(); - final byte[] bchannel = (byte[]) reply.get(1); - onUnsubscribe(bchannel, subscribedChannels); - } else if (Arrays.equals(MESSAGE.raw, resp)) { - final byte[] bchannel = (byte[]) reply.get(1); - final byte[] bmesg = (byte[]) reply.get(2); - onMessage(bchannel, bmesg); - } else if (Arrays.equals(PMESSAGE.raw, resp)) { - final byte[] bpattern = (byte[]) reply.get(1); - final byte[] bchannel = (byte[]) reply.get(2); - final byte[] bmesg = (byte[]) reply.get(3); - onPMessage(bpattern, bchannel, bmesg); - } else if (Arrays.equals(PSUBSCRIBE.raw, resp)) { - subscribedChannels = ((Long) reply.get(2)).intValue(); - final byte[] bpattern = (byte[]) reply.get(1); - onPSubscribe(bpattern, subscribedChannels); - } else if (Arrays.equals(PUNSUBSCRIBE.raw, resp)) { - subscribedChannels = ((Long) reply.get(2)).intValue(); - final byte[] bpattern = (byte[]) reply.get(1); - onPUnsubscribe(bpattern, subscribedChannels); - } else { - throw new JedisException("Unknown message type: " + firstObj); - } - } while (isSubscribed()); + do { + List reply = client.getObjectMultiBulkReply(); + final Object firstObj = reply.get(0); + if (!(firstObj instanceof byte[])) { + throw new JedisException("Unknown message type: " + firstObj); + } + final byte[] resp = (byte[]) firstObj; + if (Arrays.equals(SUBSCRIBE.raw, resp)) { + subscribedChannels = ((Long) reply.get(2)).intValue(); + final byte[] bchannel = (byte[]) reply.get(1); + onSubscribe(bchannel, subscribedChannels); + } else if (Arrays.equals(UNSUBSCRIBE.raw, resp)) { + subscribedChannels = ((Long) reply.get(2)).intValue(); + final byte[] bchannel = (byte[]) reply.get(1); + onUnsubscribe(bchannel, subscribedChannels); + } else if (Arrays.equals(MESSAGE.raw, resp)) { + final byte[] bchannel = (byte[]) reply.get(1); + final byte[] bmesg = (byte[]) reply.get(2); + onMessage(bchannel, bmesg); + } else if (Arrays.equals(PMESSAGE.raw, resp)) { + final byte[] bpattern = (byte[]) reply.get(1); + final byte[] bchannel = (byte[]) reply.get(2); + final byte[] bmesg = (byte[]) reply.get(3); + onPMessage(bpattern, bchannel, bmesg); + } else if (Arrays.equals(PSUBSCRIBE.raw, resp)) { + subscribedChannels = ((Long) reply.get(2)).intValue(); + final byte[] bpattern = (byte[]) reply.get(1); + onPSubscribe(bpattern, subscribedChannels); + } else if (Arrays.equals(PUNSUBSCRIBE.raw, resp)) { + subscribedChannels = ((Long) reply.get(2)).intValue(); + final byte[] bpattern = (byte[]) reply.get(1); + onPUnsubscribe(bpattern, subscribedChannels); + } else { + throw new JedisException("Unknown message type: " + firstObj); + } + } while (isSubscribed()); } public int getSubscribedChannels() { - return subscribedChannels; + return subscribedChannels; } } \ No newline at end of file diff --git a/src/main/java/redis/clients/jedis/BinaryRedisPipeline.java b/src/main/java/redis/clients/jedis/BinaryRedisPipeline.java index d48800c..73037b7 100644 --- a/src/main/java/redis/clients/jedis/BinaryRedisPipeline.java +++ b/src/main/java/redis/clients/jedis/BinaryRedisPipeline.java @@ -67,7 +67,7 @@ public interface BinaryRedisPipeline { Response lindex(byte[] key, long index); Response linsert(byte[] key, BinaryClient.LIST_POSITION where, - byte[] pivot, byte[] value); + byte[] pivot, byte[] value); Response llen(byte[] key); @@ -117,8 +117,7 @@ public interface BinaryRedisPipeline { Response> sort(byte[] key); - Response> sort(byte[] key, - SortingParams sortingParameters); + Response> sort(byte[] key, SortingParams sortingParameters); Response spop(byte[] key); @@ -144,53 +143,49 @@ public interface BinaryRedisPipeline { Response> zrange(byte[] key, long start, long end); - Response> zrangeByScore(byte[] key, double min, - double max); + Response> zrangeByScore(byte[] key, double min, double max); - Response> zrangeByScore(byte[] key, byte[] min, - byte[] max); + Response> zrangeByScore(byte[] key, byte[] min, byte[] max); - Response> zrangeByScore(byte[] key, double min, - double max, int offset, int count); + Response> zrangeByScore(byte[] key, double min, double max, + int offset, int count); - Response> zrangeByScore(byte[] key, byte[] min, - byte[] max, int offset, int count); + Response> zrangeByScore(byte[] key, byte[] min, byte[] max, + int offset, int count); Response> zrangeByScoreWithScores(byte[] key, double min, - double max); + double max); Response> zrangeByScoreWithScores(byte[] key, byte[] min, - byte[] max); + byte[] max); Response> zrangeByScoreWithScores(byte[] key, double min, - double max, int offset, int count); + double max, int offset, int count); Response> zrangeByScoreWithScores(byte[] key, byte[] min, - byte[] max, int offset, int count); + byte[] max, int offset, int count); - Response> zrevrangeByScore(byte[] key, double max, - double min); + Response> zrevrangeByScore(byte[] key, double max, double min); - Response> zrevrangeByScore(byte[] key, byte[] max, - byte[] min); + Response> zrevrangeByScore(byte[] key, byte[] max, byte[] min); - Response> zrevrangeByScore(byte[] key, double max, - double min, int offset, int count); + Response> zrevrangeByScore(byte[] key, double max, double min, + int offset, int count); - Response> zrevrangeByScore(byte[] key, byte[] max, - byte[] min, int offset, int count); + Response> zrevrangeByScore(byte[] key, byte[] max, byte[] min, + int offset, int count); - Response> zrevrangeByScoreWithScores(byte[] key, - double max, double min); + Response> zrevrangeByScoreWithScores(byte[] key, double max, + double min); - Response> zrevrangeByScoreWithScores(byte[] key, - byte[] max, byte[] min); + Response> zrevrangeByScoreWithScores(byte[] key, byte[] max, + byte[] min); - Response> zrevrangeByScoreWithScores(byte[] key, - double max, double min, int offset, int count); + Response> zrevrangeByScoreWithScores(byte[] key, double max, + double min, int offset, int count); - Response> zrevrangeByScoreWithScores(byte[] key, - byte[] max, byte[] min, int offset, int count); + Response> zrevrangeByScoreWithScores(byte[] key, byte[] max, + byte[] min, int offset, int count); Response> zrangeWithScores(byte[] key, long start, long end); @@ -206,8 +201,7 @@ public interface BinaryRedisPipeline { Response> zrevrange(byte[] key, long start, long end); - Response> zrevrangeWithScores(byte[] key, long start, - long end); + Response> zrevrangeWithScores(byte[] key, long start, long end); Response zrevrank(byte[] key, byte[] member); diff --git a/src/main/java/redis/clients/jedis/BinaryScriptingCommands.java b/src/main/java/redis/clients/jedis/BinaryScriptingCommands.java index 092ce7a..face8d8 100644 --- a/src/main/java/redis/clients/jedis/BinaryScriptingCommands.java +++ b/src/main/java/redis/clients/jedis/BinaryScriptingCommands.java @@ -1,6 +1,5 @@ package redis.clients.jedis; - import java.util.List; public interface BinaryScriptingCommands { @@ -8,7 +7,7 @@ public interface BinaryScriptingCommands { Object eval(byte[] script, byte[] keyCount, byte[]... params); Object eval(byte[] script, int keyCount, byte[]... params); - + Object eval(byte[] script, List keys, List args); Object eval(byte[] script); diff --git a/src/main/java/redis/clients/jedis/BitOP.java b/src/main/java/redis/clients/jedis/BitOP.java index 5e3ee89..8066a69 100644 --- a/src/main/java/redis/clients/jedis/BitOP.java +++ b/src/main/java/redis/clients/jedis/BitOP.java @@ -1,8 +1,5 @@ package redis.clients.jedis; public enum BitOP { - AND, - OR, - XOR, - NOT; + AND, OR, XOR, NOT; } diff --git a/src/main/java/redis/clients/jedis/BuilderFactory.java b/src/main/java/redis/clients/jedis/BuilderFactory.java index bebd2d6..d8ae47b 100755 --- a/src/main/java/redis/clients/jedis/BuilderFactory.java +++ b/src/main/java/redis/clients/jedis/BuilderFactory.java @@ -1,249 +1,256 @@ package redis.clients.jedis; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + import redis.clients.util.SafeEncoder; -import java.util.*; - public class BuilderFactory { public static final Builder DOUBLE = new Builder() { - public Double build(Object data) { - String asString = STRING.build(data); - return asString == null ? null : Double.valueOf(asString); - } + public Double build(Object data) { + String asString = STRING.build(data); + return asString == null ? null : Double.valueOf(asString); + } - public String toString() { - return "double"; - } + public String toString() { + return "double"; + } }; public static final Builder BOOLEAN = new Builder() { - public Boolean build(Object data) { - return ((Long) data) == 1; - } + public Boolean build(Object data) { + return ((Long) data) == 1; + } - public String toString() { - return "boolean"; - } + public String toString() { + return "boolean"; + } }; public static final Builder BYTE_ARRAY = new Builder() { - public byte[] build(Object data) { - return ((byte[]) data); // deleted == 1 - } + public byte[] build(Object data) { + return ((byte[]) data); // deleted == 1 + } - public String toString() { - return "byte[]"; - } + public String toString() { + return "byte[]"; + } }; public static final Builder LONG = new Builder() { - public Long build(Object data) { - return (Long) data; - } + public Long build(Object data) { + return (Long) data; + } - public String toString() { - return "long"; - } + public String toString() { + return "long"; + } }; public static final Builder STRING = new Builder() { - public String build(Object data) { - return data == null ? null : SafeEncoder.encode((byte[]) data); - } + public String build(Object data) { + return data == null ? null : SafeEncoder.encode((byte[]) data); + } - public String toString() { - return "string"; - } + public String toString() { + return "string"; + } }; public static final Builder> STRING_LIST = new Builder>() { - @SuppressWarnings("unchecked") - public List build(Object data) { - if (null == data) { - return null; - } - List l = (List) data; - final ArrayList result = new ArrayList(l.size()); - for (final byte[] barray : l) { - if (barray == null) { - result.add(null); - } else { - result.add(SafeEncoder.encode(barray)); - } - } - return result; - } + @SuppressWarnings("unchecked") + public List build(Object data) { + if (null == data) { + return null; + } + List l = (List) data; + final ArrayList result = new ArrayList(l.size()); + for (final byte[] barray : l) { + if (barray == null) { + result.add(null); + } else { + result.add(SafeEncoder.encode(barray)); + } + } + return result; + } - public String toString() { - return "List"; - } + public String toString() { + return "List"; + } }; public static final Builder> STRING_MAP = new Builder>() { - @SuppressWarnings("unchecked") - public Map build(Object data) { - final List flatHash = (List) data; - final Map hash = new HashMap(); - final Iterator iterator = flatHash.iterator(); - while (iterator.hasNext()) { - hash.put(SafeEncoder.encode(iterator.next()), SafeEncoder - .encode(iterator.next())); - } + @SuppressWarnings("unchecked") + public Map build(Object data) { + final List flatHash = (List) data; + final Map hash = new HashMap(); + final Iterator iterator = flatHash.iterator(); + while (iterator.hasNext()) { + hash.put(SafeEncoder.encode(iterator.next()), + SafeEncoder.encode(iterator.next())); + } - return hash; - } + return hash; + } - public String toString() { - return "Map"; - } + public String toString() { + return "Map"; + } }; public static final Builder> STRING_SET = new Builder>() { - @SuppressWarnings("unchecked") - public Set build(Object data) { - if (null == data) { - return null; - } - List l = (List) data; - final Set result = new HashSet(l.size()); - for (final byte[] barray : l) { - if (barray == null) { - result.add(null); - } else { - result.add(SafeEncoder.encode(barray)); - } - } - return result; - } + @SuppressWarnings("unchecked") + public Set build(Object data) { + if (null == data) { + return null; + } + List l = (List) data; + final Set result = new HashSet(l.size()); + for (final byte[] barray : l) { + if (barray == null) { + result.add(null); + } else { + result.add(SafeEncoder.encode(barray)); + } + } + return result; + } - public String toString() { - return "Set"; - } + public String toString() { + return "Set"; + } }; public static final Builder> BYTE_ARRAY_LIST = new Builder>() { - @SuppressWarnings("unchecked") - public List build(Object data) { - if (null == data) { - return null; - } - List l = (List) data; + @SuppressWarnings("unchecked") + public List build(Object data) { + if (null == data) { + return null; + } + List l = (List) data; - return l; - } + return l; + } - public String toString() { - return "List"; - } + public String toString() { + return "List"; + } }; public static final Builder> BYTE_ARRAY_ZSET = new Builder>() { - @SuppressWarnings("unchecked") - public Set build(Object data) { - if (null == data) { - return null; - } - List l = (List) data; - final Set result = new LinkedHashSet(l); - for (final byte[] barray : l) { - if (barray == null) { - result.add(null); - } else { - result.add(barray); - } - } - return result; - } + @SuppressWarnings("unchecked") + public Set build(Object data) { + if (null == data) { + return null; + } + List l = (List) data; + final Set result = new LinkedHashSet(l); + for (final byte[] barray : l) { + if (barray == null) { + result.add(null); + } else { + result.add(barray); + } + } + return result; + } - public String toString() { - return "ZSet"; - } + public String toString() { + return "ZSet"; + } }; public static final Builder> BYTE_ARRAY_MAP = new Builder>() { - @SuppressWarnings("unchecked") - public Map build(Object data) { - final List flatHash = (List) data; - final Map hash = new HashMap(); - final Iterator iterator = flatHash.iterator(); - while (iterator.hasNext()) { - hash.put(iterator.next(), iterator.next()); - } + @SuppressWarnings("unchecked") + public Map build(Object data) { + final List flatHash = (List) data; + final Map hash = new HashMap(); + final Iterator iterator = flatHash.iterator(); + while (iterator.hasNext()) { + hash.put(iterator.next(), iterator.next()); + } - return hash; - } + return hash; + } - public String toString() { - return "Map"; - } + public String toString() { + return "Map"; + } }; public static final Builder> STRING_ZSET = new Builder>() { - @SuppressWarnings("unchecked") - public Set build(Object data) { - if (null == data) { - return null; - } - List l = (List) data; - final Set result = new LinkedHashSet(l.size()); - for (final byte[] barray : l) { - if (barray == null) { - result.add(null); - } else { - result.add(SafeEncoder.encode(barray)); - } - } - return result; - } + @SuppressWarnings("unchecked") + public Set build(Object data) { + if (null == data) { + return null; + } + List l = (List) data; + final Set result = new LinkedHashSet(l.size()); + for (final byte[] barray : l) { + if (barray == null) { + result.add(null); + } else { + result.add(SafeEncoder.encode(barray)); + } + } + return result; + } - public String toString() { - return "ZSet"; - } + public String toString() { + return "ZSet"; + } }; public static final Builder> TUPLE_ZSET = new Builder>() { - @SuppressWarnings("unchecked") - public Set build(Object data) { - if (null == data) { - return null; - } - List l = (List) data; - final Set result = new LinkedHashSet(l.size()); - Iterator iterator = l.iterator(); - while (iterator.hasNext()) { - result.add(new Tuple(SafeEncoder.encode(iterator.next()), - Double.valueOf(SafeEncoder.encode(iterator.next())))); - } - return result; - } + @SuppressWarnings("unchecked") + public Set build(Object data) { + if (null == data) { + return null; + } + List l = (List) data; + final Set result = new LinkedHashSet(l.size()); + Iterator iterator = l.iterator(); + while (iterator.hasNext()) { + result.add(new Tuple(SafeEncoder.encode(iterator.next()), + Double.valueOf(SafeEncoder.encode(iterator.next())))); + } + return result; + } - public String toString() { - return "ZSet"; - } + public String toString() { + return "ZSet"; + } }; public static final Builder> TUPLE_ZSET_BINARY = new Builder>() { - @SuppressWarnings("unchecked") - public Set build(Object data) { - if (null == data) { - return null; - } - List l = (List) data; - final Set result = new LinkedHashSet(l.size()); - Iterator iterator = l.iterator(); - while (iterator.hasNext()) { - result.add(new Tuple(iterator.next(), Double - .valueOf(SafeEncoder.encode(iterator.next())))); - } + @SuppressWarnings("unchecked") + public Set build(Object data) { + if (null == data) { + return null; + } + List l = (List) data; + final Set result = new LinkedHashSet(l.size()); + Iterator iterator = l.iterator(); + while (iterator.hasNext()) { + result.add(new Tuple(iterator.next(), Double + .valueOf(SafeEncoder.encode(iterator.next())))); + } - return result; + return result; - } + } - public String toString() { - return "ZSet"; - } + public String toString() { + return "ZSet"; + } }; } diff --git a/src/main/java/redis/clients/jedis/Client.java b/src/main/java/redis/clients/jedis/Client.java index a2ec464..e793ce7 100644 --- a/src/main/java/redis/clients/jedis/Client.java +++ b/src/main/java/redis/clients/jedis/Client.java @@ -1,6 +1,6 @@ package redis.clients.jedis; -import redis.clients.util.SafeEncoder; +import static redis.clients.jedis.Protocol.toByteArray; import java.util.ArrayList; import java.util.HashMap; @@ -8,8 +8,7 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; -import static redis.clients.jedis.Protocol.toByteArray; -import static redis.clients.jedis.Protocol.Command.HSCAN; +import redis.clients.util.SafeEncoder; public class Client extends BinaryClient implements Commands { public Client(final String host) { @@ -24,8 +23,10 @@ public class Client extends BinaryClient implements Commands { set(SafeEncoder.encode(key), SafeEncoder.encode(value)); } - public void set(final String key, final String value, final String nxxx, final String expx, final long time) { - set(SafeEncoder.encode(key), SafeEncoder.encode(value), SafeEncoder.encode(nxxx), SafeEncoder.encode(expx), time); + public void set(final String key, final String value, final String nxxx, + final String expx, final long time) { + set(SafeEncoder.encode(key), SafeEncoder.encode(value), + SafeEncoder.encode(nxxx), SafeEncoder.encode(expx), time); } public void get(final String key) { @@ -392,14 +393,14 @@ public class Client extends BinaryClient implements Commands { } blpop(bargs); } - + public void blpop(final int timeout, final String... keys) { - List args = new ArrayList(); - for (String arg : keys) { - args.add(arg); - } - args.add(String.valueOf(timeout)); - blpop(args.toArray(new String[args.size()])); + List args = new ArrayList(); + for (String arg : keys) { + args.add(arg); + } + args.add(String.valueOf(timeout)); + blpop(args.toArray(new String[args.size()])); } public void sort(final String key, final SortingParams sortingParameters, @@ -419,14 +420,14 @@ public class Client extends BinaryClient implements Commands { } brpop(bargs); } - + public void brpop(final int timeout, final String... keys) { - List args = new ArrayList(); - for (String arg : keys) { - args.add(arg); - } - args.add(String.valueOf(timeout)); - brpop(args.toArray(new String[args.size()])); + List args = new ArrayList(); + for (String arg : keys) { + args.add(arg); + } + args.add(String.valueOf(timeout)); + brpop(args.toArray(new String[args.size()])); } public void zcount(final String key, final double min, final double max) { @@ -621,7 +622,7 @@ public class Client extends BinaryClient implements Commands { } public void setbit(final String key, final long offset, final String value) { - setbit(SafeEncoder.encode(key), offset, SafeEncoder.encode(value)); + setbit(SafeEncoder.encode(key), offset, SafeEncoder.encode(value)); } public void getbit(String key, long offset) { @@ -709,19 +710,19 @@ public class Client extends BinaryClient implements Commands { public void scriptLoad(String script) { scriptLoad(SafeEncoder.encode(script)); } - - public void zadd(String key, Map scoreMembers) { - - HashMap binaryScoreMembers = new HashMap(); - for (Map.Entry entry : scoreMembers.entrySet()) { - - binaryScoreMembers.put(SafeEncoder.encode(entry.getKey()), entry.getValue()); - } - - zaddBinary(SafeEncoder.encode(key), binaryScoreMembers); + public void zadd(String key, Map scoreMembers) { + + HashMap binaryScoreMembers = new HashMap(); + + for (Map.Entry entry : scoreMembers.entrySet()) { + + binaryScoreMembers.put(SafeEncoder.encode(entry.getKey()), + entry.getValue()); } + zaddBinary(SafeEncoder.encode(key), binaryScoreMembers); + } public void objectRefcount(String key) { objectRefcount(SafeEncoder.encode(key)); @@ -736,15 +737,15 @@ public class Client extends BinaryClient implements Commands { } public void bitcount(final String key) { - bitcount(SafeEncoder.encode(key)); + bitcount(SafeEncoder.encode(key)); } public void bitcount(final String key, long start, long end) { - bitcount(SafeEncoder.encode(key), start, end); + bitcount(SafeEncoder.encode(key), start, end); } public void bitop(BitOP op, final String destKey, String... srcKeys) { - bitop(op, SafeEncoder.encode(destKey), getByteParams(srcKeys)); + bitop(op, SafeEncoder.encode(destKey), getByteParams(srcKeys)); } public void sentinel(final String... args) { @@ -755,132 +756,144 @@ public class Client extends BinaryClient implements Commands { sentinel(arg); } - public void dump(final String key) { - dump(SafeEncoder.encode(key)); + public void dump(final String key) { + dump(SafeEncoder.encode(key)); } - - public void restore(final String key, final int ttl, final byte[] serializedValue) { - restore(SafeEncoder.encode(key), ttl, serializedValue); + + public void restore(final String key, final int ttl, + final byte[] serializedValue) { + restore(SafeEncoder.encode(key), ttl, serializedValue); } - + public void pexpire(final String key, final int milliseconds) { - pexpire(SafeEncoder.encode(key), milliseconds); + pexpire(SafeEncoder.encode(key), milliseconds); } - + public void pexpireAt(final String key, final long millisecondsTimestamp) { - pexpireAt(SafeEncoder.encode(key), millisecondsTimestamp); + pexpireAt(SafeEncoder.encode(key), millisecondsTimestamp); } - + public void pttl(final String key) { - pttl(SafeEncoder.encode(key)); + pttl(SafeEncoder.encode(key)); } - + public void incrByFloat(final String key, final double increment) { - incrByFloat(SafeEncoder.encode(key), increment); + incrByFloat(SafeEncoder.encode(key), increment); } - - public void psetex(final String key, final int milliseconds, final String value) { - psetex(SafeEncoder.encode(key), milliseconds, SafeEncoder.encode(value)); + + public void psetex(final String key, final int milliseconds, + final String value) { + psetex(SafeEncoder.encode(key), milliseconds, SafeEncoder.encode(value)); } - + public void set(final String key, final String value, final String nxxx) { - set(SafeEncoder.encode(key), SafeEncoder.encode(value), SafeEncoder.encode(nxxx)); + set(SafeEncoder.encode(key), SafeEncoder.encode(value), + SafeEncoder.encode(nxxx)); } - - public void set(final String key, final String value, final String nxxx, final String expx, final int time) { - set(SafeEncoder.encode(key), SafeEncoder.encode(value), SafeEncoder.encode(nxxx), SafeEncoder.encode(expx), time); + + public void set(final String key, final String value, final String nxxx, + final String expx, final int time) { + set(SafeEncoder.encode(key), SafeEncoder.encode(value), + SafeEncoder.encode(nxxx), SafeEncoder.encode(expx), time); } - + public void srandmember(final String key, final int count) { - srandmember(SafeEncoder.encode(key), count); + srandmember(SafeEncoder.encode(key), count); } public void clientKill(final String client) { - clientKill(SafeEncoder.encode(client)); + clientKill(SafeEncoder.encode(client)); } - + public void clientSetname(final String name) { - clientSetname(SafeEncoder.encode(name)); + clientSetname(SafeEncoder.encode(name)); } - - public void migrate(final String host, final int port, final String key, final int destinationDb, final int timeout) { - migrate(SafeEncoder.encode(host), port, SafeEncoder.encode(key), destinationDb, timeout); + + public void migrate(final String host, final int port, final String key, + final int destinationDb, final int timeout) { + migrate(SafeEncoder.encode(host), port, SafeEncoder.encode(key), + destinationDb, timeout); } - - public void hincrByFloat(final String key, final String field, double increment) { - hincrByFloat(SafeEncoder.encode(key), SafeEncoder.encode(field), increment); + + public void hincrByFloat(final String key, final String field, + double increment) { + hincrByFloat(SafeEncoder.encode(key), SafeEncoder.encode(field), + increment); } - + public void hscan(final String key, int cursor, final ScanParams params) { - hscan(SafeEncoder.encode(key), cursor, params); + hscan(SafeEncoder.encode(key), cursor, params); } - + public void sscan(final String key, int cursor, final ScanParams params) { - sscan(SafeEncoder.encode(key), cursor, params); + sscan(SafeEncoder.encode(key), cursor, params); } - + public void zscan(final String key, int cursor, final ScanParams params) { - zscan(SafeEncoder.encode(key), cursor, params); + zscan(SafeEncoder.encode(key), cursor, params); } public void cluster(final String subcommand, final int... 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++) { - arg[i] = toByteArray(args[i-1]); + arg[i] = toByteArray(args[i - 1]); } arg[0] = SafeEncoder.encode(subcommand); cluster(arg); } public void cluster(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++) { - arg[i] = SafeEncoder.encode(args[i-1]); + arg[i] = SafeEncoder.encode(args[i - 1]); } arg[0] = SafeEncoder.encode(subcommand); cluster(arg); } - + public void cluster(final String subcommand) { final byte[][] arg = new byte[1][]; arg[0] = SafeEncoder.encode(subcommand); cluster(arg); } - + public void clusterNodes() { cluster(Protocol.CLUSTER_NODES); } - + public void clusterMeet(final String ip, final int port) { cluster(Protocol.CLUSTER_MEET, ip, String.valueOf(port)); } - - public void clusterAddSlots(final int ...slots) { + + public void clusterAddSlots(final int... slots) { cluster(Protocol.CLUSTER_ADDSLOTS, slots); } - - public void clusterDelSlots(final int ...slots) { + + public void clusterDelSlots(final int... slots) { cluster(Protocol.CLUSTER_DELSLOTS, slots); } - + public void clusterInfo() { cluster(Protocol.CLUSTER_INFO); } - + public void clusterGetKeysInSlot(final int slot, final int count) { - final int[] args = new int[]{ slot, count }; - cluster(Protocol.CLUSTER_GETKEYSINSLOT, args); + final int[] args = new int[] { slot, count }; + cluster(Protocol.CLUSTER_GETKEYSINSLOT, args); } - + public void clusterSetSlotNode(final int slot, final String nodeId) { - cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot), Protocol.CLUSTER_SETSLOT_NODE, nodeId); + cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot), + Protocol.CLUSTER_SETSLOT_NODE, nodeId); } - + public void clusterSetSlotMigrating(final int slot, final String nodeId) { - cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot), Protocol.CLUSTER_SETSLOT_MIGRATING, nodeId); + cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot), + Protocol.CLUSTER_SETSLOT_MIGRATING, nodeId); } - + public void clusterSetSlotImporting(final int slot, final String nodeId) { - cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot), Protocol.CLUSTER_SETSLOT_IMPORTING, nodeId); + cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot), + Protocol.CLUSTER_SETSLOT_IMPORTING, nodeId); } } diff --git a/src/main/java/redis/clients/jedis/Commands.java b/src/main/java/redis/clients/jedis/Commands.java index c6b26f7..2d7ea92 100644 --- a/src/main/java/redis/clients/jedis/Commands.java +++ b/src/main/java/redis/clients/jedis/Commands.java @@ -143,8 +143,8 @@ public interface Commands { public void srandmember(final String key); public void zadd(final String key, final double score, final String member); - - public void zadd(final String key, final Map scoreMembers); + + public void zadd(final String key, final Map scoreMembers); public void zrange(final String key, final long start, final long end); diff --git a/src/main/java/redis/clients/jedis/Connection.java b/src/main/java/redis/clients/jedis/Connection.java index 1c42b94..50d7b97 100644 --- a/src/main/java/redis/clients/jedis/Connection.java +++ b/src/main/java/redis/clients/jedis/Connection.java @@ -25,218 +25,222 @@ public class Connection { private int timeout = Protocol.DEFAULT_TIMEOUT; public Socket getSocket() { - return socket; + return socket; } public int getTimeout() { - return timeout; + return timeout; } public void setTimeout(final int timeout) { - this.timeout = timeout; + this.timeout = timeout; } public void setTimeoutInfinite() { - try { - if(!isConnected()) { - connect(); - } - socket.setKeepAlive(true); - socket.setSoTimeout(0); - } catch (SocketException ex) { - throw new JedisException(ex); - } + try { + if (!isConnected()) { + connect(); + } + socket.setKeepAlive(true); + socket.setSoTimeout(0); + } catch (SocketException ex) { + throw new JedisException(ex); + } } public void rollbackTimeout() { - try { - socket.setSoTimeout(timeout); - socket.setKeepAlive(false); - } catch (SocketException ex) { - throw new JedisException(ex); - } + try { + socket.setSoTimeout(timeout); + socket.setKeepAlive(false); + } catch (SocketException ex) { + throw new JedisException(ex); + } } public Connection(final String host) { - super(); - this.host = host; + super(); + this.host = host; } protected void flush() { - try { - outputStream.flush(); - } catch (IOException e) { - throw new JedisConnectionException(e); - } + try { + outputStream.flush(); + } catch (IOException e) { + throw new JedisConnectionException(e); + } } protected Connection sendCommand(final Command cmd, final String... args) { - final byte[][] bargs = new byte[args.length][]; - for (int i = 0; i < args.length; i++) { - bargs[i] = SafeEncoder.encode(args[i]); - } - return sendCommand(cmd, bargs); + final byte[][] bargs = new byte[args.length][]; + for (int i = 0; i < args.length; i++) { + bargs[i] = SafeEncoder.encode(args[i]); + } + return sendCommand(cmd, bargs); } protected Connection sendCommand(final Command cmd, final byte[]... args) { - connect(); - Protocol.sendCommand(outputStream, cmd, args); - pipelinedCommands++; - return this; + connect(); + Protocol.sendCommand(outputStream, cmd, args); + pipelinedCommands++; + return this; } - + protected Connection sendCommand(final Command cmd) { - connect(); - Protocol.sendCommand(outputStream, cmd, new byte[0][]); - pipelinedCommands++; - return this; + connect(); + Protocol.sendCommand(outputStream, cmd, new byte[0][]); + pipelinedCommands++; + return this; } public Connection(final String host, final int port) { - super(); - this.host = host; - this.port = port; + super(); + this.host = host; + this.port = port; } public String getHost() { - return host; + return host; } public void setHost(final String host) { - this.host = host; + this.host = host; } public int getPort() { - return port; + return port; } public void setPort(final int port) { - this.port = port; + this.port = port; } public Connection() { - + } public void connect() { - if (!isConnected()) { - try { - socket = new Socket(); - //->@wjw_add - socket.setReuseAddress(true); - socket.setKeepAlive(true); //Will monitor the TCP connection is valid - socket.setTcpNoDelay(true); //Socket buffer Whetherclosed, to ensure timely delivery of data - socket.setSoLinger(true,0); //Control calls close () method, the underlying socket is closed immediately - //<-@wjw_add + if (!isConnected()) { + try { + socket = new Socket(); + // ->@wjw_add + socket.setReuseAddress(true); + socket.setKeepAlive(true); // Will monitor the TCP connection is + // valid + socket.setTcpNoDelay(true); // Socket buffer Whetherclosed, to + // ensure timely delivery of data + socket.setSoLinger(true, 0); // Control calls close () method, + // the underlying socket is closed + // immediately + // <-@wjw_add - socket.connect(new InetSocketAddress(host, port), timeout); - socket.setSoTimeout(timeout); - outputStream = new RedisOutputStream(socket.getOutputStream()); - inputStream = new RedisInputStream(socket.getInputStream()); - } catch (IOException ex) { - throw new JedisConnectionException(ex); - } - } + socket.connect(new InetSocketAddress(host, port), timeout); + socket.setSoTimeout(timeout); + outputStream = new RedisOutputStream(socket.getOutputStream()); + inputStream = new RedisInputStream(socket.getInputStream()); + } catch (IOException ex) { + throw new JedisConnectionException(ex); + } + } } public void disconnect() { - if (isConnected()) { - try { - inputStream.close(); - outputStream.close(); - if (!socket.isClosed()) { - socket.close(); - } - } catch (IOException ex) { - throw new JedisConnectionException(ex); - } - } + if (isConnected()) { + try { + inputStream.close(); + outputStream.close(); + if (!socket.isClosed()) { + socket.close(); + } + } catch (IOException ex) { + throw new JedisConnectionException(ex); + } + } } public boolean isConnected() { - return socket != null && socket.isBound() && !socket.isClosed() - && socket.isConnected() && !socket.isInputShutdown() - && !socket.isOutputShutdown(); + return socket != null && socket.isBound() && !socket.isClosed() + && socket.isConnected() && !socket.isInputShutdown() + && !socket.isOutputShutdown(); } protected String getStatusCodeReply() { - flush(); - pipelinedCommands--; - final byte[] resp = (byte[]) Protocol.read(inputStream); - if (null == resp) { - return null; - } else { - return SafeEncoder.encode(resp); - } + flush(); + pipelinedCommands--; + final byte[] resp = (byte[]) Protocol.read(inputStream); + if (null == resp) { + return null; + } else { + return SafeEncoder.encode(resp); + } } public String getBulkReply() { - final byte[] result = getBinaryBulkReply(); - if (null != result) { - return SafeEncoder.encode(result); - } else { - return null; - } + final byte[] result = getBinaryBulkReply(); + if (null != result) { + return SafeEncoder.encode(result); + } else { + return null; + } } public byte[] getBinaryBulkReply() { - flush(); - pipelinedCommands--; - return (byte[]) Protocol.read(inputStream); + flush(); + pipelinedCommands--; + return (byte[]) Protocol.read(inputStream); } public Long getIntegerReply() { - flush(); - pipelinedCommands--; - return (Long) Protocol.read(inputStream); + flush(); + pipelinedCommands--; + return (Long) Protocol.read(inputStream); } public List getMultiBulkReply() { - return BuilderFactory.STRING_LIST.build(getBinaryMultiBulkReply()); + return BuilderFactory.STRING_LIST.build(getBinaryMultiBulkReply()); } @SuppressWarnings("unchecked") public List getBinaryMultiBulkReply() { - flush(); - pipelinedCommands--; - return (List) Protocol.read(inputStream); + flush(); + pipelinedCommands--; + return (List) Protocol.read(inputStream); } @SuppressWarnings("unchecked") public List getObjectMultiBulkReply() { - flush(); - pipelinedCommands--; - return (List) Protocol.read(inputStream); + flush(); + pipelinedCommands--; + return (List) Protocol.read(inputStream); } - + @SuppressWarnings("unchecked") public List getIntegerMultiBulkReply() { - flush(); - pipelinedCommands--; - return (List) Protocol.read(inputStream); + flush(); + pipelinedCommands--; + return (List) Protocol.read(inputStream); } public List getAll() { - return getAll(0); + return getAll(0); } public List getAll(int except) { - List all = new ArrayList(); - flush(); - while (pipelinedCommands > except) { - try{ - all.add(Protocol.read(inputStream)); - }catch(JedisDataException e){ - all.add(e); - } - pipelinedCommands--; - } - return all; + List all = new ArrayList(); + flush(); + while (pipelinedCommands > except) { + try { + all.add(Protocol.read(inputStream)); + } catch (JedisDataException e) { + all.add(e); + } + pipelinedCommands--; + } + return all; } public Object getOne() { - flush(); - pipelinedCommands--; - return Protocol.read(inputStream); + flush(); + pipelinedCommands--; + return Protocol.read(inputStream); } } diff --git a/src/main/java/redis/clients/jedis/HostAndPort.java b/src/main/java/redis/clients/jedis/HostAndPort.java index 33d1467..4f756d6 100644 --- a/src/main/java/redis/clients/jedis/HostAndPort.java +++ b/src/main/java/redis/clients/jedis/HostAndPort.java @@ -1,50 +1,49 @@ package redis.clients.jedis; public class HostAndPort { - public static final String LOCALHOST_STR = "localhost"; - - private String host; - private int port; - - public HostAndPort(String host, int port) { - this.host = host; - this.port = port; + public static final String LOCALHOST_STR = "localhost"; + + private String host; + private int port; + + public HostAndPort(String host, int port) { + this.host = host; + this.port = port; + } + + public String getHost() { + return host; + } + + public int getPort() { + return port; + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof HostAndPort) { + HostAndPort hp = (HostAndPort) obj; + + String thisHost = convertHost(host); + String hpHost = convertHost(hp.host); + return port == hp.port && thisHost.equals(hpHost); + } - public String getHost() { - return host; - } + return false; + } - public int getPort() { - return port; - } + @Override + public String toString() { + return host + ":" + port; + } - @Override - public boolean equals(Object obj) { - if (obj instanceof HostAndPort) { - HostAndPort hp = (HostAndPort) obj; - - String thisHost = convertHost(host); - String hpHost = convertHost(hp.host); - return port == hp.port && - thisHost.equals(hpHost); - - } - - return false; - } - - @Override - public String toString() { - return host + ":" + port; - } - private String convertHost(String host) { - if (host.equals("127.0.0.1")) - return LOCALHOST_STR; - else if (host.equals("::1")) - return LOCALHOST_STR; + if (host.equals("127.0.0.1")) + return LOCALHOST_STR; + else if (host.equals("::1")) + return LOCALHOST_STR; - return host; + return host; } } diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index cdc3918..d465179 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -13,10 +13,10 @@ import java.util.Set; import redis.clients.jedis.BinaryClient.LIST_POSITION; import redis.clients.util.SafeEncoder; import redis.clients.util.Slowlog; -import java.net.URI; -import java.util.*; -public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommands, AdvancedJedisCommands, ScriptingCommands, BasicCommands, ClusterCommands { +public class Jedis extends BinaryJedis implements JedisCommands, + MultiKeyCommands, AdvancedJedisCommands, ScriptingCommands, + BasicCommands, ClusterCommands { public Jedis(final String host) { super(host); } @@ -56,24 +56,29 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand /** * Set the string value as value of the key. The string can't be longer than * 1073741824 bytes (1 GB). + * * @param key * @param value - * @param nxxx NX|XX, NX -- Only set the key if it does not already exist. - * XX -- Only set the key if it already exist. - * @param expx EX|PX, expire time units: EX = seconds; PX = milliseconds - * @param time expire time in the units of {@param #expx} + * @param nxxx + * NX|XX, NX -- Only set the key if it does not already exist. XX + * -- Only set the key if it already exist. + * @param expx + * EX|PX, expire time units: EX = seconds; PX = milliseconds + * @param time + * expire time in the units of {@param #expx} * @return Status code reply */ - public String set(final String key, final String value, final String nxxx, final String expx, final long time) { - checkIsInMulti(); - client.set(key, value, nxxx, expx, time); - return client.getStatusCodeReply(); + public String set(final String key, final String value, final String nxxx, + final String expx, final long time) { + checkIsInMulti(); + client.set(key, value, nxxx, expx, time); + return client.getStatusCodeReply(); } /** - * Get the value of the specified key. If the key does not exist null - * is returned. If the value stored at key is not a string an - * error is returned because GET can only handle string values. + * Get the value of the specified key. If the key does not exist null is + * returned. If the value stored at key is not a string an error is returned + * because GET can only handle string values. *

* Time complexity: O(1) * @@ -119,8 +124,8 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand } public Long del(String key) { - client.del(key); - return client.getIntegerReply(); + client.del(key); + return client.getIntegerReply(); } /** @@ -1381,7 +1386,7 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand client.srandmember(key); return client.getBulkReply(); } - + public List srandmember(final String key, final int count) { checkIsInMulti(); client.srandmember(key, count); @@ -1416,9 +1421,9 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand } public Long zadd(final String key, final Map scoreMembers) { - checkIsInMulti(); - client.zadd(key, scoreMembers); - return client.getIntegerReply(); + checkIsInMulti(); + client.zadd(key, scoreMembers); + return client.getIntegerReply(); } public Set zrange(final String key, final long start, final long end) { @@ -1789,39 +1794,39 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand } public List blpop(String... args) { - client.blpop(args); - client.setTimeoutInfinite(); - final List multiBulkReply = client.getMultiBulkReply(); - client.rollbackTimeout(); - return multiBulkReply; + client.blpop(args); + client.setTimeoutInfinite(); + final List multiBulkReply = client.getMultiBulkReply(); + client.rollbackTimeout(); + return multiBulkReply; } public List brpop(String... args) { - client.brpop(args); - client.setTimeoutInfinite(); - final List multiBulkReply = client.getMultiBulkReply(); - client.rollbackTimeout(); - return multiBulkReply; + client.brpop(args); + client.setTimeoutInfinite(); + final List multiBulkReply = client.getMultiBulkReply(); + client.rollbackTimeout(); + return multiBulkReply; } public List blpop(String arg) { - String[] args = new String[1]; - args[0] = arg; - client.blpop(args); - client.setTimeoutInfinite(); - final List multiBulkReply = client.getMultiBulkReply(); - client.rollbackTimeout(); - return multiBulkReply; + String[] args = new String[1]; + args[0] = arg; + client.blpop(args); + client.setTimeoutInfinite(); + final List multiBulkReply = client.getMultiBulkReply(); + client.rollbackTimeout(); + return multiBulkReply; } public List brpop(String arg) { - String[] args = new String[1]; - args[0] = arg; - client.brpop(args); - client.setTimeoutInfinite(); - final List multiBulkReply = client.getMultiBulkReply(); - client.rollbackTimeout(); - return multiBulkReply; + String[] args = new String[1]; + args[0] = arg; + client.brpop(args); + client.setTimeoutInfinite(); + final List multiBulkReply = client.getMultiBulkReply(); + client.rollbackTimeout(); + return multiBulkReply; } /** @@ -1954,8 +1959,6 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand return multiBulkReply; } - - public Long zcount(final String key, final double min, final double max) { checkIsInMulti(); client.zcount(key, min, max); @@ -2020,8 +2023,10 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand * @see #zcount(String, double, double) * * @param key - * @param min a double or Double.MIN_VALUE for "-inf" - * @param max a double or Double.MAX_VALUE for "+inf" + * @param min + * a double or Double.MIN_VALUE for "-inf" + * @param max + * a double or Double.MAX_VALUE for "+inf" * @return Multi bulk reply specifically a list of elements in the specified * score range. */ @@ -2628,8 +2633,8 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand } public Boolean setbit(String key, long offset, String value) { - client.setbit(key, offset, value); - return client.getIntegerReply() == 1; + client.setbit(key, offset, value); + return client.getIntegerReply() == 1; } /** @@ -2742,26 +2747,26 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand } public void subscribe(final JedisPubSub jedisPubSub, - final String... channels) { - client.setTimeoutInfinite(); - jedisPubSub.proceed(client, channels); - client.rollbackTimeout(); + final String... channels) { + client.setTimeoutInfinite(); + jedisPubSub.proceed(client, channels); + client.rollbackTimeout(); } public Long publish(final String channel, final String message) { - checkIsInMulti(); - connect(); - client.publish(channel, message); - return client.getIntegerReply(); + checkIsInMulti(); + connect(); + client.publish(channel, message); + return client.getIntegerReply(); } public void psubscribe(final JedisPubSub jedisPubSub, - final String... patterns) { - checkIsInMulti(); - connect(); - client.setTimeoutInfinite(); - jedisPubSub.proceedWithPatterns(client, patterns); - client.rollbackTimeout(); + final String... patterns) { + checkIsInMulti(); + connect(); + client.setTimeoutInfinite(); + jedisPubSub.proceedWithPatterns(client, patterns); + client.rollbackTimeout(); } protected static String[] getParams(List keys, List args) { @@ -2793,7 +2798,7 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand private Object getEvalResult() { Object result = client.getOne(); - + if (result instanceof byte[]) return SafeEncoder.encode((byte[]) result); @@ -2870,18 +2875,18 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand } public Long bitcount(final String key) { - client.bitcount(key); - return client.getIntegerReply(); + client.bitcount(key); + return client.getIntegerReply(); } public Long bitcount(final String key, long start, long end) { - client.bitcount(key, start, end); - return client.getIntegerReply(); + client.bitcount(key, start, end); + return client.getIntegerReply(); } public Long bitop(BitOP op, final String destKey, String... srcKeys) { - client.bitop(op, destKey, srcKeys); - return client.getIntegerReply(); + client.bitop(op, destKey, srcKeys); + return client.getIntegerReply(); } /** @@ -2917,7 +2922,7 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand * @return */ @SuppressWarnings("rawtypes") - public List> sentinelMasters() { + public List> sentinelMasters() { client.sentinel(Protocol.SENTINEL_MASTERS); final List reply = client.getObjectMultiBulkReply(); @@ -2995,7 +3000,7 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand * @return */ @SuppressWarnings("rawtypes") - public List> sentinelSlaves(String masterName) { + public List> sentinelSlaves(String masterName) { client.sentinel(Protocol.SENTINEL_SLAVES, masterName); final List reply = client.getObjectMultiBulkReply(); @@ -3007,211 +3012,224 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand } public byte[] dump(final String key) { - checkIsInMulti(); - client.dump(key); - return client.getBinaryBulkReply(); + checkIsInMulti(); + client.dump(key); + return client.getBinaryBulkReply(); } - - public String restore(final String key, final int ttl, final byte[] serializedValue) { - checkIsInMulti(); - client.restore(key, ttl, serializedValue); - return client.getStatusCodeReply(); + + public String restore(final String key, final int ttl, + final byte[] serializedValue) { + checkIsInMulti(); + client.restore(key, ttl, serializedValue); + return client.getStatusCodeReply(); } - + public Long pexpire(final String key, final int milliseconds) { - checkIsInMulti(); - client.pexpire(key, milliseconds); - return client.getIntegerReply(); + checkIsInMulti(); + client.pexpire(key, milliseconds); + return client.getIntegerReply(); } - + public Long pexpireAt(final String key, final long millisecondsTimestamp) { - checkIsInMulti(); - client.pexpireAt(key, millisecondsTimestamp); - return client.getIntegerReply(); + checkIsInMulti(); + client.pexpireAt(key, millisecondsTimestamp); + return client.getIntegerReply(); } - + public Long pttl(final String key) { - checkIsInMulti(); - client.pttl(key); - return client.getIntegerReply(); + checkIsInMulti(); + client.pttl(key); + return client.getIntegerReply(); } - + public Double incrByFloat(final String key, final double increment) { - checkIsInMulti(); - client.incrByFloat(key, increment); - String relpy = client.getBulkReply(); - return (relpy != null ? new Double(relpy) : null); + checkIsInMulti(); + client.incrByFloat(key, increment); + String relpy = client.getBulkReply(); + return (relpy != null ? new Double(relpy) : null); } - - public String psetex(final String key, final int milliseconds, final String value) { - checkIsInMulti(); - client.psetex(key, milliseconds, value); - return client.getStatusCodeReply(); + + public String psetex(final String key, final int milliseconds, + final String value) { + checkIsInMulti(); + client.psetex(key, milliseconds, value); + return client.getStatusCodeReply(); } - + public String set(final String key, final String value, final String nxxx) { - checkIsInMulti(); - client.set(key, value, nxxx); - return client.getStatusCodeReply(); + checkIsInMulti(); + client.set(key, value, nxxx); + return client.getStatusCodeReply(); } - - public String set(final String key, final String value, final String nxxx, final String expx, final int time) { - checkIsInMulti(); - client.set(key, value, nxxx, expx, time); - return client.getStatusCodeReply(); + + public String set(final String key, final String value, final String nxxx, + final String expx, final int time) { + checkIsInMulti(); + client.set(key, value, nxxx, expx, time); + return client.getStatusCodeReply(); } - + public String clientKill(final String client) { - checkIsInMulti(); - this.client.clientKill(client); - return this.client.getStatusCodeReply(); + checkIsInMulti(); + this.client.clientKill(client); + return this.client.getStatusCodeReply(); } - + public String clientSetname(final String name) { - checkIsInMulti(); - client.clientSetname(name); - return client.getStatusCodeReply(); + checkIsInMulti(); + client.clientSetname(name); + return client.getStatusCodeReply(); } - - public String migrate(final String host, final int port, final String key, final int destinationDb, final int timeout) { - checkIsInMulti(); - client.migrate(host, port, key, destinationDb, timeout); - return client.getStatusCodeReply(); + + public String migrate(final String host, final int port, final String key, + final int destinationDb, final int timeout) { + checkIsInMulti(); + client.migrate(host, port, key, destinationDb, timeout); + return client.getStatusCodeReply(); } - - public Double hincrByFloat(final String key, final String field, double increment) { - checkIsInMulti(); - client.hincrByFloat(key, field, increment); - String relpy = client.getBulkReply(); - return (relpy != null ? new Double(relpy) : null); + + public Double hincrByFloat(final String key, final String field, + double increment) { + checkIsInMulti(); + client.hincrByFloat(key, field, increment); + String relpy = client.getBulkReply(); + return (relpy != null ? new Double(relpy) : null); } public ScanResult scan(int cursor) { return scan(cursor, new ScanParams()); } - + public ScanResult scan(int cursor, final ScanParams params) { checkIsInMulti(); client.scan(cursor, params); List result = client.getObjectMultiBulkReply(); - int newcursor = Integer.parseInt(new String((byte[])result.get(0))); + int newcursor = Integer.parseInt(new String((byte[]) result.get(0))); List results = new ArrayList(); - List rawResults = (List)result.get(1); + List rawResults = (List) result.get(1); for (byte[] bs : rawResults) { results.add(SafeEncoder.encode(bs)); } return new ScanResult(newcursor, results); } - - public ScanResult> hscan(final String key, int cursor) { + + public ScanResult> hscan(final String key, + int cursor) { return hscan(key, cursor, new ScanParams()); } - - public ScanResult> hscan(final String key, int cursor, final ScanParams params) { + + public ScanResult> hscan(final String key, + int cursor, final ScanParams params) { checkIsInMulti(); client.hscan(key, cursor, params); List result = client.getObjectMultiBulkReply(); - int newcursor = Integer.parseInt(new String((byte[])result.get(0))); + int newcursor = Integer.parseInt(new String((byte[]) result.get(0))); List> results = new ArrayList>(); - List rawResults = (List)result.get(1); + List rawResults = (List) result.get(1); Iterator iterator = rawResults.iterator(); - while(iterator.hasNext()) { - results.add(new AbstractMap.SimpleEntry(SafeEncoder.encode(iterator.next()), SafeEncoder.encode(iterator.next()))); + while (iterator.hasNext()) { + results.add(new AbstractMap.SimpleEntry(SafeEncoder + .encode(iterator.next()), SafeEncoder.encode(iterator + .next()))); } return new ScanResult>(newcursor, results); } - + public ScanResult sscan(final String key, int cursor) { return sscan(key, cursor, new ScanParams()); } - - public ScanResult sscan(final String key, int cursor, final ScanParams params) { + + public ScanResult sscan(final String key, int cursor, + final ScanParams params) { checkIsInMulti(); client.sscan(key, cursor, params); List result = client.getObjectMultiBulkReply(); - int newcursor = Integer.parseInt(new String((byte[])result.get(0))); + int newcursor = Integer.parseInt(new String((byte[]) result.get(0))); List results = new ArrayList(); - List rawResults = (List)result.get(1); + List rawResults = (List) result.get(1); for (byte[] bs : rawResults) { results.add(SafeEncoder.encode(bs)); } return new ScanResult(newcursor, results); } - + public ScanResult zscan(final String key, int cursor) { return zscan(key, cursor, new ScanParams()); } - - public ScanResult zscan(final String key, int cursor, final ScanParams params) { + + public ScanResult zscan(final String key, int cursor, + final ScanParams params) { checkIsInMulti(); client.zscan(key, cursor, params); List result = client.getObjectMultiBulkReply(); - int newcursor = Integer.parseInt(new String((byte[])result.get(0))); + int newcursor = Integer.parseInt(new String((byte[]) result.get(0))); List results = new ArrayList(); - List rawResults = (List)result.get(1); + List rawResults = (List) result.get(1); Iterator iterator = rawResults.iterator(); - while(iterator.hasNext()) { - results.add(new Tuple(SafeEncoder.encode(iterator.next()), Double.valueOf(SafeEncoder.encode(iterator.next())))); + while (iterator.hasNext()) { + results.add(new Tuple(SafeEncoder.encode(iterator.next()), Double + .valueOf(SafeEncoder.encode(iterator.next())))); } return new ScanResult(newcursor, results); } + public String clusterNodes() { - checkIsInMulti(); - client.clusterNodes(); - return client.getBulkReply(); - } - - public String clusterMeet(final String ip, final int port) { - checkIsInMulti(); - client.clusterMeet(ip, port); - return client.getStatusCodeReply(); - } - - public String clusterAddSlots(final int ...slots) { - checkIsInMulti(); - client.clusterAddSlots(slots); - return client.getStatusCodeReply(); - } - - public String clusterDelSlots(final int ...slots) { - checkIsInMulti(); - client.clusterDelSlots(slots); - return client.getStatusCodeReply(); - } - - public String clusterInfo() { - checkIsInMulti(); - client.clusterInfo(); - return client.getStatusCodeReply(); - } - - public List clusterGetKeysInSlot(final int slot, final int count) { - checkIsInMulti(); - client.clusterGetKeysInSlot(slot, count); - return client.getMultiBulkReply(); - } - - public String clusterSetSlotNode(final int slot, final String nodeId) { - checkIsInMulti(); - client.clusterSetSlotNode(slot, nodeId); - return client.getStatusCodeReply(); - } - - public String clusterSetSlotMigrating(final int slot, final String nodeId) { - checkIsInMulti(); - client.clusterSetSlotMigrating(slot, nodeId); - return client.getStatusCodeReply(); - } - - public String clusterSetSlotImporting(final int slot, final String nodeId) { - checkIsInMulti(); - client.clusterSetSlotImporting(slot, nodeId); - return client.getStatusCodeReply(); + checkIsInMulti(); + client.clusterNodes(); + return client.getBulkReply(); } - public String asking() { - checkIsInMulti(); - client.asking(); - return client.getStatusCodeReply(); - } + public String clusterMeet(final String ip, final int port) { + checkIsInMulti(); + client.clusterMeet(ip, port); + return client.getStatusCodeReply(); + } + + public String clusterAddSlots(final int... slots) { + checkIsInMulti(); + client.clusterAddSlots(slots); + return client.getStatusCodeReply(); + } + + public String clusterDelSlots(final int... slots) { + checkIsInMulti(); + client.clusterDelSlots(slots); + return client.getStatusCodeReply(); + } + + public String clusterInfo() { + checkIsInMulti(); + client.clusterInfo(); + return client.getStatusCodeReply(); + } + + public List clusterGetKeysInSlot(final int slot, final int count) { + checkIsInMulti(); + client.clusterGetKeysInSlot(slot, count); + return client.getMultiBulkReply(); + } + + public String clusterSetSlotNode(final int slot, final String nodeId) { + checkIsInMulti(); + client.clusterSetSlotNode(slot, nodeId); + return client.getStatusCodeReply(); + } + + public String clusterSetSlotMigrating(final int slot, final String nodeId) { + checkIsInMulti(); + client.clusterSetSlotMigrating(slot, nodeId); + return client.getStatusCodeReply(); + } + + public String clusterSetSlotImporting(final int slot, final String nodeId) { + checkIsInMulti(); + client.clusterSetSlotImporting(slot, nodeId); + return client.getStatusCodeReply(); + } + + public String asking() { + checkIsInMulti(); + client.asking(); + return client.getStatusCodeReply(); + } } diff --git a/src/main/java/redis/clients/jedis/JedisClusterCommand.java b/src/main/java/redis/clients/jedis/JedisClusterCommand.java index 8596971..41087a7 100644 --- a/src/main/java/redis/clients/jedis/JedisClusterCommand.java +++ b/src/main/java/redis/clients/jedis/JedisClusterCommand.java @@ -7,47 +7,54 @@ import redis.clients.jedis.exceptions.JedisRedirectionException; import redis.clients.util.JedisClusterCRC16; public abstract class JedisClusterCommand { - - private boolean asking = false; - - private JedisClusterConnectionHandler connectionHandler; - private int commandTimeout; - private int redirections; -// private boolean asking = false; - - public JedisClusterCommand(JedisClusterConnectionHandler connectionHandler, int timeout, int maxRedirections) { - this.connectionHandler = connectionHandler; - this.commandTimeout = timeout; - this.redirections = maxRedirections; - } - public abstract T execute(); - - public T run(String key) { - try { - - if (key == null) { - throw new JedisClusterException("No way to dispatch this command to Redis Cluster."); - } else if (redirections == 0) { - throw new JedisClusterMaxRedirectionsException("Too many Cluster redirections?"); - } - connectionHandler.getConnectionFromSlot(JedisClusterCRC16.getSlot(key)); - if (asking) { - //TODO: Pipeline asking with the original command to make it faster.... - connectionHandler.getConnection().asking(); - } - return execute(); - } catch (JedisRedirectionException jre) { - return handleRedirection(jre, key); - } - } + private boolean asking = false; - private T handleRedirection(JedisRedirectionException jre, String key) { - if (jre instanceof JedisAskDataException) { - asking = true; - } - redirections--; - this.connectionHandler.assignSlotToNode(jre.getSlot(), jre.getTargetNode()); - return run(key); + private JedisClusterConnectionHandler connectionHandler; + private int commandTimeout; + private int redirections; + + // private boolean asking = false; + + public JedisClusterCommand(JedisClusterConnectionHandler connectionHandler, + int timeout, int maxRedirections) { + this.connectionHandler = connectionHandler; + this.commandTimeout = timeout; + this.redirections = maxRedirections; + } + + public abstract T execute(); + + public T run(String key) { + try { + + if (key == null) { + throw new JedisClusterException( + "No way to dispatch this command to Redis Cluster."); + } else if (redirections == 0) { + throw new JedisClusterMaxRedirectionsException( + "Too many Cluster redirections?"); + } + connectionHandler.getConnectionFromSlot(JedisClusterCRC16 + .getSlot(key)); + if (asking) { + // TODO: Pipeline asking with the original command to make it + // faster.... + connectionHandler.getConnection().asking(); + } + return execute(); + } catch (JedisRedirectionException jre) { + return handleRedirection(jre, key); } + } + + private T handleRedirection(JedisRedirectionException jre, String key) { + if (jre instanceof JedisAskDataException) { + asking = true; + } + redirections--; + this.connectionHandler.assignSlotToNode(jre.getSlot(), + jre.getTargetNode()); + return run(key); + } } \ No newline at end of file diff --git a/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java index 765b9a2..045d365 100644 --- a/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java +++ b/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java @@ -5,78 +5,80 @@ import java.util.Map; import java.util.Random; import java.util.Set; - public abstract class JedisClusterConnectionHandler { - - protected Map nodes = new HashMap(); - protected Map slots = new HashMap(); - - abstract Jedis getConnection(); - abstract Jedis getConnectionFromSlot(int slot); - - public JedisClusterConnectionHandler(Set nodes) { - initializeSlotsCache(nodes); - } - - public Map getNodes() { - return nodes; - } - - private void initializeSlotsCache(Set nodes) { - for (HostAndPort hostAndPort : nodes) { - JedisPool jp = new JedisPool(hostAndPort.getHost(), hostAndPort.getPort()); - this.nodes.put(hostAndPort.getHost() + hostAndPort.getPort(), jp); - discoverClusterNodesAndSlots(jp); - } + protected Map nodes = new HashMap(); + protected Map slots = new HashMap(); + + abstract Jedis getConnection(); + + abstract Jedis getConnectionFromSlot(int slot); + + public JedisClusterConnectionHandler(Set nodes) { + initializeSlotsCache(nodes); + } + + public Map getNodes() { + return nodes; + } + + private void initializeSlotsCache(Set nodes) { + for (HostAndPort hostAndPort : nodes) { + JedisPool jp = new JedisPool(hostAndPort.getHost(), + hostAndPort.getPort()); + this.nodes.put(hostAndPort.getHost() + hostAndPort.getPort(), jp); + discoverClusterNodesAndSlots(jp); } - private void discoverClusterNodesAndSlots(JedisPool jp) { - String localNodes = jp.getResource().clusterNodes(); - for (String nodeInfo : localNodes.split("\n")) { - HostAndPort node = getHostAndPortFromNodeLine(nodeInfo); - JedisPool nodePool = new JedisPool(node.getHost(), node.getPort()); - this.nodes.put(node.getHost() + node.getPort(), nodePool); - populateNodeSlots(nodeInfo, nodePool); - } - } + } - private void populateNodeSlots(String nodeInfo, JedisPool nodePool) { - String[] nodeInfoArray = nodeInfo.split(" "); - if (nodeInfoArray.length > 7) { - for (int i = 8; i < nodeInfoArray.length; i++) { - processSlot(nodeInfoArray[i], nodePool); - } - } + private void discoverClusterNodesAndSlots(JedisPool jp) { + String localNodes = jp.getResource().clusterNodes(); + for (String nodeInfo : localNodes.split("\n")) { + HostAndPort node = getHostAndPortFromNodeLine(nodeInfo); + JedisPool nodePool = new JedisPool(node.getHost(), node.getPort()); + this.nodes.put(node.getHost() + node.getPort(), nodePool); + populateNodeSlots(nodeInfo, nodePool); } + } - private void processSlot(String slot, JedisPool nodePool) { - if (slot.contains("-")) { - String[] slotRange = slot.split("-"); - for (int i = Integer.valueOf(slotRange[0]); i <= Integer.valueOf(slotRange[1]); i++) { - slots.put(i, nodePool); - } - } else { - slots.put(Integer.valueOf(slot), nodePool); - } + private void populateNodeSlots(String nodeInfo, JedisPool nodePool) { + String[] nodeInfoArray = nodeInfo.split(" "); + if (nodeInfoArray.length > 7) { + for (int i = 8; i < nodeInfoArray.length; i++) { + processSlot(nodeInfoArray[i], nodePool); + } } + } - private HostAndPort getHostAndPortFromNodeLine(String nodeInfo) { - String stringHostAndPort = nodeInfo.split(" ",3)[1]; - String[] arrayHostAndPort = stringHostAndPort.split(":"); - return new HostAndPort(arrayHostAndPort[0], Integer.valueOf(arrayHostAndPort[1])); + private void processSlot(String slot, JedisPool nodePool) { + if (slot.contains("-")) { + String[] slotRange = slot.split("-"); + for (int i = Integer.valueOf(slotRange[0]); i <= Integer + .valueOf(slotRange[1]); i++) { + slots.put(i, nodePool); + } + } else { + slots.put(Integer.valueOf(slot), nodePool); } + } + + private HostAndPort getHostAndPortFromNodeLine(String nodeInfo) { + String stringHostAndPort = nodeInfo.split(" ", 3)[1]; + String[] arrayHostAndPort = stringHostAndPort.split(":"); + return new HostAndPort(arrayHostAndPort[0], + Integer.valueOf(arrayHostAndPort[1])); + } + + public void assignSlotToNode(int slot, HostAndPort targetNode) { + JedisPool targetPool = nodes.get(targetNode.getHost() + + targetNode.getPort()); + slots.put(slot, targetPool); + } + + protected JedisPool getRandomConnection() { + Object[] nodeArray = nodes.values().toArray(); + return (JedisPool) (nodeArray[new Random().nextInt(nodeArray.length)]); + } - public void assignSlotToNode(int slot, HostAndPort targetNode) { - JedisPool targetPool = nodes.get(targetNode.getHost() + targetNode.getPort()); - slots.put(slot, targetPool); - } - - - protected JedisPool getRandomConnection() { - Object[] nodeArray = nodes.values().toArray(); - return (JedisPool) (nodeArray[new Random().nextInt(nodeArray.length)]); - } - - } diff --git a/src/main/java/redis/clients/jedis/JedisCommands.java b/src/main/java/redis/clients/jedis/JedisCommands.java index 4f9af0d..3077e68 100644 --- a/src/main/java/redis/clients/jedis/JedisCommands.java +++ b/src/main/java/redis/clients/jedis/JedisCommands.java @@ -7,8 +7,7 @@ import java.util.Set; /** * Common interface for sharded and non-sharded Jedis */ -public interface - JedisCommands { +public interface JedisCommands { String set(String key, String value); String get(String key); @@ -114,8 +113,8 @@ public interface Long strlen(String key); Long zadd(String key, double score, String member); - - Long zadd(String key, Map scoreMembers); + + Long zadd(String key, Map scoreMembers); Set zrange(String key, long start, long end); @@ -152,50 +151,50 @@ public interface Set zrevrangeByScore(String key, double max, double min); Set zrangeByScore(String key, double min, double max, int offset, - int count); + int count); Set zrevrangeByScore(String key, String max, String min); Set zrangeByScore(String key, String min, String max, int offset, - int count); + int count); Set zrevrangeByScore(String key, double max, double min, - int offset, int count); + int offset, int count); Set zrangeByScoreWithScores(String key, double min, double max); Set zrevrangeByScoreWithScores(String key, double max, double min); Set zrangeByScoreWithScores(String key, double min, double max, - int offset, int count); - + int offset, int count); + Set zrevrangeByScore(String key, String max, String min, - int offset, int count); + int offset, int count); Set zrangeByScoreWithScores(String key, String min, String max); - + Set zrevrangeByScoreWithScores(String key, String max, String min); Set zrangeByScoreWithScores(String key, String min, String max, - int offset, int count); + int offset, int count); Set zrevrangeByScoreWithScores(String key, double max, double min, - int offset, int count); - + int offset, int count); + Set zrevrangeByScoreWithScores(String key, String max, String min, - int offset, int count); + int offset, int count); Long zremrangeByRank(String key, long start, long end); Long zremrangeByScore(String key, double start, double end); - + Long zremrangeByScore(String key, String start, String end); Long linsert(String key, Client.LIST_POSITION where, String pivot, - String value); - + String value); + Long lpushx(String key, String... string); - + Long rpushx(String key, String... string); List blpop(String arg); @@ -211,10 +210,10 @@ public interface Long bitcount(final String key); Long bitcount(final String key, long start, long end); - + ScanResult> hscan(final String key, int cursor); - + ScanResult sscan(final String key, int cursor); - + ScanResult zscan(final String key, int cursor); } diff --git a/src/main/java/redis/clients/jedis/JedisMonitor.java b/src/main/java/redis/clients/jedis/JedisMonitor.java index dff2672..cd8e802 100644 --- a/src/main/java/redis/clients/jedis/JedisMonitor.java +++ b/src/main/java/redis/clients/jedis/JedisMonitor.java @@ -4,12 +4,12 @@ public abstract class JedisMonitor { protected Client client; public void proceed(Client client) { - this.client = client; - this.client.setTimeoutInfinite(); - do { - String command = client.getBulkReply(); - onCommand(command); - } while (client.isConnected()); + this.client = client; + this.client.setTimeoutInfinite(); + do { + String command = client.getBulkReply(); + onCommand(command); + } while (client.isConnected()); } public abstract void onCommand(String command); diff --git a/src/main/java/redis/clients/jedis/JedisPool.java b/src/main/java/redis/clients/jedis/JedisPool.java index 241dfe8..6b2c80c 100644 --- a/src/main/java/redis/clients/jedis/JedisPool.java +++ b/src/main/java/redis/clients/jedis/JedisPool.java @@ -18,7 +18,7 @@ public class JedisPool extends Pool { this(new GenericObjectPoolConfig(), host, port, Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE, null); } - + public JedisPool(final String host) { URI uri = URI.create(host); if (uri.getScheme() != null && uri.getScheme().equals("redis")) { @@ -84,7 +84,7 @@ public class JedisPool extends Pool { } public void returnResource(final Jedis resource) { - resource.resetState(); + resource.resetState(); returnResourceObject(resource); } } diff --git a/src/main/java/redis/clients/jedis/JedisPoolConfig.java b/src/main/java/redis/clients/jedis/JedisPoolConfig.java index fff38d4..5efdde8 100644 --- a/src/main/java/redis/clients/jedis/JedisPoolConfig.java +++ b/src/main/java/redis/clients/jedis/JedisPoolConfig.java @@ -4,10 +4,10 @@ import org.apache.commons.pool2.impl.GenericObjectPoolConfig; public class JedisPoolConfig extends GenericObjectPoolConfig { public JedisPoolConfig() { - // defaults to make your life with connection pool easier :) - setTestWhileIdle(true); - setMinEvictableIdleTimeMillis(60000); - setTimeBetweenEvictionRunsMillis(30000); - setNumTestsPerEvictionRun(-1); + // defaults to make your life with connection pool easier :) + setTestWhileIdle(true); + setMinEvictableIdleTimeMillis(60000); + setTimeBetweenEvictionRunsMillis(30000); + setNumTestsPerEvictionRun(-1); } } diff --git a/src/main/java/redis/clients/jedis/JedisPubSub.java b/src/main/java/redis/clients/jedis/JedisPubSub.java index d07a409..1f3ac5f 100644 --- a/src/main/java/redis/clients/jedis/JedisPubSub.java +++ b/src/main/java/redis/clients/jedis/JedisPubSub.java @@ -21,7 +21,7 @@ public abstract class JedisPubSub { public abstract void onMessage(String channel, String message); public abstract void onPMessage(String pattern, String channel, - String message); + String message); public abstract void onSubscribe(String channel, int subscribedChannels); @@ -32,115 +32,115 @@ public abstract class JedisPubSub { public abstract void onPSubscribe(String pattern, int subscribedChannels); public void unsubscribe() { - if (client == null) { - throw new JedisConnectionException( - "JedisPubSub was not subscribed to a Jedis instance."); - } - client.unsubscribe(); - client.flush(); + if (client == null) { + throw new JedisConnectionException( + "JedisPubSub was not subscribed to a Jedis instance."); + } + client.unsubscribe(); + client.flush(); } public void unsubscribe(String... channels) { - client.unsubscribe(channels); - client.flush(); + client.unsubscribe(channels); + client.flush(); } public void subscribe(String... channels) { - client.subscribe(channels); - client.flush(); + client.subscribe(channels); + client.flush(); } public void psubscribe(String... patterns) { - client.psubscribe(patterns); - client.flush(); + client.psubscribe(patterns); + client.flush(); } public void punsubscribe() { - client.punsubscribe(); - client.flush(); + client.punsubscribe(); + client.flush(); } public void punsubscribe(String... patterns) { - client.punsubscribe(patterns); - client.flush(); + client.punsubscribe(patterns); + client.flush(); } public boolean isSubscribed() { - return subscribedChannels > 0; + return subscribedChannels > 0; } public void proceedWithPatterns(Client client, String... patterns) { - this.client = client; - client.psubscribe(patterns); - client.flush(); - process(client); + this.client = client; + client.psubscribe(patterns); + client.flush(); + process(client); } public void proceed(Client client, String... channels) { - this.client = client; - client.subscribe(channels); - client.flush(); - process(client); + this.client = client; + client.subscribe(channels); + client.flush(); + process(client); } private void process(Client client) { - do { - List reply = client.getObjectMultiBulkReply(); - final Object firstObj = reply.get(0); - if (!(firstObj instanceof byte[])) { - throw new JedisException("Unknown message type: " + firstObj); - } - final byte[] resp = (byte[]) firstObj; - if (Arrays.equals(SUBSCRIBE.raw, resp)) { - subscribedChannels = ((Long) reply.get(2)).intValue(); - final byte[] bchannel = (byte[]) reply.get(1); - final String strchannel = (bchannel == null) ? null - : SafeEncoder.encode(bchannel); - onSubscribe(strchannel, subscribedChannels); - } else if (Arrays.equals(UNSUBSCRIBE.raw, resp)) { - subscribedChannels = ((Long) reply.get(2)).intValue(); - final byte[] bchannel = (byte[]) reply.get(1); - final String strchannel = (bchannel == null) ? null - : SafeEncoder.encode(bchannel); - onUnsubscribe(strchannel, subscribedChannels); - } else if (Arrays.equals(MESSAGE.raw, resp)) { - final byte[] bchannel = (byte[]) reply.get(1); - final byte[] bmesg = (byte[]) reply.get(2); - final String strchannel = (bchannel == null) ? null - : SafeEncoder.encode(bchannel); - final String strmesg = (bmesg == null) ? null : SafeEncoder - .encode(bmesg); - onMessage(strchannel, strmesg); - } else if (Arrays.equals(PMESSAGE.raw, resp)) { - final byte[] bpattern = (byte[]) reply.get(1); - final byte[] bchannel = (byte[]) reply.get(2); - final byte[] bmesg = (byte[]) reply.get(3); - final String strpattern = (bpattern == null) ? null - : SafeEncoder.encode(bpattern); - final String strchannel = (bchannel == null) ? null - : SafeEncoder.encode(bchannel); - final String strmesg = (bmesg == null) ? null : SafeEncoder - .encode(bmesg); - onPMessage(strpattern, strchannel, strmesg); - } else if (Arrays.equals(PSUBSCRIBE.raw, resp)) { - subscribedChannels = ((Long) reply.get(2)).intValue(); - final byte[] bpattern = (byte[]) reply.get(1); - final String strpattern = (bpattern == null) ? null - : SafeEncoder.encode(bpattern); - onPSubscribe(strpattern, subscribedChannels); - } else if (Arrays.equals(PUNSUBSCRIBE.raw, resp)) { - subscribedChannels = ((Long) reply.get(2)).intValue(); - final byte[] bpattern = (byte[]) reply.get(1); - final String strpattern = (bpattern == null) ? null - : SafeEncoder.encode(bpattern); - onPUnsubscribe(strpattern, subscribedChannels); - } else { - throw new JedisException("Unknown message type: " + firstObj); - } - } while (isSubscribed()); + do { + List reply = client.getObjectMultiBulkReply(); + final Object firstObj = reply.get(0); + if (!(firstObj instanceof byte[])) { + throw new JedisException("Unknown message type: " + firstObj); + } + final byte[] resp = (byte[]) firstObj; + if (Arrays.equals(SUBSCRIBE.raw, resp)) { + subscribedChannels = ((Long) reply.get(2)).intValue(); + final byte[] bchannel = (byte[]) reply.get(1); + final String strchannel = (bchannel == null) ? null + : SafeEncoder.encode(bchannel); + onSubscribe(strchannel, subscribedChannels); + } else if (Arrays.equals(UNSUBSCRIBE.raw, resp)) { + subscribedChannels = ((Long) reply.get(2)).intValue(); + final byte[] bchannel = (byte[]) reply.get(1); + final String strchannel = (bchannel == null) ? null + : SafeEncoder.encode(bchannel); + onUnsubscribe(strchannel, subscribedChannels); + } else if (Arrays.equals(MESSAGE.raw, resp)) { + final byte[] bchannel = (byte[]) reply.get(1); + final byte[] bmesg = (byte[]) reply.get(2); + final String strchannel = (bchannel == null) ? null + : SafeEncoder.encode(bchannel); + final String strmesg = (bmesg == null) ? null : SafeEncoder + .encode(bmesg); + onMessage(strchannel, strmesg); + } else if (Arrays.equals(PMESSAGE.raw, resp)) { + final byte[] bpattern = (byte[]) reply.get(1); + final byte[] bchannel = (byte[]) reply.get(2); + final byte[] bmesg = (byte[]) reply.get(3); + final String strpattern = (bpattern == null) ? null + : SafeEncoder.encode(bpattern); + final String strchannel = (bchannel == null) ? null + : SafeEncoder.encode(bchannel); + final String strmesg = (bmesg == null) ? null : SafeEncoder + .encode(bmesg); + onPMessage(strpattern, strchannel, strmesg); + } else if (Arrays.equals(PSUBSCRIBE.raw, resp)) { + subscribedChannels = ((Long) reply.get(2)).intValue(); + final byte[] bpattern = (byte[]) reply.get(1); + final String strpattern = (bpattern == null) ? null + : SafeEncoder.encode(bpattern); + onPSubscribe(strpattern, subscribedChannels); + } else if (Arrays.equals(PUNSUBSCRIBE.raw, resp)) { + subscribedChannels = ((Long) reply.get(2)).intValue(); + final byte[] bpattern = (byte[]) reply.get(1); + final String strpattern = (bpattern == null) ? null + : SafeEncoder.encode(bpattern); + onPUnsubscribe(strpattern, subscribedChannels); + } else { + throw new JedisException("Unknown message type: " + firstObj); + } + } while (isSubscribed()); } public int getSubscribedChannels() { - return subscribedChannels; + return subscribedChannels; } } \ No newline at end of file diff --git a/src/main/java/redis/clients/jedis/JedisRandomConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisRandomConnectionHandler.java index 40d3f04..d4e558e 100644 --- a/src/main/java/redis/clients/jedis/JedisRandomConnectionHandler.java +++ b/src/main/java/redis/clients/jedis/JedisRandomConnectionHandler.java @@ -4,17 +4,16 @@ import java.util.Set; public class JedisRandomConnectionHandler extends JedisClusterConnectionHandler { - - public JedisRandomConnectionHandler(Set nodes) { - super(nodes); - } + public JedisRandomConnectionHandler(Set nodes) { + super(nodes); + } - public Jedis getConnection() { - return getRandomConnection().getResource(); - } + public Jedis getConnection() { + return getRandomConnection().getResource(); + } - @Override - Jedis getConnectionFromSlot(int slot) { - return getRandomConnection().getResource(); - } + @Override + Jedis getConnectionFromSlot(int slot) { + return getRandomConnection().getResource(); + } } diff --git a/src/main/java/redis/clients/jedis/JedisSentinelPool.java b/src/main/java/redis/clients/jedis/JedisSentinelPool.java index 9190225..4fe5433 100644 --- a/src/main/java/redis/clients/jedis/JedisSentinelPool.java +++ b/src/main/java/redis/clients/jedis/JedisSentinelPool.java @@ -79,7 +79,7 @@ public class JedisSentinelPool extends Pool { } public void returnResource(final Jedis resource) { - resource.resetState(); + resource.resetState(); returnResourceObject(resource); } @@ -101,8 +101,9 @@ public class JedisSentinelPool extends Pool { if (!master.equals(currentHostMaster)) { currentHostMaster = master; log.info("Created JedisPool to master at " + master); - initPool(poolConfig, new JedisFactory(master.getHost(), master.getPort(), - timeout, password, database)); + initPool(poolConfig, + new JedisFactory(master.getHost(), master.getPort(), + timeout, password, database)); } } @@ -164,10 +165,10 @@ public class JedisSentinelPool extends Pool { } private HostAndPort toHostAndPort(List getMasterAddrByNameResult) { - String host = getMasterAddrByNameResult.get(0); - int port = Integer.parseInt(getMasterAddrByNameResult.get(1)); - - return new HostAndPort(host, port); + String host = getMasterAddrByNameResult.get(0); + int port = Integer.parseInt(getMasterAddrByNameResult.get(1)); + + return new HostAndPort(host, port); } protected class JedisPubSubAdapter extends JedisPubSub { diff --git a/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java index 4f3ea5d..4aba893 100644 --- a/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java +++ b/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java @@ -2,47 +2,45 @@ package redis.clients.jedis; import java.util.Set; -public class JedisSlotBasedConnectionHandler extends JedisClusterConnectionHandler { +public class JedisSlotBasedConnectionHandler extends + JedisClusterConnectionHandler { - private Jedis currentConnection; - - public JedisSlotBasedConnectionHandler(Set nodes) { - super(nodes); + private Jedis currentConnection; + + public JedisSlotBasedConnectionHandler(Set nodes) { + super(nodes); + } + + public Jedis getConnection() { + return currentConnection != null ? currentConnection + : getRandomConnection().getResource(); + } + + private void returnCurrentConnection() { + if (currentConnection != null) { + nodes.get( + currentConnection.getClient().getHost() + + currentConnection.getClient().getPort()) + .returnResource(currentConnection); } - - public Jedis getConnection() { - return currentConnection != null ? currentConnection : getRandomConnection().getResource(); + } + + @Override + public void assignSlotToNode(int slot, HostAndPort targetNode) { + super.assignSlotToNode(slot, targetNode); + getConnectionFromSlot(slot); + } + + @Override + public Jedis getConnectionFromSlot(int slot) { + returnCurrentConnection(); + JedisPool connectionPool = slots.get(slot); + if (connectionPool == null) { + connectionPool = getRandomConnection(); } - - - - - private void returnCurrentConnection() { - if (currentConnection != null) { - nodes.get(currentConnection.getClient().getHost()+currentConnection.getClient().getPort()).returnResource(currentConnection); - } - - } - - - @Override - public void assignSlotToNode(int slot, HostAndPort targetNode) { - super.assignSlotToNode(slot, targetNode); - getConnectionFromSlot(slot); - } - - @Override - public Jedis getConnectionFromSlot(int slot) { - returnCurrentConnection(); - JedisPool connectionPool = slots.get(slot); - if (connectionPool == null) { - connectionPool = getRandomConnection(); - } - currentConnection = connectionPool.getResource(); - return connectionPool.getResource(); - } - - + currentConnection = connectionPool.getResource(); + return connectionPool.getResource(); + } } diff --git a/src/main/java/redis/clients/jedis/MultiKeyBinaryCommands.java b/src/main/java/redis/clients/jedis/MultiKeyBinaryCommands.java index 1b3c158..e6ea8fd 100644 --- a/src/main/java/redis/clients/jedis/MultiKeyBinaryCommands.java +++ b/src/main/java/redis/clients/jedis/MultiKeyBinaryCommands.java @@ -1,6 +1,5 @@ package redis.clients.jedis; - import java.util.List; import java.util.Set; diff --git a/src/main/java/redis/clients/jedis/MultiKeyBinaryRedisPipeline.java b/src/main/java/redis/clients/jedis/MultiKeyBinaryRedisPipeline.java index d77ddd9..fd71016 100644 --- a/src/main/java/redis/clients/jedis/MultiKeyBinaryRedisPipeline.java +++ b/src/main/java/redis/clients/jedis/MultiKeyBinaryRedisPipeline.java @@ -1,16 +1,16 @@ package redis.clients.jedis; - import java.util.List; import java.util.Set; /** - * Multikey related commands (these are split out because they are non-shardable) + * Multikey related commands (these are split out because they are + * non-shardable) */ public interface MultiKeyBinaryRedisPipeline { Response del(byte[]... keys); - + Response> blpop(byte[]... args); Response> brpop(byte[]... args); @@ -39,7 +39,8 @@ public interface MultiKeyBinaryRedisPipeline { Response smove(byte[] srckey, byte[] dstkey, byte[] member); - Response sort(byte[] key, SortingParams sortingParameters, byte[] dstkey); + Response sort(byte[] key, SortingParams sortingParameters, + byte[] dstkey); Response sort(byte[] key, byte[] dstkey); diff --git a/src/main/java/redis/clients/jedis/MultiKeyCommands.java b/src/main/java/redis/clients/jedis/MultiKeyCommands.java index 64285de..3565c6d 100644 --- a/src/main/java/redis/clients/jedis/MultiKeyCommands.java +++ b/src/main/java/redis/clients/jedis/MultiKeyCommands.java @@ -1,8 +1,6 @@ package redis.clients.jedis; - import java.util.List; -import java.util.Map; import java.util.Set; public interface MultiKeyCommands { @@ -71,6 +69,6 @@ public interface MultiKeyCommands { String randomKey(); Long bitop(BitOP op, final String destKey, String... srcKeys); - + ScanResult scan(int cursor); } diff --git a/src/main/java/redis/clients/jedis/MultiKeyCommandsPipeline.java b/src/main/java/redis/clients/jedis/MultiKeyCommandsPipeline.java index ee9af65..92c8d5a 100644 --- a/src/main/java/redis/clients/jedis/MultiKeyCommandsPipeline.java +++ b/src/main/java/redis/clients/jedis/MultiKeyCommandsPipeline.java @@ -1,12 +1,11 @@ package redis.clients.jedis; - import java.util.List; import java.util.Set; - /** - * Multikey related commands (these are split out because they are non-shardable) + * Multikey related commands (these are split out because they are + * non-shardable) */ public interface MultiKeyCommandsPipeline { Response del(String... keys); @@ -39,7 +38,8 @@ public interface MultiKeyCommandsPipeline { Response smove(String srckey, String dstkey, String member); - Response sort(String key, SortingParams sortingParameters, String dstkey); + Response sort(String key, SortingParams sortingParameters, + String dstkey); Response sort(String key, String dstkey); diff --git a/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java b/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java index 04bdc80..fa7ae6e 100644 --- a/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java +++ b/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java @@ -5,401 +5,399 @@ import java.util.Map; import java.util.Set; abstract class MultiKeyPipelineBase extends PipelineBase implements - BasicRedisPipeline, - MultiKeyBinaryRedisPipeline, - MultiKeyCommandsPipeline, - ClusterPipeline { + BasicRedisPipeline, MultiKeyBinaryRedisPipeline, + MultiKeyCommandsPipeline, ClusterPipeline { protected Client client = null; public Response> brpop(String... args) { - client.brpop(args); - return getResponse(BuilderFactory.STRING_LIST); + client.brpop(args); + return getResponse(BuilderFactory.STRING_LIST); } - + public Response> brpop(int timeout, String... keys) { - client.brpop(timeout, keys); - return getResponse(BuilderFactory.STRING_LIST); + client.brpop(timeout, keys); + return getResponse(BuilderFactory.STRING_LIST); } public Response> blpop(String... args) { - client.blpop(args); - return getResponse(BuilderFactory.STRING_LIST); + client.blpop(args); + return getResponse(BuilderFactory.STRING_LIST); } - + public Response> blpop(int timeout, String... keys) { - client.blpop(timeout, keys); - return getResponse(BuilderFactory.STRING_LIST); + client.blpop(timeout, keys); + return getResponse(BuilderFactory.STRING_LIST); } - + public Response> blpopMap(int timeout, String... keys) { - client.blpop(timeout, keys); - return getResponse(BuilderFactory.STRING_MAP); + client.blpop(timeout, keys); + return getResponse(BuilderFactory.STRING_MAP); } public Response> brpop(byte[]... args) { - client.brpop(args); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); + client.brpop(args); + return getResponse(BuilderFactory.BYTE_ARRAY_LIST); } - + public Response> brpop(int timeout, byte[]... keys) { - client.brpop(timeout, keys); - return getResponse(BuilderFactory.STRING_LIST); + client.brpop(timeout, keys); + return getResponse(BuilderFactory.STRING_LIST); } - + public Response> brpopMap(int timeout, String... keys) { - client.blpop(timeout, keys); - return getResponse(BuilderFactory.STRING_MAP); + client.blpop(timeout, keys); + return getResponse(BuilderFactory.STRING_MAP); } public Response> blpop(byte[]... args) { - client.blpop(args); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); + client.blpop(args); + return getResponse(BuilderFactory.BYTE_ARRAY_LIST); } - + public Response> blpop(int timeout, byte[]... keys) { - client.blpop(timeout, keys); - return getResponse(BuilderFactory.STRING_LIST); + client.blpop(timeout, keys); + return getResponse(BuilderFactory.STRING_LIST); } public Response del(String... keys) { - client.del(keys); - return getResponse(BuilderFactory.LONG); + client.del(keys); + return getResponse(BuilderFactory.LONG); } public Response del(byte[]... keys) { - client.del(keys); - return getResponse(BuilderFactory.LONG); + client.del(keys); + return getResponse(BuilderFactory.LONG); } public Response> keys(String pattern) { - getClient(pattern).keys(pattern); - return getResponse(BuilderFactory.STRING_SET); + getClient(pattern).keys(pattern); + return getResponse(BuilderFactory.STRING_SET); } public Response> keys(byte[] pattern) { - getClient(pattern).keys(pattern); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); + getClient(pattern).keys(pattern); + return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); } public Response> mget(String... keys) { - client.mget(keys); - return getResponse(BuilderFactory.STRING_LIST); + client.mget(keys); + return getResponse(BuilderFactory.STRING_LIST); } public Response> mget(byte[]... keys) { - client.mget(keys); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); + client.mget(keys); + return getResponse(BuilderFactory.BYTE_ARRAY_LIST); } public Response mset(String... keysvalues) { - client.mset(keysvalues); - return getResponse(BuilderFactory.STRING); + client.mset(keysvalues); + return getResponse(BuilderFactory.STRING); } public Response mset(byte[]... keysvalues) { - client.mset(keysvalues); - return getResponse(BuilderFactory.STRING); + client.mset(keysvalues); + return getResponse(BuilderFactory.STRING); } public Response msetnx(String... keysvalues) { - client.msetnx(keysvalues); - return getResponse(BuilderFactory.LONG); + client.msetnx(keysvalues); + return getResponse(BuilderFactory.LONG); } public Response msetnx(byte[]... keysvalues) { - client.msetnx(keysvalues); - return getResponse(BuilderFactory.LONG); + client.msetnx(keysvalues); + return getResponse(BuilderFactory.LONG); } public Response rename(String oldkey, String newkey) { - client.rename(oldkey, newkey); - return getResponse(BuilderFactory.STRING); + client.rename(oldkey, newkey); + return getResponse(BuilderFactory.STRING); } public Response rename(byte[] oldkey, byte[] newkey) { - client.rename(oldkey, newkey); - return getResponse(BuilderFactory.STRING); + client.rename(oldkey, newkey); + return getResponse(BuilderFactory.STRING); } public Response renamenx(String oldkey, String newkey) { - client.renamenx(oldkey, newkey); - return getResponse(BuilderFactory.LONG); + client.renamenx(oldkey, newkey); + return getResponse(BuilderFactory.LONG); } public Response renamenx(byte[] oldkey, byte[] newkey) { - client.renamenx(oldkey, newkey); - return getResponse(BuilderFactory.LONG); + client.renamenx(oldkey, newkey); + return getResponse(BuilderFactory.LONG); } public Response rpoplpush(String srckey, String dstkey) { - client.rpoplpush(srckey, dstkey); - return getResponse(BuilderFactory.STRING); + client.rpoplpush(srckey, dstkey); + return getResponse(BuilderFactory.STRING); } public Response rpoplpush(byte[] srckey, byte[] dstkey) { - client.rpoplpush(srckey, dstkey); - return getResponse(BuilderFactory.BYTE_ARRAY); + client.rpoplpush(srckey, dstkey); + return getResponse(BuilderFactory.BYTE_ARRAY); } public Response> sdiff(String... keys) { - client.sdiff(keys); - return getResponse(BuilderFactory.STRING_SET); + client.sdiff(keys); + return getResponse(BuilderFactory.STRING_SET); } public Response> sdiff(byte[]... keys) { - client.sdiff(keys); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); + client.sdiff(keys); + return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); } public Response sdiffstore(String dstkey, String... keys) { - client.sdiffstore(dstkey, keys); - return getResponse(BuilderFactory.LONG); + client.sdiffstore(dstkey, keys); + return getResponse(BuilderFactory.LONG); } public Response sdiffstore(byte[] dstkey, byte[]... keys) { - client.sdiffstore(dstkey, keys); - return getResponse(BuilderFactory.LONG); + client.sdiffstore(dstkey, keys); + return getResponse(BuilderFactory.LONG); } public Response> sinter(String... keys) { - client.sinter(keys); - return getResponse(BuilderFactory.STRING_SET); + client.sinter(keys); + return getResponse(BuilderFactory.STRING_SET); } public Response> sinter(byte[]... keys) { - client.sinter(keys); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); + client.sinter(keys); + return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); } public Response sinterstore(String dstkey, String... keys) { - client.sinterstore(dstkey, keys); - return getResponse(BuilderFactory.LONG); + client.sinterstore(dstkey, keys); + return getResponse(BuilderFactory.LONG); } public Response sinterstore(byte[] dstkey, byte[]... keys) { - client.sinterstore(dstkey, keys); - return getResponse(BuilderFactory.LONG); + client.sinterstore(dstkey, keys); + return getResponse(BuilderFactory.LONG); } public Response smove(String srckey, String dstkey, String member) { - client.smove(srckey, dstkey, member); - return getResponse(BuilderFactory.LONG); + client.smove(srckey, dstkey, member); + return getResponse(BuilderFactory.LONG); } public Response smove(byte[] srckey, byte[] dstkey, byte[] member) { - client.smove(srckey, dstkey, member); - return getResponse(BuilderFactory.LONG); + client.smove(srckey, dstkey, member); + return getResponse(BuilderFactory.LONG); } - public Response sort(String key, - SortingParams sortingParameters, String dstkey) { - client.sort(key, sortingParameters, dstkey); - return getResponse(BuilderFactory.LONG); + public Response sort(String key, SortingParams sortingParameters, + String dstkey) { + client.sort(key, sortingParameters, dstkey); + return getResponse(BuilderFactory.LONG); } - public Response sort(byte[] key, - SortingParams sortingParameters, byte[] dstkey) { - client.sort(key, sortingParameters, dstkey); - return getResponse(BuilderFactory.LONG); + public Response sort(byte[] key, SortingParams sortingParameters, + byte[] dstkey) { + client.sort(key, sortingParameters, dstkey); + return getResponse(BuilderFactory.LONG); } public Response sort(String key, String dstkey) { - client.sort(key, dstkey); - return getResponse(BuilderFactory.LONG); + client.sort(key, dstkey); + return getResponse(BuilderFactory.LONG); } public Response sort(byte[] key, byte[] dstkey) { - client.sort(key, dstkey); - return getResponse(BuilderFactory.LONG); + client.sort(key, dstkey); + return getResponse(BuilderFactory.LONG); } public Response> sunion(String... keys) { - client.sunion(keys); - return getResponse(BuilderFactory.STRING_SET); + client.sunion(keys); + return getResponse(BuilderFactory.STRING_SET); } public Response> sunion(byte[]... keys) { - client.sunion(keys); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); + client.sunion(keys); + return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); } public Response sunionstore(String dstkey, String... keys) { - client.sunionstore(dstkey, keys); - return getResponse(BuilderFactory.LONG); + client.sunionstore(dstkey, keys); + return getResponse(BuilderFactory.LONG); } public Response sunionstore(byte[] dstkey, byte[]... keys) { - client.sunionstore(dstkey, keys); - return getResponse(BuilderFactory.LONG); + client.sunionstore(dstkey, keys); + return getResponse(BuilderFactory.LONG); } public Response watch(String... keys) { - client.watch(keys); - return getResponse(BuilderFactory.STRING); + client.watch(keys); + return getResponse(BuilderFactory.STRING); } public Response watch(byte[]... keys) { - client.watch(keys); - return getResponse(BuilderFactory.STRING); + client.watch(keys); + return getResponse(BuilderFactory.STRING); } public Response zinterstore(String dstkey, String... sets) { - client.zinterstore(dstkey, sets); - return getResponse(BuilderFactory.LONG); + client.zinterstore(dstkey, sets); + return getResponse(BuilderFactory.LONG); } public Response zinterstore(byte[] dstkey, byte[]... sets) { - client.zinterstore(dstkey, sets); - return getResponse(BuilderFactory.LONG); + client.zinterstore(dstkey, sets); + return getResponse(BuilderFactory.LONG); } public Response zinterstore(String dstkey, ZParams params, - String... sets) { - client.zinterstore(dstkey, params, sets); - return getResponse(BuilderFactory.LONG); + String... sets) { + client.zinterstore(dstkey, params, sets); + return getResponse(BuilderFactory.LONG); } public Response zinterstore(byte[] dstkey, ZParams params, - byte[]... sets) { - client.zinterstore(dstkey, params, sets); - return getResponse(BuilderFactory.LONG); + byte[]... sets) { + client.zinterstore(dstkey, params, sets); + return getResponse(BuilderFactory.LONG); } public Response zunionstore(String dstkey, String... sets) { - client.zunionstore(dstkey, sets); - return getResponse(BuilderFactory.LONG); + client.zunionstore(dstkey, sets); + return getResponse(BuilderFactory.LONG); } public Response zunionstore(byte[] dstkey, byte[]... sets) { - client.zunionstore(dstkey, sets); - return getResponse(BuilderFactory.LONG); + client.zunionstore(dstkey, sets); + return getResponse(BuilderFactory.LONG); } public Response zunionstore(String dstkey, ZParams params, - String... sets) { - client.zunionstore(dstkey, params, sets); - return getResponse(BuilderFactory.LONG); + String... sets) { + client.zunionstore(dstkey, params, sets); + return getResponse(BuilderFactory.LONG); } public Response zunionstore(byte[] dstkey, ZParams params, - byte[]... sets) { - client.zunionstore(dstkey, params, sets); - return getResponse(BuilderFactory.LONG); + byte[]... sets) { + client.zunionstore(dstkey, params, sets); + return getResponse(BuilderFactory.LONG); } public Response bgrewriteaof() { - client.bgrewriteaof(); - return getResponse(BuilderFactory.STRING); + client.bgrewriteaof(); + return getResponse(BuilderFactory.STRING); } public Response bgsave() { - client.bgsave(); - return getResponse(BuilderFactory.STRING); + client.bgsave(); + return getResponse(BuilderFactory.STRING); } public Response configGet(String pattern) { - client.configGet(pattern); - return getResponse(BuilderFactory.STRING); + client.configGet(pattern); + return getResponse(BuilderFactory.STRING); } public Response configSet(String parameter, String value) { - client.configSet(parameter, value); - return getResponse(BuilderFactory.STRING); + client.configSet(parameter, value); + return getResponse(BuilderFactory.STRING); } public Response brpoplpush(String source, String destination, - int timeout) { - client.brpoplpush(source, destination, timeout); - return getResponse(BuilderFactory.STRING); + int timeout) { + client.brpoplpush(source, destination, timeout); + return getResponse(BuilderFactory.STRING); } public Response brpoplpush(byte[] source, byte[] destination, - int timeout) { - client.brpoplpush(source, destination, timeout); - return getResponse(BuilderFactory.BYTE_ARRAY); + int timeout) { + client.brpoplpush(source, destination, timeout); + return getResponse(BuilderFactory.BYTE_ARRAY); } public Response configResetStat() { - client.configResetStat(); - return getResponse(BuilderFactory.STRING); + client.configResetStat(); + return getResponse(BuilderFactory.STRING); } public Response save() { - client.save(); - return getResponse(BuilderFactory.STRING); + client.save(); + return getResponse(BuilderFactory.STRING); } public Response lastsave() { - client.lastsave(); - return getResponse(BuilderFactory.LONG); + client.lastsave(); + return getResponse(BuilderFactory.LONG); } public Response publish(String channel, String message) { - client.publish(channel, message); - return getResponse(BuilderFactory.LONG); + client.publish(channel, message); + return getResponse(BuilderFactory.LONG); } public Response publish(byte[] channel, byte[] message) { - client.publish(channel, message); - return getResponse(BuilderFactory.LONG); + client.publish(channel, message); + return getResponse(BuilderFactory.LONG); } public Response randomKey() { - client.randomKey(); - return getResponse(BuilderFactory.STRING); + client.randomKey(); + return getResponse(BuilderFactory.STRING); } public Response randomKeyBinary() { - client.randomKey(); - return getResponse(BuilderFactory.BYTE_ARRAY); + client.randomKey(); + return getResponse(BuilderFactory.BYTE_ARRAY); } public Response flushDB() { - client.flushDB(); - return getResponse(BuilderFactory.STRING); + client.flushDB(); + return getResponse(BuilderFactory.STRING); } public Response flushAll() { - client.flushAll(); - return getResponse(BuilderFactory.STRING); + client.flushAll(); + return getResponse(BuilderFactory.STRING); } public Response info() { - client.info(); - return getResponse(BuilderFactory.STRING); + client.info(); + return getResponse(BuilderFactory.STRING); } public Response dbSize() { - client.dbSize(); - return getResponse(BuilderFactory.LONG); + client.dbSize(); + return getResponse(BuilderFactory.LONG); } public Response shutdown() { - client.shutdown(); - return getResponse(BuilderFactory.STRING); + client.shutdown(); + return getResponse(BuilderFactory.STRING); } public Response ping() { - client.ping(); - return getResponse(BuilderFactory.STRING); + client.ping(); + return getResponse(BuilderFactory.STRING); } public Response select(int index) { - client.select(index); - return getResponse(BuilderFactory.STRING); + client.select(index); + return getResponse(BuilderFactory.STRING); } public Response bitop(BitOP op, byte[] destKey, byte[]... srcKeys) { - client.bitop(op, destKey, srcKeys); - return getResponse(BuilderFactory.LONG); + client.bitop(op, destKey, srcKeys); + return getResponse(BuilderFactory.LONG); } public Response bitop(BitOP op, String destKey, String... srcKeys) { - client.bitop(op, destKey, srcKeys); - return getResponse(BuilderFactory.LONG); + client.bitop(op, destKey, srcKeys); + return getResponse(BuilderFactory.LONG); } - + public Response clusterNodes() { client.clusterNodes(); return getResponse(BuilderFactory.STRING); @@ -425,22 +423,26 @@ abstract class MultiKeyPipelineBase extends PipelineBase implements return getResponse(BuilderFactory.STRING); } - public Response> clusterGetKeysInSlot(final int slot, final int count) { + public Response> clusterGetKeysInSlot(final int slot, + final int count) { client.clusterGetKeysInSlot(slot, count); return getResponse(BuilderFactory.STRING_LIST); } - public Response clusterSetSlotNode(final int slot, final String nodeId) { + public Response clusterSetSlotNode(final int slot, + final String nodeId) { client.clusterSetSlotNode(slot, nodeId); return getResponse(BuilderFactory.STRING); } - public Response clusterSetSlotMigrating(final int slot, final String nodeId) { + public Response clusterSetSlotMigrating(final int slot, + final String nodeId) { client.clusterSetSlotMigrating(slot, nodeId); return getResponse(BuilderFactory.STRING); } - public Response clusterSetSlotImporting(final int slot, final String nodeId) { + public Response clusterSetSlotImporting(final int slot, + final String nodeId) { client.clusterSetSlotImporting(slot, nodeId); return getResponse(BuilderFactory.STRING); } diff --git a/src/main/java/redis/clients/jedis/Pipeline.java b/src/main/java/redis/clients/jedis/Pipeline.java index 98cab69..97f856b 100755 --- a/src/main/java/redis/clients/jedis/Pipeline.java +++ b/src/main/java/redis/clients/jedis/Pipeline.java @@ -1,66 +1,66 @@ package redis.clients.jedis; -import redis.clients.jedis.exceptions.JedisDataException; - import java.util.ArrayList; import java.util.List; -public class Pipeline extends MultiKeyPipelineBase { - - private MultiResponseBuilder currentMulti; - - private class MultiResponseBuilder extends Builder>{ - private List> responses = new ArrayList>(); - - @Override - public List build(Object data) { - @SuppressWarnings("unchecked") - List list = (List)data; - List values = new ArrayList(); - - if(list.size() != responses.size()){ - throw new JedisDataException("Expected data size " + responses.size() + " but was " + list.size()); - } - - for(int i=0;i response = responses.get(i); - response.set(list.get(i)); - values.add(response.get()); - } - return values; - } +import redis.clients.jedis.exceptions.JedisDataException; - public void addResponse(Response response){ - responses.add(response); - } +public class Pipeline extends MultiKeyPipelineBase { + + private MultiResponseBuilder currentMulti; + + private class MultiResponseBuilder extends Builder> { + private List> responses = new ArrayList>(); + + @Override + public List build(Object data) { + @SuppressWarnings("unchecked") + List list = (List) data; + List values = new ArrayList(); + + if (list.size() != responses.size()) { + throw new JedisDataException("Expected data size " + + responses.size() + " but was " + list.size()); + } + + for (int i = 0; i < list.size(); i++) { + Response response = responses.get(i); + response.set(list.get(i)); + values.add(response.get()); + } + return values; + } + + public void addResponse(Response response) { + responses.add(response); + } } @Override protected Response getResponse(Builder builder) { - if(currentMulti != null){ - super.getResponse(BuilderFactory.STRING); //Expected QUEUED - - Response lr = new Response(builder); - currentMulti.addResponse(lr); - return lr; - } - else{ - return super.getResponse(builder); - } + if (currentMulti != null) { + super.getResponse(BuilderFactory.STRING); // Expected QUEUED + + Response lr = new Response(builder); + currentMulti.addResponse(lr); + return lr; + } else { + return super.getResponse(builder); + } } public void setClient(Client client) { - this.client = client; + this.client = client; } @Override protected Client getClient(byte[] key) { - return client; + return client; } @Override protected Client getClient(String key) { - return client; + return client; } /** @@ -69,10 +69,10 @@ public class Pipeline extends MultiKeyPipelineBase { * the different Response of the commands you execute. */ public void sync() { - List unformatted = client.getAll(); - for (Object o : unformatted) { - generateResponse(o); - } + List unformatted = client.getAll(); + for (Object o : unformatted) { + generateResponse(o); + } } /** @@ -84,37 +84,38 @@ public class Pipeline extends MultiKeyPipelineBase { * @return A list of all the responses in the order you executed them. */ public List syncAndReturnAll() { - List unformatted = client.getAll(); - List formatted = new ArrayList(); - - for (Object o : unformatted) { - try { - formatted.add(generateResponse(o).get()); - } catch (JedisDataException e) { - formatted.add(e); - } - } - return formatted; + List unformatted = client.getAll(); + List formatted = new ArrayList(); + + for (Object o : unformatted) { + try { + formatted.add(generateResponse(o).get()); + } catch (JedisDataException e) { + formatted.add(e); + } + } + return formatted; } public Response discard() { - client.discard(); - currentMulti = null; - return getResponse(BuilderFactory.STRING); + client.discard(); + currentMulti = null; + return getResponse(BuilderFactory.STRING); } public Response> exec() { - client.exec(); - Response> response = super.getResponse(currentMulti); - currentMulti = null; - return response; + client.exec(); + Response> response = super.getResponse(currentMulti); + currentMulti = null; + return response; } public Response multi() { - client.multi(); - Response response = getResponse(BuilderFactory.STRING); //Expecting OK - currentMulti = new MultiResponseBuilder(); - return response; + client.multi(); + Response response = getResponse(BuilderFactory.STRING); // Expecting + // OK + currentMulti = new MultiResponseBuilder(); + return response; } } diff --git a/src/main/java/redis/clients/jedis/PipelineBase.java b/src/main/java/redis/clients/jedis/PipelineBase.java index 9ebcc9e..3183ba1 100644 --- a/src/main/java/redis/clients/jedis/PipelineBase.java +++ b/src/main/java/redis/clients/jedis/PipelineBase.java @@ -1,1191 +1,1207 @@ package redis.clients.jedis; -import redis.clients.jedis.BinaryClient.LIST_POSITION; +import static redis.clients.jedis.Protocol.toByteArray; import java.util.List; import java.util.Map; import java.util.Set; -import static redis.clients.jedis.Protocol.toByteArray; +import redis.clients.jedis.BinaryClient.LIST_POSITION; + +abstract class PipelineBase extends Queable implements BinaryRedisPipeline, + RedisPipeline { -abstract class PipelineBase extends Queable implements - BinaryRedisPipeline, - RedisPipeline { - protected abstract Client getClient(String key); - + protected abstract Client getClient(byte[] key); public Response append(String key, String value) { - getClient(key).append(key, value); - return getResponse(BuilderFactory.LONG); + getClient(key).append(key, value); + return getResponse(BuilderFactory.LONG); } public Response append(byte[] key, byte[] value) { - getClient(key).append(key, value); - return getResponse(BuilderFactory.LONG); + getClient(key).append(key, value); + return getResponse(BuilderFactory.LONG); } public Response> blpop(String key) { - String[] temp = new String[1]; - temp[0] = key; - getClient(key).blpop(temp); - return getResponse(BuilderFactory.STRING_LIST); + String[] temp = new String[1]; + temp[0] = key; + getClient(key).blpop(temp); + return getResponse(BuilderFactory.STRING_LIST); } public Response> brpop(String key) { - String[] temp = new String[1]; - temp[0] = key; - getClient(key).brpop(temp); - return getResponse(BuilderFactory.STRING_LIST); + String[] temp = new String[1]; + temp[0] = key; + getClient(key).brpop(temp); + return getResponse(BuilderFactory.STRING_LIST); } public Response> blpop(byte[] key) { - byte[][] temp = new byte[1][]; - temp[0] = key; - getClient(key).blpop(temp); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); + byte[][] temp = new byte[1][]; + temp[0] = key; + getClient(key).blpop(temp); + return getResponse(BuilderFactory.BYTE_ARRAY_LIST); } public Response> brpop(byte[] key) { - byte[][] temp = new byte[1][]; - temp[0] = key; - getClient(key).brpop(temp); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); + byte[][] temp = new byte[1][]; + temp[0] = key; + getClient(key).brpop(temp); + return getResponse(BuilderFactory.BYTE_ARRAY_LIST); } public Response decr(String key) { - getClient(key).decr(key); - return getResponse(BuilderFactory.LONG); + getClient(key).decr(key); + return getResponse(BuilderFactory.LONG); } public Response decr(byte[] key) { - getClient(key).decr(key); - return getResponse(BuilderFactory.LONG); + getClient(key).decr(key); + return getResponse(BuilderFactory.LONG); } public Response decrBy(String key, long integer) { - getClient(key).decrBy(key, integer); - return getResponse(BuilderFactory.LONG); + getClient(key).decrBy(key, integer); + return getResponse(BuilderFactory.LONG); } public Response decrBy(byte[] key, long integer) { - getClient(key).decrBy(key, integer); - return getResponse(BuilderFactory.LONG); + getClient(key).decrBy(key, integer); + return getResponse(BuilderFactory.LONG); } public Response del(String key) { - getClient(key).del(key); - return getResponse(BuilderFactory.LONG); + getClient(key).del(key); + return getResponse(BuilderFactory.LONG); } public Response del(byte[] key) { - getClient(key).del(key); - return getResponse(BuilderFactory.LONG); + getClient(key).del(key); + return getResponse(BuilderFactory.LONG); } public Response echo(String string) { - getClient(string).echo(string); - return getResponse(BuilderFactory.STRING); + getClient(string).echo(string); + return getResponse(BuilderFactory.STRING); } public Response echo(byte[] string) { - getClient(string).echo(string); - return getResponse(BuilderFactory.BYTE_ARRAY); + getClient(string).echo(string); + return getResponse(BuilderFactory.BYTE_ARRAY); } public Response exists(String key) { - getClient(key).exists(key); - return getResponse(BuilderFactory.BOOLEAN); + getClient(key).exists(key); + return getResponse(BuilderFactory.BOOLEAN); } public Response exists(byte[] key) { - getClient(key).exists(key); - return getResponse(BuilderFactory.BOOLEAN); + getClient(key).exists(key); + return getResponse(BuilderFactory.BOOLEAN); } public Response expire(String key, int seconds) { - getClient(key).expire(key, seconds); - return getResponse(BuilderFactory.LONG); + getClient(key).expire(key, seconds); + return getResponse(BuilderFactory.LONG); } public Response expire(byte[] key, int seconds) { - getClient(key).expire(key, seconds); - return getResponse(BuilderFactory.LONG); + getClient(key).expire(key, seconds); + return getResponse(BuilderFactory.LONG); } public Response expireAt(String key, long unixTime) { - getClient(key).expireAt(key, unixTime); - return getResponse(BuilderFactory.LONG); + getClient(key).expireAt(key, unixTime); + return getResponse(BuilderFactory.LONG); } public Response expireAt(byte[] key, long unixTime) { - getClient(key).expireAt(key, unixTime); - return getResponse(BuilderFactory.LONG); + getClient(key).expireAt(key, unixTime); + return getResponse(BuilderFactory.LONG); } public Response get(String key) { - getClient(key).get(key); - return getResponse(BuilderFactory.STRING); + getClient(key).get(key); + return getResponse(BuilderFactory.STRING); } public Response get(byte[] key) { - getClient(key).get(key); - return getResponse(BuilderFactory.BYTE_ARRAY); + getClient(key).get(key); + return getResponse(BuilderFactory.BYTE_ARRAY); } public Response getbit(String key, long offset) { - getClient(key).getbit(key, offset); - return getResponse(BuilderFactory.BOOLEAN); + getClient(key).getbit(key, offset); + return getResponse(BuilderFactory.BOOLEAN); } public Response getbit(byte[] key, long offset) { - getClient(key).getbit(key, offset); - return getResponse(BuilderFactory.BOOLEAN); + getClient(key).getbit(key, offset); + return getResponse(BuilderFactory.BOOLEAN); } public Response getrange(String key, long startOffset, - long endOffset) { - getClient(key).getrange(key, startOffset, endOffset); - return getResponse(BuilderFactory.STRING); + long endOffset) { + getClient(key).getrange(key, startOffset, endOffset); + return getResponse(BuilderFactory.STRING); } public Response getSet(String key, String value) { - getClient(key).getSet(key, value); - return getResponse(BuilderFactory.STRING); + getClient(key).getSet(key, value); + return getResponse(BuilderFactory.STRING); } public Response getSet(byte[] key, byte[] value) { - getClient(key).getSet(key, value); - return getResponse(BuilderFactory.BYTE_ARRAY); + getClient(key).getSet(key, value); + return getResponse(BuilderFactory.BYTE_ARRAY); } public Response getrange(byte[] key, long startOffset, long endOffset) { - getClient(key).getrange(key, startOffset, endOffset); - return getResponse(BuilderFactory.LONG); + getClient(key).getrange(key, startOffset, endOffset); + return getResponse(BuilderFactory.LONG); } public Response hdel(String key, String... field) { - getClient(key).hdel(key, field); - return getResponse(BuilderFactory.LONG); + getClient(key).hdel(key, field); + return getResponse(BuilderFactory.LONG); } public Response hdel(byte[] key, byte[]... field) { - getClient(key).hdel(key, field); - return getResponse(BuilderFactory.LONG); + getClient(key).hdel(key, field); + return getResponse(BuilderFactory.LONG); } public Response hexists(String key, String field) { - getClient(key).hexists(key, field); - return getResponse(BuilderFactory.BOOLEAN); + getClient(key).hexists(key, field); + return getResponse(BuilderFactory.BOOLEAN); } public Response hexists(byte[] key, byte[] field) { - getClient(key).hexists(key, field); - return getResponse(BuilderFactory.BOOLEAN); + getClient(key).hexists(key, field); + return getResponse(BuilderFactory.BOOLEAN); } public Response hget(String key, String field) { - getClient(key).hget(key, field); - return getResponse(BuilderFactory.STRING); + getClient(key).hget(key, field); + return getResponse(BuilderFactory.STRING); } public Response hget(byte[] key, byte[] field) { - getClient(key).hget(key, field); - return getResponse(BuilderFactory.BYTE_ARRAY); + getClient(key).hget(key, field); + return getResponse(BuilderFactory.BYTE_ARRAY); } public Response> hgetAll(String key) { - getClient(key).hgetAll(key); - return getResponse(BuilderFactory.STRING_MAP); + getClient(key).hgetAll(key); + return getResponse(BuilderFactory.STRING_MAP); } public Response> hgetAll(byte[] key) { - getClient(key).hgetAll(key); - return getResponse(BuilderFactory.BYTE_ARRAY_MAP); + getClient(key).hgetAll(key); + return getResponse(BuilderFactory.BYTE_ARRAY_MAP); } public Response hincrBy(String key, String field, long value) { - getClient(key).hincrBy(key, field, value); - return getResponse(BuilderFactory.LONG); + getClient(key).hincrBy(key, field, value); + return getResponse(BuilderFactory.LONG); } public Response hincrBy(byte[] key, byte[] field, long value) { - getClient(key).hincrBy(key, field, value); - return getResponse(BuilderFactory.LONG); + getClient(key).hincrBy(key, field, value); + return getResponse(BuilderFactory.LONG); } public Response> hkeys(String key) { - getClient(key).hkeys(key); - return getResponse(BuilderFactory.STRING_SET); + getClient(key).hkeys(key); + return getResponse(BuilderFactory.STRING_SET); } public Response> hkeys(byte[] key) { - getClient(key).hkeys(key); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); + getClient(key).hkeys(key); + return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); } public Response hlen(String key) { - getClient(key).hlen(key); - return getResponse(BuilderFactory.LONG); + getClient(key).hlen(key); + return getResponse(BuilderFactory.LONG); } public Response hlen(byte[] key) { - getClient(key).hlen(key); - return getResponse(BuilderFactory.LONG); + getClient(key).hlen(key); + return getResponse(BuilderFactory.LONG); } public Response> hmget(String key, String... fields) { - getClient(key).hmget(key, fields); - return getResponse(BuilderFactory.STRING_LIST); + getClient(key).hmget(key, fields); + return getResponse(BuilderFactory.STRING_LIST); } public Response> hmget(byte[] key, byte[]... fields) { - getClient(key).hmget(key, fields); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); + getClient(key).hmget(key, fields); + return getResponse(BuilderFactory.BYTE_ARRAY_LIST); } public Response hmset(String key, Map hash) { - getClient(key).hmset(key, hash); - return getResponse(BuilderFactory.STRING); + getClient(key).hmset(key, hash); + return getResponse(BuilderFactory.STRING); } public Response hmset(byte[] key, Map hash) { - getClient(key).hmset(key, hash); - return getResponse(BuilderFactory.STRING); + getClient(key).hmset(key, hash); + return getResponse(BuilderFactory.STRING); } public Response hset(String key, String field, String value) { - getClient(key).hset(key, field, value); - return getResponse(BuilderFactory.LONG); + getClient(key).hset(key, field, value); + return getResponse(BuilderFactory.LONG); } public Response hset(byte[] key, byte[] field, byte[] value) { - getClient(key).hset(key, field, value); - return getResponse(BuilderFactory.LONG); + getClient(key).hset(key, field, value); + return getResponse(BuilderFactory.LONG); } public Response hsetnx(String key, String field, String value) { - getClient(key).hsetnx(key, field, value); - return getResponse(BuilderFactory.LONG); + getClient(key).hsetnx(key, field, value); + return getResponse(BuilderFactory.LONG); } public Response hsetnx(byte[] key, byte[] field, byte[] value) { - getClient(key).hsetnx(key, field, value); - return getResponse(BuilderFactory.LONG); + getClient(key).hsetnx(key, field, value); + return getResponse(BuilderFactory.LONG); } public Response> hvals(String key) { - getClient(key).hvals(key); - return getResponse(BuilderFactory.STRING_LIST); + getClient(key).hvals(key); + return getResponse(BuilderFactory.STRING_LIST); } public Response> hvals(byte[] key) { - getClient(key).hvals(key); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); + getClient(key).hvals(key); + return getResponse(BuilderFactory.BYTE_ARRAY_LIST); } public Response incr(String key) { - getClient(key).incr(key); - return getResponse(BuilderFactory.LONG); + getClient(key).incr(key); + return getResponse(BuilderFactory.LONG); } public Response incr(byte[] key) { - getClient(key).incr(key); - return getResponse(BuilderFactory.LONG); + getClient(key).incr(key); + return getResponse(BuilderFactory.LONG); } public Response incrBy(String key, long integer) { - getClient(key).incrBy(key, integer); - return getResponse(BuilderFactory.LONG); + getClient(key).incrBy(key, integer); + return getResponse(BuilderFactory.LONG); } public Response incrBy(byte[] key, long integer) { - getClient(key).incrBy(key, integer); - return getResponse(BuilderFactory.LONG); + getClient(key).incrBy(key, integer); + return getResponse(BuilderFactory.LONG); } public Response lindex(String key, long index) { - getClient(key).lindex(key, index); - return getResponse(BuilderFactory.STRING); + getClient(key).lindex(key, index); + return getResponse(BuilderFactory.STRING); } public Response lindex(byte[] key, long index) { - getClient(key).lindex(key, index); - return getResponse(BuilderFactory.BYTE_ARRAY); + getClient(key).lindex(key, index); + return getResponse(BuilderFactory.BYTE_ARRAY); } public Response linsert(String key, LIST_POSITION where, - String pivot, String value) { - getClient(key).linsert(key, where, pivot, value); - return getResponse(BuilderFactory.LONG); + String pivot, String value) { + getClient(key).linsert(key, where, pivot, value); + return getResponse(BuilderFactory.LONG); } public Response linsert(byte[] key, LIST_POSITION where, - byte[] pivot, byte[] value) { - getClient(key).linsert(key, where, pivot, value); - return getResponse(BuilderFactory.LONG); + byte[] pivot, byte[] value) { + getClient(key).linsert(key, where, pivot, value); + return getResponse(BuilderFactory.LONG); } public Response llen(String key) { - getClient(key).llen(key); - return getResponse(BuilderFactory.LONG); + getClient(key).llen(key); + return getResponse(BuilderFactory.LONG); } public Response llen(byte[] key) { - getClient(key).llen(key); - return getResponse(BuilderFactory.LONG); + getClient(key).llen(key); + return getResponse(BuilderFactory.LONG); } public Response lpop(String key) { - getClient(key).lpop(key); - return getResponse(BuilderFactory.STRING); + getClient(key).lpop(key); + return getResponse(BuilderFactory.STRING); } public Response lpop(byte[] key) { - getClient(key).lpop(key); - return getResponse(BuilderFactory.BYTE_ARRAY); + getClient(key).lpop(key); + return getResponse(BuilderFactory.BYTE_ARRAY); } public Response lpush(String key, String... string) { - getClient(key).lpush(key, string); - return getResponse(BuilderFactory.LONG); + getClient(key).lpush(key, string); + return getResponse(BuilderFactory.LONG); } public Response lpush(byte[] key, byte[]... string) { - getClient(key).lpush(key, string); - return getResponse(BuilderFactory.LONG); + getClient(key).lpush(key, string); + return getResponse(BuilderFactory.LONG); } public Response lpushx(String key, String... string) { - getClient(key).lpushx(key, string); - return getResponse(BuilderFactory.LONG); + getClient(key).lpushx(key, string); + return getResponse(BuilderFactory.LONG); } public Response lpushx(byte[] key, byte[]... bytes) { - getClient(key).lpushx(key, bytes); - return getResponse(BuilderFactory.LONG); + getClient(key).lpushx(key, bytes); + return getResponse(BuilderFactory.LONG); } public Response> lrange(String key, long start, long end) { - getClient(key).lrange(key, start, end); - return getResponse(BuilderFactory.STRING_LIST); + getClient(key).lrange(key, start, end); + return getResponse(BuilderFactory.STRING_LIST); } public Response> lrange(byte[] key, long start, long end) { - getClient(key).lrange(key, start, end); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); + getClient(key).lrange(key, start, end); + return getResponse(BuilderFactory.BYTE_ARRAY_LIST); } public Response lrem(String key, long count, String value) { - getClient(key).lrem(key, count, value); - return getResponse(BuilderFactory.LONG); + getClient(key).lrem(key, count, value); + return getResponse(BuilderFactory.LONG); } public Response lrem(byte[] key, long count, byte[] value) { - getClient(key).lrem(key, count, value); - return getResponse(BuilderFactory.LONG); + getClient(key).lrem(key, count, value); + return getResponse(BuilderFactory.LONG); } public Response lset(String key, long index, String value) { - getClient(key).lset(key, index, value); - return getResponse(BuilderFactory.STRING); + getClient(key).lset(key, index, value); + return getResponse(BuilderFactory.STRING); } public Response lset(byte[] key, long index, byte[] value) { - getClient(key).lset(key, index, value); - return getResponse(BuilderFactory.STRING); + getClient(key).lset(key, index, value); + return getResponse(BuilderFactory.STRING); } public Response ltrim(String key, long start, long end) { - getClient(key).ltrim(key, start, end); - return getResponse(BuilderFactory.STRING); + getClient(key).ltrim(key, start, end); + return getResponse(BuilderFactory.STRING); } public Response ltrim(byte[] key, long start, long end) { - getClient(key).ltrim(key, start, end); - return getResponse(BuilderFactory.STRING); + getClient(key).ltrim(key, start, end); + return getResponse(BuilderFactory.STRING); } public Response move(String key, int dbIndex) { - getClient(key).move(key, dbIndex); - return getResponse(BuilderFactory.LONG); + getClient(key).move(key, dbIndex); + return getResponse(BuilderFactory.LONG); } public Response move(byte[] key, int dbIndex) { - getClient(key).move(key, dbIndex); - return getResponse(BuilderFactory.LONG); + getClient(key).move(key, dbIndex); + return getResponse(BuilderFactory.LONG); } public Response persist(String key) { - getClient(key).persist(key); - return getResponse(BuilderFactory.LONG); + getClient(key).persist(key); + return getResponse(BuilderFactory.LONG); } public Response persist(byte[] key) { - getClient(key).persist(key); - return getResponse(BuilderFactory.LONG); + getClient(key).persist(key); + return getResponse(BuilderFactory.LONG); } public Response rpop(String key) { - getClient(key).rpop(key); - return getResponse(BuilderFactory.STRING); + getClient(key).rpop(key); + return getResponse(BuilderFactory.STRING); } public Response rpop(byte[] key) { - getClient(key).rpop(key); - return getResponse(BuilderFactory.BYTE_ARRAY); + getClient(key).rpop(key); + return getResponse(BuilderFactory.BYTE_ARRAY); } public Response rpush(String key, String... string) { - getClient(key).rpush(key, string); - return getResponse(BuilderFactory.LONG); + getClient(key).rpush(key, string); + return getResponse(BuilderFactory.LONG); } public Response rpush(byte[] key, byte[]... string) { - getClient(key).rpush(key, string); - return getResponse(BuilderFactory.LONG); + getClient(key).rpush(key, string); + return getResponse(BuilderFactory.LONG); } public Response rpushx(String key, String... string) { - getClient(key).rpushx(key, string); - return getResponse(BuilderFactory.LONG); + getClient(key).rpushx(key, string); + return getResponse(BuilderFactory.LONG); } public Response rpushx(byte[] key, byte[]... string) { - getClient(key).rpushx(key, string); - return getResponse(BuilderFactory.LONG); + getClient(key).rpushx(key, string); + return getResponse(BuilderFactory.LONG); } public Response sadd(String key, String... member) { - getClient(key).sadd(key, member); - return getResponse(BuilderFactory.LONG); + getClient(key).sadd(key, member); + return getResponse(BuilderFactory.LONG); } public Response sadd(byte[] key, byte[]... member) { - getClient(key).sadd(key, member); - return getResponse(BuilderFactory.LONG); + getClient(key).sadd(key, member); + return getResponse(BuilderFactory.LONG); } public Response scard(String key) { - getClient(key).scard(key); - return getResponse(BuilderFactory.LONG); + getClient(key).scard(key); + return getResponse(BuilderFactory.LONG); } public Response scard(byte[] key) { - getClient(key).scard(key); - return getResponse(BuilderFactory.LONG); + getClient(key).scard(key); + return getResponse(BuilderFactory.LONG); } public Response set(String key, String value) { - getClient(key).set(key, value); - return getResponse(BuilderFactory.STRING); + getClient(key).set(key, value); + return getResponse(BuilderFactory.STRING); } public Response set(byte[] key, byte[] value) { - getClient(key).set(key, value); - return getResponse(BuilderFactory.STRING); + getClient(key).set(key, value); + return getResponse(BuilderFactory.STRING); } public Response setbit(String key, long offset, boolean value) { - getClient(key).setbit(key, offset, value); - return getResponse(BuilderFactory.BOOLEAN); + getClient(key).setbit(key, offset, value); + return getResponse(BuilderFactory.BOOLEAN); } public Response setbit(byte[] key, long offset, byte[] value) { - getClient(key).setbit(key, offset, value); - return getResponse(BuilderFactory.BOOLEAN); + getClient(key).setbit(key, offset, value); + return getResponse(BuilderFactory.BOOLEAN); } public Response setex(String key, int seconds, String value) { - getClient(key).setex(key, seconds, value); - return getResponse(BuilderFactory.STRING); + getClient(key).setex(key, seconds, value); + return getResponse(BuilderFactory.STRING); } public Response setex(byte[] key, int seconds, byte[] value) { - getClient(key).setex(key, seconds, value); - return getResponse(BuilderFactory.STRING); + getClient(key).setex(key, seconds, value); + return getResponse(BuilderFactory.STRING); } public Response setnx(String key, String value) { - getClient(key).setnx(key, value); - return getResponse(BuilderFactory.LONG); + getClient(key).setnx(key, value); + return getResponse(BuilderFactory.LONG); } public Response setnx(byte[] key, byte[] value) { - getClient(key).setnx(key, value); - return getResponse(BuilderFactory.LONG); + getClient(key).setnx(key, value); + return getResponse(BuilderFactory.LONG); } public Response setrange(String key, long offset, String value) { - getClient(key).setrange(key, offset, value); - return getResponse(BuilderFactory.LONG); + getClient(key).setrange(key, offset, value); + return getResponse(BuilderFactory.LONG); } public Response setrange(byte[] key, long offset, byte[] value) { - getClient(key).setrange(key, offset, value); - return getResponse(BuilderFactory.LONG); + getClient(key).setrange(key, offset, value); + return getResponse(BuilderFactory.LONG); } public Response sismember(String key, String member) { - getClient(key).sismember(key, member); - return getResponse(BuilderFactory.BOOLEAN); + getClient(key).sismember(key, member); + return getResponse(BuilderFactory.BOOLEAN); } public Response sismember(byte[] key, byte[] member) { - getClient(key).sismember(key, member); - return getResponse(BuilderFactory.BOOLEAN); + getClient(key).sismember(key, member); + return getResponse(BuilderFactory.BOOLEAN); } public Response> smembers(String key) { - getClient(key).smembers(key); - return getResponse(BuilderFactory.STRING_SET); + getClient(key).smembers(key); + return getResponse(BuilderFactory.STRING_SET); } public Response> smembers(byte[] key) { - getClient(key).smembers(key); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); + getClient(key).smembers(key); + return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); } public Response> sort(String key) { - getClient(key).sort(key); - return getResponse(BuilderFactory.STRING_LIST); + getClient(key).sort(key); + return getResponse(BuilderFactory.STRING_LIST); } public Response> sort(byte[] key) { - getClient(key).sort(key); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); + getClient(key).sort(key); + return getResponse(BuilderFactory.BYTE_ARRAY_LIST); } public Response> sort(String key, - SortingParams sortingParameters) { - getClient(key).sort(key, sortingParameters); - return getResponse(BuilderFactory.STRING_LIST); + SortingParams sortingParameters) { + getClient(key).sort(key, sortingParameters); + return getResponse(BuilderFactory.STRING_LIST); } public Response> sort(byte[] key, - SortingParams sortingParameters) { - getClient(key).sort(key, sortingParameters); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); + SortingParams sortingParameters) { + getClient(key).sort(key, sortingParameters); + return getResponse(BuilderFactory.BYTE_ARRAY_LIST); } public Response spop(String key) { - getClient(key).spop(key); - return getResponse(BuilderFactory.STRING); + getClient(key).spop(key); + return getResponse(BuilderFactory.STRING); } public Response spop(byte[] key) { - getClient(key).spop(key); - return getResponse(BuilderFactory.BYTE_ARRAY); + getClient(key).spop(key); + return getResponse(BuilderFactory.BYTE_ARRAY); } public Response srandmember(String key) { - getClient(key).srandmember(key); - return getResponse(BuilderFactory.STRING); + getClient(key).srandmember(key); + return getResponse(BuilderFactory.STRING); } - + public Response> srandmember(String key, int count) { - getClient(key).srandmember(key, count); - return getResponse(BuilderFactory.STRING_LIST); + getClient(key).srandmember(key, count); + return getResponse(BuilderFactory.STRING_LIST); } public Response srandmember(byte[] key) { - getClient(key).srandmember(key); - return getResponse(BuilderFactory.BYTE_ARRAY); + getClient(key).srandmember(key); + return getResponse(BuilderFactory.BYTE_ARRAY); } - + public Response> srandmember(byte[] key, int count) { - getClient(key).srandmember(key, count); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); + getClient(key).srandmember(key, count); + return getResponse(BuilderFactory.BYTE_ARRAY_LIST); } public Response srem(String key, String... member) { - getClient(key).srem(key, member); - return getResponse(BuilderFactory.LONG); + getClient(key).srem(key, member); + return getResponse(BuilderFactory.LONG); } public Response srem(byte[] key, byte[]... member) { - getClient(key).srem(key, member); - return getResponse(BuilderFactory.LONG); + getClient(key).srem(key, member); + return getResponse(BuilderFactory.LONG); } public Response strlen(String key) { - getClient(key).strlen(key); - return getResponse(BuilderFactory.LONG); + getClient(key).strlen(key); + return getResponse(BuilderFactory.LONG); } public Response strlen(byte[] key) { - getClient(key).strlen(key); - return getResponse(BuilderFactory.LONG); + getClient(key).strlen(key); + return getResponse(BuilderFactory.LONG); } public Response substr(String key, int start, int end) { - getClient(key).substr(key, start, end); - return getResponse(BuilderFactory.STRING); + getClient(key).substr(key, start, end); + return getResponse(BuilderFactory.STRING); } public Response substr(byte[] key, int start, int end) { - getClient(key).substr(key, start, end); - return getResponse(BuilderFactory.STRING); + getClient(key).substr(key, start, end); + return getResponse(BuilderFactory.STRING); } public Response ttl(String key) { - getClient(key).ttl(key); - return getResponse(BuilderFactory.LONG); + getClient(key).ttl(key); + return getResponse(BuilderFactory.LONG); } public Response ttl(byte[] key) { - getClient(key).ttl(key); - return getResponse(BuilderFactory.LONG); + getClient(key).ttl(key); + return getResponse(BuilderFactory.LONG); } public Response type(String key) { - getClient(key).type(key); - return getResponse(BuilderFactory.STRING); + getClient(key).type(key); + return getResponse(BuilderFactory.STRING); } public Response type(byte[] key) { - getClient(key).type(key); - return getResponse(BuilderFactory.STRING); + getClient(key).type(key); + return getResponse(BuilderFactory.STRING); + } + + public Response zadd(String key, double score, String member) { + getClient(key).zadd(key, score, member); + return getResponse(BuilderFactory.LONG); } - - public Response zadd(String key, double score, String member) { - getClient(key).zadd(key, score, member); - return getResponse(BuilderFactory.LONG); - } public Response zadd(String key, Map scoreMembers) { - getClient(key).zadd(key, scoreMembers); - return getResponse(BuilderFactory.LONG); + getClient(key).zadd(key, scoreMembers); + return getResponse(BuilderFactory.LONG); } public Response zadd(byte[] key, double score, byte[] member) { - getClient(key).zadd(key, score, member); - return getResponse(BuilderFactory.LONG); + getClient(key).zadd(key, score, member); + return getResponse(BuilderFactory.LONG); } public Response zcard(String key) { - getClient(key).zcard(key); - return getResponse(BuilderFactory.LONG); + getClient(key).zcard(key); + return getResponse(BuilderFactory.LONG); } public Response zcard(byte[] key) { - getClient(key).zcard(key); - return getResponse(BuilderFactory.LONG); + getClient(key).zcard(key); + return getResponse(BuilderFactory.LONG); } public Response zcount(String key, double min, double max) { - getClient(key).zcount(key, min, max); - return getResponse(BuilderFactory.LONG); + getClient(key).zcount(key, min, max); + return getResponse(BuilderFactory.LONG); } - + public Response zcount(String key, String min, String max) { - getClient(key).zcount(key, min, max); - return getResponse(BuilderFactory.LONG); + getClient(key).zcount(key, min, max); + return getResponse(BuilderFactory.LONG); } public Response zcount(byte[] key, double min, double max) { - getClient(key).zcount(key, toByteArray(min), toByteArray(max)); - return getResponse(BuilderFactory.LONG); + getClient(key).zcount(key, toByteArray(min), toByteArray(max)); + return getResponse(BuilderFactory.LONG); } public Response zincrby(String key, double score, String member) { - getClient(key).zincrby(key, score, member); - return getResponse(BuilderFactory.DOUBLE); + getClient(key).zincrby(key, score, member); + return getResponse(BuilderFactory.DOUBLE); } public Response zincrby(byte[] key, double score, byte[] member) { - getClient(key).zincrby(key, score, member); - return getResponse(BuilderFactory.DOUBLE); + getClient(key).zincrby(key, score, member); + return getResponse(BuilderFactory.DOUBLE); } public Response> zrange(String key, long start, long end) { - getClient(key).zrange(key, start, end); - return getResponse(BuilderFactory.STRING_ZSET); + getClient(key).zrange(key, start, end); + return getResponse(BuilderFactory.STRING_ZSET); } public Response> zrange(byte[] key, long start, long end) { - getClient(key).zrange(key, start, end); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); + getClient(key).zrange(key, start, end); + return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); } public Response> zrangeByScore(String key, double min, - double max) { - getClient(key).zrangeByScore(key, min, max); - return getResponse(BuilderFactory.STRING_ZSET); + double max) { + getClient(key).zrangeByScore(key, min, max); + return getResponse(BuilderFactory.STRING_ZSET); } public Response> zrangeByScore(byte[] key, double min, - double max) { - return zrangeByScore(key, toByteArray(min), toByteArray(max)); + double max) { + return zrangeByScore(key, toByteArray(min), toByteArray(max)); } public Response> zrangeByScore(String key, String min, - String max) { - getClient(key).zrangeByScore(key, min, max); - return getResponse(BuilderFactory.STRING_ZSET); + String max) { + getClient(key).zrangeByScore(key, min, max); + return getResponse(BuilderFactory.STRING_ZSET); } public Response> zrangeByScore(byte[] key, byte[] min, - byte[] max) { - getClient(key).zrangeByScore(key, min, max); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); + byte[] max) { + getClient(key).zrangeByScore(key, min, max); + return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); } public Response> zrangeByScore(String key, double min, - double max, int offset, int count) { - getClient(key).zrangeByScore(key, min, max, offset, count); - return getResponse(BuilderFactory.STRING_ZSET); + double max, int offset, int count) { + getClient(key).zrangeByScore(key, min, max, offset, count); + return getResponse(BuilderFactory.STRING_ZSET); + } + + public Response> zrangeByScore(String key, String min, + String max, int offset, int count) { + getClient(key).zrangeByScore(key, min, max, offset, count); + return getResponse(BuilderFactory.STRING_ZSET); } - - public Response> zrangeByScore(String key, String min, String max, int offset, int count) { - getClient(key).zrangeByScore(key, min, max, offset, count); - return getResponse(BuilderFactory.STRING_ZSET); - } public Response> zrangeByScore(byte[] key, double min, - double max, int offset, int count) { - return zrangeByScore(key, toByteArray(min), toByteArray(max), offset, count); + double max, int offset, int count) { + return zrangeByScore(key, toByteArray(min), toByteArray(max), offset, + count); } public Response> zrangeByScore(byte[] key, byte[] min, - byte[] max, int offset, int count) { - getClient(key).zrangeByScore(key, min, max, offset, count); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); + byte[] max, int offset, int count) { + getClient(key).zrangeByScore(key, min, max, offset, count); + return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); } public Response> zrangeByScoreWithScores(String key, double min, - double max) { - getClient(key).zrangeByScoreWithScores(key, min, max); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - public Response> zrangeByScoreWithScores(String key, String min, - String max) { - getClient(key).zrangeByScoreWithScores(key, min, max); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - public Response> zrangeByScoreWithScores(byte[] key, double min, - double max) { - return zrangeByScoreWithScores(key, toByteArray(min), toByteArray(max)); + double max) { + getClient(key).zrangeByScoreWithScores(key, min, max); + return getResponse(BuilderFactory.TUPLE_ZSET); } - public Response> zrangeByScoreWithScores(byte[] key, byte[] min, - byte[] max) { - getClient(key).zrangeByScoreWithScores(key, min, max); - return getResponse(BuilderFactory.TUPLE_ZSET_BINARY); - } - - public Response> zrangeByScoreWithScores(String key, double min, - double max, int offset, int count) { - getClient(key).zrangeByScoreWithScores(key, min, max, offset, count); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - public Response> zrangeByScoreWithScores(String key, String min, - String max, int offset, int count) { - getClient(key).zrangeByScoreWithScores(key, min, max, offset, count); - return getResponse(BuilderFactory.TUPLE_ZSET); + String max) { + getClient(key).zrangeByScoreWithScores(key, min, max); + return getResponse(BuilderFactory.TUPLE_ZSET); } public Response> zrangeByScoreWithScores(byte[] key, double min, - double max, int offset, int count) { - getClient(key).zrangeByScoreWithScores(key, toByteArray(min), toByteArray(max), offset, count); - return getResponse(BuilderFactory.TUPLE_ZSET_BINARY); + double max) { + return zrangeByScoreWithScores(key, toByteArray(min), toByteArray(max)); } public Response> zrangeByScoreWithScores(byte[] key, byte[] min, - byte[] max, int offset, int count) { - getClient(key).zrangeByScoreWithScores(key, min, max, offset, count); - return getResponse(BuilderFactory.TUPLE_ZSET_BINARY); + byte[] max) { + getClient(key).zrangeByScoreWithScores(key, min, max); + return getResponse(BuilderFactory.TUPLE_ZSET_BINARY); + } + + public Response> zrangeByScoreWithScores(String key, double min, + double max, int offset, int count) { + getClient(key).zrangeByScoreWithScores(key, min, max, offset, count); + return getResponse(BuilderFactory.TUPLE_ZSET); + } + + public Response> zrangeByScoreWithScores(String key, String min, + String max, int offset, int count) { + getClient(key).zrangeByScoreWithScores(key, min, max, offset, count); + return getResponse(BuilderFactory.TUPLE_ZSET); + } + + public Response> zrangeByScoreWithScores(byte[] key, double min, + double max, int offset, int count) { + getClient(key).zrangeByScoreWithScores(key, toByteArray(min), + toByteArray(max), offset, count); + return getResponse(BuilderFactory.TUPLE_ZSET_BINARY); + } + + public Response> zrangeByScoreWithScores(byte[] key, byte[] min, + byte[] max, int offset, int count) { + getClient(key).zrangeByScoreWithScores(key, min, max, offset, count); + return getResponse(BuilderFactory.TUPLE_ZSET_BINARY); } public Response> zrevrangeByScore(String key, double max, - double min) { - getClient(key).zrevrangeByScore(key, max, min); - return getResponse(BuilderFactory.STRING_ZSET); + double min) { + getClient(key).zrevrangeByScore(key, max, min); + return getResponse(BuilderFactory.STRING_ZSET); } public Response> zrevrangeByScore(byte[] key, double max, - double min) { - getClient(key).zrevrangeByScore(key, toByteArray(max), toByteArray(min)); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); + double min) { + getClient(key) + .zrevrangeByScore(key, toByteArray(max), toByteArray(min)); + return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); } public Response> zrevrangeByScore(String key, String max, - String min) { - getClient(key).zrevrangeByScore(key, max, min); - return getResponse(BuilderFactory.STRING_ZSET); + String min) { + getClient(key).zrevrangeByScore(key, max, min); + return getResponse(BuilderFactory.STRING_ZSET); } public Response> zrevrangeByScore(byte[] key, byte[] max, - byte[] min) { - getClient(key).zrevrangeByScore(key, max, min); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); + byte[] min) { + getClient(key).zrevrangeByScore(key, max, min); + return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); } public Response> zrevrangeByScore(String key, double max, - double min, int offset, int count) { - getClient(key).zrevrangeByScore(key, max, min, offset, count); - return getResponse(BuilderFactory.STRING_ZSET); + double min, int offset, int count) { + getClient(key).zrevrangeByScore(key, max, min, offset, count); + return getResponse(BuilderFactory.STRING_ZSET); + } + + public Response> zrevrangeByScore(String key, String max, + String min, int offset, int count) { + getClient(key).zrevrangeByScore(key, max, min, offset, count); + return getResponse(BuilderFactory.STRING_ZSET); } - - public Response> zrevrangeByScore(String key, String max, - String min, int offset, int count) { - getClient(key).zrevrangeByScore(key, max, min, offset, count); - return getResponse(BuilderFactory.STRING_ZSET); - } public Response> zrevrangeByScore(byte[] key, double max, - double min, int offset, int count) { - getClient(key).zrevrangeByScore(key, toByteArray(max), toByteArray(min), offset, count); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); + double min, int offset, int count) { + getClient(key).zrevrangeByScore(key, toByteArray(max), + toByteArray(min), offset, count); + return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); } public Response> zrevrangeByScore(byte[] key, byte[] max, - byte[] min, int offset, int count) { - getClient(key).zrevrangeByScore(key, max, min, offset, count); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); + byte[] min, int offset, int count) { + getClient(key).zrevrangeByScore(key, max, min, offset, count); + return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); } public Response> zrevrangeByScoreWithScores(String key, - double max, double min) { - getClient(key).zrevrangeByScoreWithScores(key, max, min); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - public Response> zrevrangeByScoreWithScores(String key, - String max, String min) { - getClient(key).zrevrangeByScoreWithScores(key, max, min); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - public Response> zrevrangeByScoreWithScores(byte[] key, - double max, double min) { - getClient(key).zrevrangeByScoreWithScores(key, toByteArray(max), toByteArray(min)); - return getResponse(BuilderFactory.TUPLE_ZSET_BINARY); - } - - public Response> zrevrangeByScoreWithScores(byte[] key, - byte[] max, byte[] min) { - getClient(key).zrevrangeByScoreWithScores(key, max, min); - return getResponse(BuilderFactory.TUPLE_ZSET_BINARY); - } - - public Response> zrevrangeByScoreWithScores(String key, - double max, double min, int offset, int count) { - getClient(key).zrevrangeByScoreWithScores(key, max, min, offset, count); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - public Response> zrevrangeByScoreWithScores(String key, - String max, String min, int offset, int count) { - getClient(key).zrevrangeByScoreWithScores(key, max, min, offset, count); + double max, double min) { + getClient(key).zrevrangeByScoreWithScores(key, max, min); return getResponse(BuilderFactory.TUPLE_ZSET); - } + } - public Response> zrevrangeByScoreWithScores(byte[] key, - double max, double min, int offset, int count) { - getClient(key).zrevrangeByScoreWithScores(key, toByteArray(max), toByteArray(min), offset, count); - return getResponse(BuilderFactory.TUPLE_ZSET_BINARY); + public Response> zrevrangeByScoreWithScores(String key, + String max, String min) { + getClient(key).zrevrangeByScoreWithScores(key, max, min); + return getResponse(BuilderFactory.TUPLE_ZSET); } public Response> zrevrangeByScoreWithScores(byte[] key, - byte[] max, byte[] min, int offset, int count) { - getClient(key).zrevrangeByScoreWithScores(key, max, min, offset, count); - return getResponse(BuilderFactory.TUPLE_ZSET_BINARY); + double max, double min) { + getClient(key).zrevrangeByScoreWithScores(key, toByteArray(max), + toByteArray(min)); + return getResponse(BuilderFactory.TUPLE_ZSET_BINARY); } - public Response> zrangeWithScores(String key, long start, long end) { - getClient(key).zrangeWithScores(key, start, end); - return getResponse(BuilderFactory.TUPLE_ZSET); + public Response> zrevrangeByScoreWithScores(byte[] key, + byte[] max, byte[] min) { + getClient(key).zrevrangeByScoreWithScores(key, max, min); + return getResponse(BuilderFactory.TUPLE_ZSET_BINARY); } - public Response> zrangeWithScores(byte[] key, long start, long end) { - getClient(key).zrangeWithScores(key, start, end); - return getResponse(BuilderFactory.TUPLE_ZSET_BINARY); + public Response> zrevrangeByScoreWithScores(String key, + double max, double min, int offset, int count) { + getClient(key).zrevrangeByScoreWithScores(key, max, min, offset, count); + return getResponse(BuilderFactory.TUPLE_ZSET); + } + + public Response> zrevrangeByScoreWithScores(String key, + String max, String min, int offset, int count) { + getClient(key).zrevrangeByScoreWithScores(key, max, min, offset, count); + return getResponse(BuilderFactory.TUPLE_ZSET); + } + + public Response> zrevrangeByScoreWithScores(byte[] key, + double max, double min, int offset, int count) { + getClient(key).zrevrangeByScoreWithScores(key, toByteArray(max), + toByteArray(min), offset, count); + return getResponse(BuilderFactory.TUPLE_ZSET_BINARY); + } + + public Response> zrevrangeByScoreWithScores(byte[] key, + byte[] max, byte[] min, int offset, int count) { + getClient(key).zrevrangeByScoreWithScores(key, max, min, offset, count); + return getResponse(BuilderFactory.TUPLE_ZSET_BINARY); + } + + public Response> zrangeWithScores(String key, long start, + long end) { + getClient(key).zrangeWithScores(key, start, end); + return getResponse(BuilderFactory.TUPLE_ZSET); + } + + public Response> zrangeWithScores(byte[] key, long start, + long end) { + getClient(key).zrangeWithScores(key, start, end); + return getResponse(BuilderFactory.TUPLE_ZSET_BINARY); } public Response zrank(String key, String member) { - getClient(key).zrank(key, member); - return getResponse(BuilderFactory.LONG); + getClient(key).zrank(key, member); + return getResponse(BuilderFactory.LONG); } public Response zrank(byte[] key, byte[] member) { - getClient(key).zrank(key, member); - return getResponse(BuilderFactory.LONG); + getClient(key).zrank(key, member); + return getResponse(BuilderFactory.LONG); } public Response zrem(String key, String... member) { - getClient(key).zrem(key, member); - return getResponse(BuilderFactory.LONG); + getClient(key).zrem(key, member); + return getResponse(BuilderFactory.LONG); } public Response zrem(byte[] key, byte[]... member) { - getClient(key).zrem(key, member); - return getResponse(BuilderFactory.LONG); + getClient(key).zrem(key, member); + return getResponse(BuilderFactory.LONG); } public Response zremrangeByRank(String key, long start, long end) { - getClient(key).zremrangeByRank(key, start, end); - return getResponse(BuilderFactory.LONG); + getClient(key).zremrangeByRank(key, start, end); + return getResponse(BuilderFactory.LONG); } public Response zremrangeByRank(byte[] key, long start, long end) { - getClient(key).zremrangeByRank(key, start, end); - return getResponse(BuilderFactory.LONG); + getClient(key).zremrangeByRank(key, start, end); + return getResponse(BuilderFactory.LONG); } public Response zremrangeByScore(String key, double start, double end) { - getClient(key).zremrangeByScore(key, start, end); - return getResponse(BuilderFactory.LONG); + getClient(key).zremrangeByScore(key, start, end); + return getResponse(BuilderFactory.LONG); } - + public Response zremrangeByScore(String key, String start, String end) { - getClient(key).zremrangeByScore(key, start, end); - return getResponse(BuilderFactory.LONG); + getClient(key).zremrangeByScore(key, start, end); + return getResponse(BuilderFactory.LONG); } public Response zremrangeByScore(byte[] key, double start, double end) { - getClient(key).zremrangeByScore(key, toByteArray(start), toByteArray(end)); - return getResponse(BuilderFactory.LONG); + getClient(key).zremrangeByScore(key, toByteArray(start), + toByteArray(end)); + return getResponse(BuilderFactory.LONG); } public Response zremrangeByScore(byte[] key, byte[] start, byte[] end) { - getClient(key).zremrangeByScore(key, start, end); - return getResponse(BuilderFactory.LONG); + getClient(key).zremrangeByScore(key, start, end); + return getResponse(BuilderFactory.LONG); } public Response> zrevrange(String key, long start, long end) { - getClient(key).zrevrange(key, start, end); - return getResponse(BuilderFactory.STRING_ZSET); + getClient(key).zrevrange(key, start, end); + return getResponse(BuilderFactory.STRING_ZSET); } public Response> zrevrange(byte[] key, long start, long end) { - getClient(key).zrevrange(key, start, end); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); + getClient(key).zrevrange(key, start, end); + return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); } public Response> zrevrangeWithScores(String key, long start, - long end) { - getClient(key).zrevrangeWithScores(key, start, end); - return getResponse(BuilderFactory.TUPLE_ZSET); + long end) { + getClient(key).zrevrangeWithScores(key, start, end); + return getResponse(BuilderFactory.TUPLE_ZSET); } public Response> zrevrangeWithScores(byte[] key, long start, - long end) { - getClient(key).zrevrangeWithScores(key, start, end); - return getResponse(BuilderFactory.TUPLE_ZSET); + long end) { + getClient(key).zrevrangeWithScores(key, start, end); + return getResponse(BuilderFactory.TUPLE_ZSET); } public Response zrevrank(String key, String member) { - getClient(key).zrevrank(key, member); - return getResponse(BuilderFactory.LONG); + getClient(key).zrevrank(key, member); + return getResponse(BuilderFactory.LONG); } public Response zrevrank(byte[] key, byte[] member) { - getClient(key).zrevrank(key, member); - return getResponse(BuilderFactory.LONG); + getClient(key).zrevrank(key, member); + return getResponse(BuilderFactory.LONG); } public Response zscore(String key, String member) { - getClient(key).zscore(key, member); - return getResponse(BuilderFactory.DOUBLE); + getClient(key).zscore(key, member); + return getResponse(BuilderFactory.DOUBLE); } public Response zscore(byte[] key, byte[] member) { - getClient(key).zscore(key, member); - return getResponse(BuilderFactory.DOUBLE); + getClient(key).zscore(key, member); + return getResponse(BuilderFactory.DOUBLE); } public Response bitcount(String key) { - getClient(key).bitcount(key); - return getResponse(BuilderFactory.LONG); + getClient(key).bitcount(key); + return getResponse(BuilderFactory.LONG); } public Response bitcount(String key, long start, long end) { - getClient(key).bitcount(key, start, end); - return getResponse(BuilderFactory.LONG); + getClient(key).bitcount(key, start, end); + return getResponse(BuilderFactory.LONG); } public Response bitcount(byte[] key) { - getClient(key).bitcount(key); - return getResponse(BuilderFactory.LONG); + getClient(key).bitcount(key); + return getResponse(BuilderFactory.LONG); } public Response bitcount(byte[] key, long start, long end) { - getClient(key).bitcount(key, start, end); - return getResponse(BuilderFactory.LONG); + getClient(key).bitcount(key, start, end); + return getResponse(BuilderFactory.LONG); } - + public Response dump(String key) { - getClient(key).dump(key); - return getResponse(BuilderFactory.BYTE_ARRAY); + getClient(key).dump(key); + return getResponse(BuilderFactory.BYTE_ARRAY); } - + public Response dump(byte[] key) { - getClient(key).dump(key); - return getResponse(BuilderFactory.BYTE_ARRAY); + getClient(key).dump(key); + return getResponse(BuilderFactory.BYTE_ARRAY); } - - public Response migrate(String host, int port, String key, int destinationDb, int timeout) { - getClient(key).migrate(host, port, key, destinationDb, timeout); - return getResponse(BuilderFactory.STRING); + + public Response migrate(String host, int port, String key, + int destinationDb, int timeout) { + getClient(key).migrate(host, port, key, destinationDb, timeout); + return getResponse(BuilderFactory.STRING); } - - public Response migrate(byte[] host, int port, byte[] key, int destinationDb, int timeout) { - getClient(key).migrate(host, port, key, destinationDb, timeout); - return getResponse(BuilderFactory.STRING); + + public Response migrate(byte[] host, int port, byte[] key, + int destinationDb, int timeout) { + getClient(key).migrate(host, port, key, destinationDb, timeout); + return getResponse(BuilderFactory.STRING); } - + public Response objectRefcount(String key) { - getClient(key).objectRefcount(key); - return getResponse(BuilderFactory.LONG); + getClient(key).objectRefcount(key); + return getResponse(BuilderFactory.LONG); } - + public Response objectRefcount(byte[] key) { - getClient(key).objectRefcount(key); - return getResponse(BuilderFactory.LONG); + getClient(key).objectRefcount(key); + return getResponse(BuilderFactory.LONG); } - + public Response objectEncoding(String key) { - getClient(key).objectEncoding(key); - return getResponse(BuilderFactory.STRING); + getClient(key).objectEncoding(key); + return getResponse(BuilderFactory.STRING); } - + public Response objectEncoding(byte[] key) { - getClient(key).objectEncoding(key); - return getResponse(BuilderFactory.BYTE_ARRAY); + getClient(key).objectEncoding(key); + return getResponse(BuilderFactory.BYTE_ARRAY); } - + public Response objectIdletime(String key) { - getClient(key).objectIdletime(key); - return getResponse(BuilderFactory.LONG); + getClient(key).objectIdletime(key); + return getResponse(BuilderFactory.LONG); } - + public Response objectIdletime(byte[] key) { - getClient(key).objectIdletime(key); - return getResponse(BuilderFactory.LONG); + getClient(key).objectIdletime(key); + return getResponse(BuilderFactory.LONG); } - + public Response pexpire(String key, int milliseconds) { - getClient(key).pexpire(key, milliseconds); - return getResponse(BuilderFactory.LONG); + getClient(key).pexpire(key, milliseconds); + return getResponse(BuilderFactory.LONG); } - + public Response pexpire(byte[] key, int milliseconds) { - getClient(key).pexpire(key, milliseconds); - return getResponse(BuilderFactory.LONG); + getClient(key).pexpire(key, milliseconds); + return getResponse(BuilderFactory.LONG); } - + public Response pexpireAt(String key, long millisecondsTimestamp) { - getClient(key).pexpireAt(key, millisecondsTimestamp); - return getResponse(BuilderFactory.LONG); + getClient(key).pexpireAt(key, millisecondsTimestamp); + return getResponse(BuilderFactory.LONG); } - + public Response pexpireAt(byte[] key, long millisecondsTimestamp) { - getClient(key).pexpireAt(key, millisecondsTimestamp); - return getResponse(BuilderFactory.LONG); + getClient(key).pexpireAt(key, millisecondsTimestamp); + return getResponse(BuilderFactory.LONG); } - + public Response pttl(String key) { - getClient(key).pttl(key); - return getResponse(BuilderFactory.LONG); + getClient(key).pttl(key); + return getResponse(BuilderFactory.LONG); } - + public Response pttl(byte[] key) { - getClient(key).pttl(key); - return getResponse(BuilderFactory.LONG); + getClient(key).pttl(key); + return getResponse(BuilderFactory.LONG); } - + public Response restore(String key, int ttl, byte[] serializedValue) { - getClient(key).restore(key, ttl, serializedValue); - return getResponse(BuilderFactory.STRING); + getClient(key).restore(key, ttl, serializedValue); + return getResponse(BuilderFactory.STRING); } - + public Response restore(byte[] key, int ttl, byte[] serializedValue) { - getClient(key).restore(key, ttl, serializedValue); - return getResponse(BuilderFactory.STRING); + getClient(key).restore(key, ttl, serializedValue); + return getResponse(BuilderFactory.STRING); } - + public Response incrByFloat(String key, double increment) { - getClient(key).incrByFloat(key, increment); - return getResponse(BuilderFactory.DOUBLE); + getClient(key).incrByFloat(key, increment); + return getResponse(BuilderFactory.DOUBLE); } - + public Response incrByFloat(byte[] key, double increment) { - getClient(key).incrByFloat(key, increment); - return getResponse(BuilderFactory.DOUBLE); + getClient(key).incrByFloat(key, increment); + return getResponse(BuilderFactory.DOUBLE); } - + public Response psetex(String key, int milliseconds, String value) { - getClient(key).psetex(key, milliseconds, value); - return getResponse(BuilderFactory.STRING); + getClient(key).psetex(key, milliseconds, value); + return getResponse(BuilderFactory.STRING); } - + public Response psetex(byte[] key, int milliseconds, byte[] value) { - getClient(key).psetex(key, milliseconds, value); - return getResponse(BuilderFactory.STRING); + getClient(key).psetex(key, milliseconds, value); + return getResponse(BuilderFactory.STRING); } - + public Response set(String key, String value, String nxxx) { - getClient(key).set(key, value, nxxx); - return getResponse(BuilderFactory.STRING); + getClient(key).set(key, value, nxxx); + return getResponse(BuilderFactory.STRING); } - + public Response set(byte[] key, byte[] value, byte[] nxxx) { - getClient(key).set(key, value, nxxx); - return getResponse(BuilderFactory.STRING); + getClient(key).set(key, value, nxxx); + return getResponse(BuilderFactory.STRING); } - - public Response set(String key, String value, String nxxx, String expx, int time) { - getClient(key).set(key, value, nxxx, expx, time); - return getResponse(BuilderFactory.STRING); + + public Response set(String key, String value, String nxxx, + String expx, int time) { + getClient(key).set(key, value, nxxx, expx, time); + return getResponse(BuilderFactory.STRING); } - - public Response set(byte[] key, byte[] value, byte[] nxxx, byte[] expx, int time) { - getClient(key).set(key, value, nxxx, expx, time); - return getResponse(BuilderFactory.STRING); + + public Response set(byte[] key, byte[] value, byte[] nxxx, + byte[] expx, int time) { + getClient(key).set(key, value, nxxx, expx, time); + return getResponse(BuilderFactory.STRING); } - - public Response hincrByFloat(String key, String field, double increment) { - getClient(key).hincrByFloat(key, field, increment); - return getResponse(BuilderFactory.DOUBLE); + + public Response hincrByFloat(String key, String field, + double increment) { + getClient(key).hincrByFloat(key, field, increment); + return getResponse(BuilderFactory.DOUBLE); } - - public Response hincrByFloat(byte[] key, byte[] field, double increment) { - getClient(key).hincrByFloat(key, field, increment); - return getResponse(BuilderFactory.DOUBLE); + + public Response hincrByFloat(byte[] key, byte[] field, + double increment) { + getClient(key).hincrByFloat(key, field, increment); + return getResponse(BuilderFactory.DOUBLE); } public Response eval(String script) { - return this.eval(script, 0, new String[0]); + return this.eval(script, 0, new String[0]); } - - public Response eval(String script, List keys, List args) { - String[] argv = Jedis.getParams(keys, args); - return this.eval(script, keys.size(), argv); + + public Response eval(String script, List keys, + List args) { + String[] argv = Jedis.getParams(keys, args); + return this.eval(script, keys.size(), argv); } - + public Response eval(String script, int numKeys, String[] argv) { - getClient(script).eval(script, numKeys, argv); - return getResponse(BuilderFactory.STRING); + getClient(script).eval(script, numKeys, argv); + return getResponse(BuilderFactory.STRING); } - + public Response evalsha(String script) { - return this.evalsha(script, 0, new String[0]); + return this.evalsha(script, 0, new String[0]); } - - public Response evalsha(String sha1, List keys, List args) { - String[] argv = Jedis.getParams(keys, args); - return this.evalsha(sha1, keys.size(), argv); + + public Response evalsha(String sha1, List keys, + List args) { + String[] argv = Jedis.getParams(keys, args); + return this.evalsha(sha1, keys.size(), argv); } - + public Response evalsha(String sha1, int numKeys, String[] argv) { - getClient(sha1).evalsha(sha1, numKeys, argv); - return getResponse(BuilderFactory.STRING); + getClient(sha1).evalsha(sha1, numKeys, argv); + return getResponse(BuilderFactory.STRING); } - - + } diff --git a/src/main/java/redis/clients/jedis/PipelineBlock.java b/src/main/java/redis/clients/jedis/PipelineBlock.java index 9afc391..9cf2f7e 100644 --- a/src/main/java/redis/clients/jedis/PipelineBlock.java +++ b/src/main/java/redis/clients/jedis/PipelineBlock.java @@ -1,6 +1,5 @@ package redis.clients.jedis; - public abstract class PipelineBlock extends Pipeline { public abstract void execute(); } diff --git a/src/main/java/redis/clients/jedis/Protocol.java b/src/main/java/redis/clients/jedis/Protocol.java index a5e08c6..2ba157c 100644 --- a/src/main/java/redis/clients/jedis/Protocol.java +++ b/src/main/java/redis/clients/jedis/Protocol.java @@ -16,7 +16,7 @@ public final class Protocol { private static final String ASK_RESPONSE = "ASK"; private static final String MOVED_RESPONSE = "MOVED"; - public static final int DEFAULT_PORT = 6379; + public static final int DEFAULT_PORT = 6379; public static final int DEFAULT_SENTINEL_PORT = 26379; public static final int DEFAULT_TIMEOUT = 2000; public static final int DEFAULT_DATABASE = 0; @@ -44,7 +44,7 @@ public final class Protocol { public static final String CLUSTER_SETSLOT_NODE = "node"; public static final String CLUSTER_SETSLOT_MIGRATING = "migrating"; public static final String CLUSTER_SETSLOT_IMPORTING = "importing"; - + private Protocol() { // this prevent the class from instantiation } @@ -76,27 +76,32 @@ public final class Protocol { } private static void processError(final RedisInputStream is) { - String message = is.readLine(); - //TODO: I'm not sure if this is the best way to do this. - //Maybe Read only first 5 bytes instead? - if (message.startsWith(MOVED_RESPONSE)) { - String[] movedInfo = parseTargetHostAndSlot(message); - throw new JedisMovedDataException(message, new HostAndPort(movedInfo[1], Integer.valueOf(movedInfo[2])), Integer.valueOf(movedInfo[0])); - } else if (message.startsWith(ASK_RESPONSE)) { - String[] askInfo = parseTargetHostAndSlot(message); - throw new JedisAskDataException(message, new HostAndPort(askInfo[1], Integer.valueOf(askInfo[2])), Integer.valueOf(askInfo[0])); - } - throw new JedisDataException(message); + String message = is.readLine(); + // TODO: I'm not sure if this is the best way to do this. + // Maybe Read only first 5 bytes instead? + if (message.startsWith(MOVED_RESPONSE)) { + String[] movedInfo = parseTargetHostAndSlot(message); + throw new JedisMovedDataException(message, new HostAndPort( + movedInfo[1], Integer.valueOf(movedInfo[2])), + Integer.valueOf(movedInfo[0])); + } else if (message.startsWith(ASK_RESPONSE)) { + String[] askInfo = parseTargetHostAndSlot(message); + throw new JedisAskDataException(message, new HostAndPort( + askInfo[1], Integer.valueOf(askInfo[2])), + Integer.valueOf(askInfo[0])); + } + throw new JedisDataException(message); } - - private static String[] parseTargetHostAndSlot(String clusterRedirectResponse) { - String[] response = new String[3]; - String[] messageInfo = clusterRedirectResponse.split(" "); - String[] targetHostAndPort = messageInfo[2].split(":"); - response[0] = messageInfo[1]; - response[1] = targetHostAndPort[0]; - response[2] = targetHostAndPort[1]; - return response; + + private static String[] parseTargetHostAndSlot( + String clusterRedirectResponse) { + String[] response = new String[3]; + String[] messageInfo = clusterRedirectResponse.split(" "); + String[] targetHostAndPort = messageInfo[2].split(":"); + response[0] = messageInfo[1]; + response[1] = targetHostAndPort[0]; + response[2] = targetHostAndPort[1]; + return response; } private static Object process(final RedisInputStream is) { @@ -134,10 +139,11 @@ public final class Protocol { int offset = 0; try { while (offset < len) { - int size = is.read(read, offset, (len - offset)); - if (size == -1) - throw new JedisConnectionException("It seems like server has closed the connection."); - offset += size; + int size = is.read(read, offset, (len - offset)); + if (size == -1) + throw new JedisConnectionException( + "It seems like server has closed the connection."); + offset += size; } // read 2 more bytes for the command delimiter is.readByte(); @@ -175,7 +181,7 @@ public final class Protocol { } 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) { @@ -201,8 +207,7 @@ public final class Protocol { } public static enum Keyword { - AGGREGATE, ALPHA, ASC, BY, DESC, GET, LIMIT, MESSAGE, NO, NOSORT, PMESSAGE, PSUBSCRIBE, PUNSUBSCRIBE, OK, ONE, QUEUED, SET, STORE, SUBSCRIBE, UNSUBSCRIBE, WEIGHTS, WITHSCORES, RESETSTAT, RESET, FLUSH, EXISTS, LOAD, KILL, LEN, REFCOUNT, ENCODING, IDLETIME, AND, OR, XOR, NOT, - GETNAME, SETNAME,LIST, MATCH, COUNT; + AGGREGATE, ALPHA, ASC, BY, DESC, GET, LIMIT, MESSAGE, NO, NOSORT, PMESSAGE, PSUBSCRIBE, PUNSUBSCRIBE, OK, ONE, QUEUED, SET, STORE, SUBSCRIBE, UNSUBSCRIBE, WEIGHTS, WITHSCORES, RESETSTAT, RESET, FLUSH, EXISTS, LOAD, KILL, LEN, REFCOUNT, ENCODING, IDLETIME, AND, OR, XOR, NOT, GETNAME, SETNAME, LIST, MATCH, COUNT; public final byte[] raw; Keyword() { diff --git a/src/main/java/redis/clients/jedis/Queable.java b/src/main/java/redis/clients/jedis/Queable.java index b8ff0e5..769bf16 100644 --- a/src/main/java/redis/clients/jedis/Queable.java +++ b/src/main/java/redis/clients/jedis/Queable.java @@ -7,21 +7,21 @@ public class Queable { private Queue> pipelinedResponses = new LinkedList>(); protected void clean() { - pipelinedResponses.clear(); + pipelinedResponses.clear(); } protected Response generateResponse(Object data) { - Response response = pipelinedResponses.poll(); - if (response != null) { - response.set(data); - } - return response; + Response response = pipelinedResponses.poll(); + if (response != null) { + response.set(data); + } + return response; } protected Response getResponse(Builder builder) { - Response lr = new Response(builder); - pipelinedResponses.add(lr); - return lr; + Response lr = new Response(builder); + pipelinedResponses.add(lr); + return lr; } } diff --git a/src/main/java/redis/clients/jedis/RedisPipeline.java b/src/main/java/redis/clients/jedis/RedisPipeline.java index ff9e862..bb5226c 100644 --- a/src/main/java/redis/clients/jedis/RedisPipeline.java +++ b/src/main/java/redis/clients/jedis/RedisPipeline.java @@ -32,10 +32,7 @@ public interface RedisPipeline { Response getbit(String key, long offset); - - - Response getrange(String key, long startOffset, - long endOffset); + Response getrange(String key, long startOffset, long endOffset); Response getSet(String key, String value); @@ -70,7 +67,7 @@ public interface RedisPipeline { Response lindex(String key, long index); Response linsert(String key, BinaryClient.LIST_POSITION where, - String pivot, String value); + String pivot, String value); Response llen(String key); @@ -118,8 +115,7 @@ public interface RedisPipeline { Response> sort(String key); - Response> sort(String key, - SortingParams sortingParameters); + Response> sort(String key, SortingParams sortingParameters); Response spop(String key); @@ -145,35 +141,31 @@ public interface RedisPipeline { Response> zrange(String key, long start, long end); - Response> zrangeByScore(String key, double min, - double max); + Response> zrangeByScore(String key, double min, double max); - Response> zrangeByScore(String key, String min, - String max); + Response> zrangeByScore(String key, String min, String max); - Response> zrangeByScore(String key, double min, - double max, int offset, int count); + Response> zrangeByScore(String key, double min, double max, + int offset, int count); Response> zrangeByScoreWithScores(String key, double min, - double max); + double max); Response> zrangeByScoreWithScores(String key, double min, - double max, int offset, int count); + double max, int offset, int count); - Response> zrevrangeByScore(String key, double max, - double min); + Response> zrevrangeByScore(String key, double max, double min); - Response> zrevrangeByScore(String key, String max, - String min); + Response> zrevrangeByScore(String key, String max, String min); - Response> zrevrangeByScore(String key, double max, - double min, int offset, int count); + Response> zrevrangeByScore(String key, double max, double min, + int offset, int count); - Response> zrevrangeByScoreWithScores(String key, - double max, double min); + Response> zrevrangeByScoreWithScores(String key, double max, + double min); - Response> zrevrangeByScoreWithScores(String key, - double max, double min, int offset, int count); + Response> zrevrangeByScoreWithScores(String key, double max, + double min, int offset, int count); Response> zrangeWithScores(String key, long start, long end); @@ -187,8 +179,7 @@ public interface RedisPipeline { Response> zrevrange(String key, long start, long end); - Response> zrevrangeWithScores(String key, long start, - long end); + Response> zrevrangeWithScores(String key, long start, long end); Response zrevrank(String key, String member); diff --git a/src/main/java/redis/clients/jedis/Response.java b/src/main/java/redis/clients/jedis/Response.java index 058985f..b17f314 100644 --- a/src/main/java/redis/clients/jedis/Response.java +++ b/src/main/java/redis/clients/jedis/Response.java @@ -10,34 +10,34 @@ public class Response { private Object data; public Response(Builder b) { - this.builder = b; + this.builder = b; } public void set(Object data) { - this.data = data; - set = true; + this.data = data; + set = true; } public T get() { - if (!set) { - throw new JedisDataException( - "Please close pipeline or multi block before calling this method."); - } - if (!built) { - if(data != null ){ - if (data instanceof JedisDataException){ - throw new JedisDataException((JedisDataException)data); - } - response = builder.build(data); - } - this.data = null; - built = true; - } - return response; + if (!set) { + throw new JedisDataException( + "Please close pipeline or multi block before calling this method."); + } + if (!built) { + if (data != null) { + if (data instanceof JedisDataException) { + throw new JedisDataException((JedisDataException) data); + } + response = builder.build(data); + } + this.data = null; + built = true; + } + return response; } public String toString() { - return "Response " + builder.toString(); + return "Response " + builder.toString(); } } diff --git a/src/main/java/redis/clients/jedis/ShardedJedis.java b/src/main/java/redis/clients/jedis/ShardedJedis.java index f3d2f72..02c0e4c 100644 --- a/src/main/java/redis/clients/jedis/ShardedJedis.java +++ b/src/main/java/redis/clients/jedis/ShardedJedis.java @@ -1,14 +1,14 @@ package redis.clients.jedis; -import redis.clients.jedis.BinaryClient.LIST_POSITION; -import redis.clients.util.Hashing; - import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Pattern; +import redis.clients.jedis.BinaryClient.LIST_POSITION; +import redis.clients.util.Hashing; + public class ShardedJedis extends BinaryShardedJedis implements JedisCommands { public ShardedJedis(List shards) { super(shards); @@ -38,8 +38,8 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands { } public String echo(String string) { - Jedis j = getShard(string); - return j.echo(string); + Jedis j = getShard(string); + return j.echo(string); } public Boolean exists(String key) { @@ -73,8 +73,8 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands { } public Boolean setbit(String key, long offset, String value) { - Jedis j = getShard(key); - return j.setbit(key, offset, value); + Jedis j = getShard(key); + return j.setbit(key, offset, value); } public Boolean getbit(String key, long offset) { @@ -108,13 +108,13 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands { } public List blpop(String arg) { - Jedis j = getShard(arg); - return j.blpop(arg); + Jedis j = getShard(arg); + return j.blpop(arg); } public List brpop(String arg) { - Jedis j = getShard(arg); - return j.brpop(arg); + Jedis j = getShard(arg); + return j.brpop(arg); } public Long decrBy(String key, long integer) { @@ -228,13 +228,13 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands { } public Long strlen(final String key) { - Jedis j = getShard(key); - return j.strlen(key); + Jedis j = getShard(key); + return j.strlen(key); } public Long move(String key, int dbIndex) { - Jedis j = getShard(key); - return j.move(key, dbIndex); + Jedis j = getShard(key); + return j.move(key, dbIndex); } public Long rpushx(String key, String... string) { @@ -243,8 +243,8 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands { } public Long persist(final String key) { - Jedis j = getShard(key); - return j.persist(key); + Jedis j = getShard(key); + return j.persist(key); } public Long llen(String key) { @@ -326,10 +326,10 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands { Jedis j = getShard(key); return j.zadd(key, score, member); } - + public Long zadd(String key, Map scoreMembers) { - Jedis j = getShard(key); - return j.zadd(key, scoreMembers); + Jedis j = getShard(key); + return j.zadd(key, scoreMembers); } public Set zrange(String key, long start, long end) { @@ -527,12 +527,12 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands { Jedis j = getShard(key); return j.hscan(key, cursor); } - + public ScanResult sscan(String key, int cursor) { Jedis j = getShard(key); return j.sscan(key, cursor); } - + public ScanResult zscan(String key, int cursor) { Jedis j = getShard(key); return j.zscan(key, cursor); diff --git a/src/main/java/redis/clients/jedis/ShardedJedisPipeline.java b/src/main/java/redis/clients/jedis/ShardedJedisPipeline.java index be6db92..6b68e95 100644 --- a/src/main/java/redis/clients/jedis/ShardedJedisPipeline.java +++ b/src/main/java/redis/clients/jedis/ShardedJedisPipeline.java @@ -11,27 +11,27 @@ public class ShardedJedisPipeline extends PipelineBase { private Queue clients = new LinkedList(); private static class FutureResult { - private Client client; + private Client client; - public FutureResult(Client client) { - this.client = client; - } + public FutureResult(Client client) { + this.client = client; + } - public Object get() { - return client.getOne(); - } + public Object get() { + return client.getOne(); + } } public void setShardedJedis(BinaryShardedJedis jedis) { - this.jedis = jedis; + this.jedis = jedis; } public List getResults() { - List r = new ArrayList(); - for (FutureResult fr : results) { - r.add(fr.get()); - } - return r; + List r = new ArrayList(); + for (FutureResult fr : results) { + r.add(fr.get()); + } + return r; } /** @@ -40,30 +40,30 @@ public class ShardedJedisPipeline extends PipelineBase { * the different Response<?> of the commands you execute. */ public void sync() { - for (Client client : clients) { - generateResponse(client.getOne()); - } + for (Client client : clients) { + generateResponse(client.getOne()); + } } /** * Syncronize pipeline by reading all responses. This operation closes the * pipeline. Whenever possible try to avoid using this version and use - * ShardedJedisPipeline.sync() as it won't go through all the responses and generate the - * right response type (usually it is a waste of time). - * + * ShardedJedisPipeline.sync() as it won't go through all the responses and + * generate the right response type (usually it is a waste of time). + * * @return A list of all the responses in the order you executed them. */ public List syncAndReturnAll() { - List formatted = new ArrayList(); - for (Client client : clients) { - formatted.add(generateResponse(client.getOne()).get()); - } - return formatted; + List formatted = new ArrayList(); + for (Client client : clients) { + formatted.add(generateResponse(client.getOne()).get()); + } + return formatted; } /** - * This method will be removed in Jedis 3.0. Use the methods that return Response's and call - * sync(). + * This method will be removed in Jedis 3.0. Use the methods that return + * Response's and call sync(). */ @Deprecated public void execute() { @@ -71,17 +71,17 @@ public class ShardedJedisPipeline extends PipelineBase { @Override protected Client getClient(String key) { - Client client = jedis.getShard(key).getClient(); - clients.add(client); - results.add(new FutureResult(client)); - return client; + Client client = jedis.getShard(key).getClient(); + clients.add(client); + results.add(new FutureResult(client)); + return client; } @Override protected Client getClient(byte[] key) { - Client client = jedis.getShard(key).getClient(); - clients.add(client); - results.add(new FutureResult(client)); - return client; + Client client = jedis.getShard(key).getClient(); + clients.add(client); + results.add(new FutureResult(client)); + return client; } } \ No newline at end of file diff --git a/src/main/java/redis/clients/jedis/SortingParams.java b/src/main/java/redis/clients/jedis/SortingParams.java index cfdf03b..ea0bee8 100644 --- a/src/main/java/redis/clients/jedis/SortingParams.java +++ b/src/main/java/redis/clients/jedis/SortingParams.java @@ -36,7 +36,7 @@ public class SortingParams { * @return the SortingParams Object */ public SortingParams by(final String pattern) { - return by(SafeEncoder.encode(pattern)); + return by(SafeEncoder.encode(pattern)); } /** @@ -53,9 +53,9 @@ public class SortingParams { * @return the SortingParams Object */ public SortingParams by(final byte[] pattern) { - params.add(BY.raw); - params.add(pattern); - return this; + params.add(BY.raw); + params.add(pattern); + return this; } /** @@ -67,13 +67,13 @@ public class SortingParams { * @return the SortingParams Object */ public SortingParams nosort() { - params.add(BY.raw); - params.add(NOSORT.raw); - return this; + params.add(BY.raw); + params.add(NOSORT.raw); + return this; } public Collection getParams() { - return Collections.unmodifiableCollection(params); + return Collections.unmodifiableCollection(params); } /** @@ -82,8 +82,8 @@ public class SortingParams { * @return the sortingParams Object */ public SortingParams desc() { - params.add(DESC.raw); - return this; + params.add(DESC.raw); + return this; } /** @@ -92,8 +92,8 @@ public class SortingParams { * @return the SortingParams Object */ public SortingParams asc() { - params.add(ASC.raw); - return this; + params.add(ASC.raw); + return this; } /** @@ -105,10 +105,10 @@ public class SortingParams { * @return the SortingParams Object */ public SortingParams limit(final int start, final int count) { - params.add(LIMIT.raw); - params.add(Protocol.toByteArray(start)); - params.add(Protocol.toByteArray(count)); - return this; + params.add(LIMIT.raw); + params.add(Protocol.toByteArray(start)); + params.add(Protocol.toByteArray(count)); + return this; } /** @@ -118,8 +118,8 @@ public class SortingParams { * @return the SortingParams Object */ public SortingParams alpha() { - params.add(ALPHA.raw); - return this; + params.add(ALPHA.raw); + return this; } /** @@ -138,11 +138,11 @@ public class SortingParams { * @return the SortingParams Object */ public SortingParams get(String... patterns) { - for (final String pattern : patterns) { - params.add(GET.raw); - params.add(SafeEncoder.encode(pattern)); - } - return this; + for (final String pattern : patterns) { + params.add(GET.raw); + params.add(SafeEncoder.encode(pattern)); + } + return this; } /** @@ -161,10 +161,10 @@ public class SortingParams { * @return the SortingParams Object */ public SortingParams get(byte[]... patterns) { - for (final byte[] pattern : patterns) { - params.add(GET.raw); - params.add(pattern); - } - return this; + for (final byte[] pattern : patterns) { + params.add(GET.raw); + params.add(pattern); + } + return this; } } \ No newline at end of file diff --git a/src/main/java/redis/clients/jedis/Transaction.java b/src/main/java/redis/clients/jedis/Transaction.java index 949f541..69d50d2 100644 --- a/src/main/java/redis/clients/jedis/Transaction.java +++ b/src/main/java/redis/clients/jedis/Transaction.java @@ -6,70 +6,71 @@ import java.util.List; import redis.clients.jedis.exceptions.JedisDataException; /** - * Transaction is nearly identical to Pipeline, only differences are the multi/discard behaviors + * Transaction is nearly identical to Pipeline, only differences are the + * multi/discard behaviors */ public class Transaction extends MultiKeyPipelineBase { protected boolean inTransaction = true; - protected Transaction(){ - // client will be set later in transaction block + protected Transaction() { + // client will be set later in transaction block } public Transaction(final Client client) { - this.client = client; + this.client = client; } @Override protected Client getClient(String key) { - return client; + return client; } @Override protected Client getClient(byte[] key) { - return client; + return client; } public List exec() { - client.exec(); - client.getAll(1); // Discard all but the last reply + client.exec(); + client.getAll(1); // Discard all but the last reply - List unformatted = client.getObjectMultiBulkReply(); - if (unformatted == null) { - return null; - } - List formatted = new ArrayList(); - for (Object o : unformatted) { - try { - formatted.add(generateResponse(o).get()); - } catch (JedisDataException e) { - formatted.add(e); - } - } - return formatted; + List unformatted = client.getObjectMultiBulkReply(); + if (unformatted == null) { + return null; + } + List formatted = new ArrayList(); + for (Object o : unformatted) { + try { + formatted.add(generateResponse(o).get()); + } catch (JedisDataException e) { + formatted.add(e); + } + } + return formatted; } public List> execGetResponse() { - client.exec(); - client.getAll(1); // Discard all but the last reply + client.exec(); + client.getAll(1); // Discard all but the last reply - List unformatted = client.getObjectMultiBulkReply(); - if (unformatted == null) { - return null; - } - List> response = new ArrayList>(); - for (Object o : unformatted) { - response.add(generateResponse(o)); - } - return response; + List unformatted = client.getObjectMultiBulkReply(); + if (unformatted == null) { + return null; + } + List> response = new ArrayList>(); + for (Object o : unformatted) { + response.add(generateResponse(o)); + } + return response; } public String discard() { - client.discard(); - client.getAll(1); // Discard all but the last reply - inTransaction = false; - clean(); - return client.getStatusCodeReply(); + client.discard(); + client.getAll(1); // Discard all but the last reply + inTransaction = false; + clean(); + return client.getStatusCodeReply(); } } \ No newline at end of file diff --git a/src/main/java/redis/clients/jedis/TransactionBlock.java b/src/main/java/redis/clients/jedis/TransactionBlock.java index e784e19..87df232 100644 --- a/src/main/java/redis/clients/jedis/TransactionBlock.java +++ b/src/main/java/redis/clients/jedis/TransactionBlock.java @@ -13,6 +13,6 @@ public abstract class TransactionBlock extends Transaction { public abstract void execute() throws JedisException; public void setClient(Client client) { - this.client = client; + this.client = client; } } diff --git a/src/main/java/redis/clients/jedis/Tuple.java b/src/main/java/redis/clients/jedis/Tuple.java index 211a9e9..ad8d001 100644 --- a/src/main/java/redis/clients/jedis/Tuple.java +++ b/src/main/java/redis/clients/jedis/Tuple.java @@ -9,72 +9,72 @@ public class Tuple implements Comparable { private Double score; public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result; - if (null != element) { - for (final byte b : element) { - result = prime * result + b; - } - } - long temp; - temp = Double.doubleToLongBits(score); - result = prime * result + (int) (temp ^ (temp >>> 32)); - return result; + final int prime = 31; + int result = 1; + result = prime * result; + if (null != element) { + for (final byte b : element) { + result = prime * result + b; + } + } + long temp; + temp = Double.doubleToLongBits(score); + result = prime * result + (int) (temp ^ (temp >>> 32)); + return result; } public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Tuple other = (Tuple) obj; - if (element == null) { - if (other.element != null) - return false; - } else if (!Arrays.equals(element, other.element)) - return false; - return true; + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Tuple other = (Tuple) obj; + if (element == null) { + if (other.element != null) + return false; + } else if (!Arrays.equals(element, other.element)) + return false; + return true; } public int compareTo(Tuple other) { - if (Arrays.equals(this.element, other.element)) - return 0; - else - return this.score < other.getScore() ? -1 : 1; + if (Arrays.equals(this.element, other.element)) + return 0; + else + return this.score < other.getScore() ? -1 : 1; } public Tuple(String element, Double score) { - super(); - this.element = SafeEncoder.encode(element); - this.score = score; + super(); + this.element = SafeEncoder.encode(element); + this.score = score; } public Tuple(byte[] element, Double score) { - super(); - this.element = element; - this.score = score; + super(); + this.element = element; + this.score = score; } public String getElement() { - if (null != element) { - return SafeEncoder.encode(element); - } else { - return null; - } + if (null != element) { + return SafeEncoder.encode(element); + } else { + return null; + } } public byte[] getBinaryElement() { - return element; + return element; } public double getScore() { - return score; + return score; } public String toString() { - return '[' + Arrays.toString(element) + ',' + score + ']'; + return '[' + Arrays.toString(element) + ',' + score + ']'; } } \ No newline at end of file diff --git a/src/main/java/redis/clients/jedis/ZParams.java b/src/main/java/redis/clients/jedis/ZParams.java index daa6f8e..7b585f3 100644 --- a/src/main/java/redis/clients/jedis/ZParams.java +++ b/src/main/java/redis/clients/jedis/ZParams.java @@ -12,33 +12,33 @@ import redis.clients.util.SafeEncoder; public class ZParams { public enum Aggregate { - SUM, MIN, MAX; + SUM, MIN, MAX; - public final byte[] raw; + public final byte[] raw; - Aggregate() { - raw = SafeEncoder.encode(name()); - } + Aggregate() { + raw = SafeEncoder.encode(name()); + } } private List params = new ArrayList(); public ZParams weights(final int... weights) { - params.add(WEIGHTS.raw); - for (final int weight : weights) { - params.add(Protocol.toByteArray(weight)); - } + params.add(WEIGHTS.raw); + for (final int weight : weights) { + params.add(Protocol.toByteArray(weight)); + } - return this; + return this; } public Collection getParams() { - return Collections.unmodifiableCollection(params); + return Collections.unmodifiableCollection(params); } public ZParams aggregate(final Aggregate aggregate) { - params.add(AGGREGATE.raw); - params.add(aggregate.raw); - return this; + params.add(AGGREGATE.raw); + params.add(aggregate.raw); + return this; } } diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisAskDataException.java b/src/main/java/redis/clients/jedis/exceptions/JedisAskDataException.java index 599a779..0544109 100644 --- a/src/main/java/redis/clients/jedis/exceptions/JedisAskDataException.java +++ b/src/main/java/redis/clients/jedis/exceptions/JedisAskDataException.java @@ -4,17 +4,20 @@ import redis.clients.jedis.HostAndPort; public class JedisAskDataException extends JedisRedirectionException { private static final long serialVersionUID = 3878126572474819403L; - - public JedisAskDataException(Throwable cause, HostAndPort targetHost, int slot) { - super(cause, targetHost, slot); + + public JedisAskDataException(Throwable cause, HostAndPort targetHost, + int slot) { + super(cause, targetHost, slot); } - public JedisAskDataException(String message, Throwable cause, HostAndPort targetHost, int slot) { - super(message, cause, targetHost, slot); + public JedisAskDataException(String message, Throwable cause, + HostAndPort targetHost, int slot) { + super(message, cause, targetHost, slot); } - public JedisAskDataException(String message, HostAndPort targetHost, int slot) { - super(message, targetHost, slot); - } + public JedisAskDataException(String message, HostAndPort targetHost, + int slot) { + super(message, targetHost, slot); + } } diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisClusterException.java b/src/main/java/redis/clients/jedis/exceptions/JedisClusterException.java index e20d5a7..7e93b26 100644 --- a/src/main/java/redis/clients/jedis/exceptions/JedisClusterException.java +++ b/src/main/java/redis/clients/jedis/exceptions/JedisClusterException.java @@ -1,18 +1,17 @@ package redis.clients.jedis.exceptions; - public class JedisClusterException extends JedisDataException { private static final long serialVersionUID = 3878126572474819403L; - + public JedisClusterException(Throwable cause) { - super(cause); + super(cause); } public JedisClusterException(String message, Throwable cause) { - super(message, cause); + super(message, cause); } - public JedisClusterException(String message) { - super(message); - } + public JedisClusterException(String message) { + super(message); + } } diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisClusterMaxRedirectionsException.java b/src/main/java/redis/clients/jedis/exceptions/JedisClusterMaxRedirectionsException.java index 519188b..29c289b 100644 --- a/src/main/java/redis/clients/jedis/exceptions/JedisClusterMaxRedirectionsException.java +++ b/src/main/java/redis/clients/jedis/exceptions/JedisClusterMaxRedirectionsException.java @@ -1,18 +1,17 @@ package redis.clients.jedis.exceptions; - public class JedisClusterMaxRedirectionsException extends JedisDataException { private static final long serialVersionUID = 3878126572474819403L; - + public JedisClusterMaxRedirectionsException(Throwable cause) { - super(cause); + super(cause); } public JedisClusterMaxRedirectionsException(String message, Throwable cause) { - super(message, cause); + super(message, cause); } - public JedisClusterMaxRedirectionsException(String message) { - super(message); - } + public JedisClusterMaxRedirectionsException(String message) { + super(message); + } } diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisConnectionException.java b/src/main/java/redis/clients/jedis/exceptions/JedisConnectionException.java index 6e25718..f20c53a 100644 --- a/src/main/java/redis/clients/jedis/exceptions/JedisConnectionException.java +++ b/src/main/java/redis/clients/jedis/exceptions/JedisConnectionException.java @@ -4,14 +4,14 @@ public class JedisConnectionException extends JedisException { private static final long serialVersionUID = 3878126572474819403L; public JedisConnectionException(String message) { - super(message); + super(message); } public JedisConnectionException(Throwable cause) { - super(cause); + super(cause); } public JedisConnectionException(String message, Throwable cause) { - super(message, cause); + super(message, cause); } } diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisDataException.java b/src/main/java/redis/clients/jedis/exceptions/JedisDataException.java index 1a7de9b..9872377 100644 --- a/src/main/java/redis/clients/jedis/exceptions/JedisDataException.java +++ b/src/main/java/redis/clients/jedis/exceptions/JedisDataException.java @@ -4,14 +4,14 @@ public class JedisDataException extends JedisException { private static final long serialVersionUID = 3878126572474819403L; public JedisDataException(String message) { - super(message); + super(message); } public JedisDataException(Throwable cause) { - super(cause); + super(cause); } public JedisDataException(String message, Throwable cause) { - super(message, cause); + super(message, cause); } } diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisException.java b/src/main/java/redis/clients/jedis/exceptions/JedisException.java index f983bf6..f4abb71 100644 --- a/src/main/java/redis/clients/jedis/exceptions/JedisException.java +++ b/src/main/java/redis/clients/jedis/exceptions/JedisException.java @@ -1,18 +1,17 @@ package redis.clients.jedis.exceptions; - public class JedisException extends RuntimeException { private static final long serialVersionUID = -2946266495682282677L; public JedisException(String message) { - super(message); + super(message); } public JedisException(Throwable e) { - super(e); + super(e); } public JedisException(String message, Throwable cause) { - super(message, cause); + super(message, cause); } } diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisMovedDataException.java b/src/main/java/redis/clients/jedis/exceptions/JedisMovedDataException.java index c7a0873..123f5e3 100644 --- a/src/main/java/redis/clients/jedis/exceptions/JedisMovedDataException.java +++ b/src/main/java/redis/clients/jedis/exceptions/JedisMovedDataException.java @@ -2,20 +2,21 @@ package redis.clients.jedis.exceptions; import redis.clients.jedis.HostAndPort; - public class JedisMovedDataException extends JedisRedirectionException { private static final long serialVersionUID = 3878126572474819403L; - - public JedisMovedDataException(String message, HostAndPort targetNode, int slot) { - super(message, targetNode, slot); + public JedisMovedDataException(String message, HostAndPort targetNode, + int slot) { + super(message, targetNode, slot); } - public JedisMovedDataException(Throwable cause, HostAndPort targetNode, int slot) { - super(cause, targetNode, slot); + public JedisMovedDataException(Throwable cause, HostAndPort targetNode, + int slot) { + super(cause, targetNode, slot); } - public JedisMovedDataException(String message, Throwable cause, HostAndPort targetNode, int slot) { - super(message, cause, targetNode, slot); + public JedisMovedDataException(String message, Throwable cause, + HostAndPort targetNode, int slot) { + super(message, cause, targetNode, slot); } } diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisRedirectionException.java b/src/main/java/redis/clients/jedis/exceptions/JedisRedirectionException.java index 65969f3..ab96287 100644 --- a/src/main/java/redis/clients/jedis/exceptions/JedisRedirectionException.java +++ b/src/main/java/redis/clients/jedis/exceptions/JedisRedirectionException.java @@ -2,36 +2,38 @@ package redis.clients.jedis.exceptions; import redis.clients.jedis.HostAndPort; - public class JedisRedirectionException extends JedisDataException { private static final long serialVersionUID = 3878126572474819403L; - + private HostAndPort targetNode; private int slot; - public JedisRedirectionException(String message, HostAndPort targetNode, int slot) { - super(message); - this.targetNode = targetNode; - this.slot = slot; + public JedisRedirectionException(String message, HostAndPort targetNode, + int slot) { + super(message); + this.targetNode = targetNode; + this.slot = slot; } - public JedisRedirectionException(Throwable cause, HostAndPort targetNode, int slot) { - super(cause); - this.targetNode = targetNode; - this.slot = slot; + public JedisRedirectionException(Throwable cause, HostAndPort targetNode, + int slot) { + super(cause); + this.targetNode = targetNode; + this.slot = slot; } - public JedisRedirectionException(String message, Throwable cause, HostAndPort targetNode, int slot) { - super(message, cause); - this.targetNode = targetNode; - this.slot = slot; + public JedisRedirectionException(String message, Throwable cause, + HostAndPort targetNode, int slot) { + super(message, cause); + this.targetNode = targetNode; + this.slot = slot; } - public HostAndPort getTargetNode() { - return targetNode; - } + public HostAndPort getTargetNode() { + return targetNode; + } - public int getSlot() { - return slot; - } + public int getSlot() { + return slot; + } } diff --git a/src/main/java/redis/clients/util/Hashing.java b/src/main/java/redis/clients/util/Hashing.java index 1460f03..b15a199 100644 --- a/src/main/java/redis/clients/util/Hashing.java +++ b/src/main/java/redis/clients/util/Hashing.java @@ -8,28 +8,28 @@ public interface Hashing { public ThreadLocal md5Holder = new ThreadLocal(); public static final Hashing MD5 = new Hashing() { - public long hash(String key) { - return hash(SafeEncoder.encode(key)); - } + public long hash(String key) { + return hash(SafeEncoder.encode(key)); + } - public long hash(byte[] key) { - try { - if (md5Holder.get() == null) { - md5Holder.set(MessageDigest.getInstance("MD5")); - } - } catch (NoSuchAlgorithmException e) { - throw new IllegalStateException("++++ no md5 algorythm found"); - } - MessageDigest md5 = md5Holder.get(); + public long hash(byte[] key) { + try { + if (md5Holder.get() == null) { + md5Holder.set(MessageDigest.getInstance("MD5")); + } + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("++++ no md5 algorythm found"); + } + MessageDigest md5 = md5Holder.get(); - md5.reset(); - md5.update(key); - byte[] bKey = md5.digest(); - long res = ((long) (bKey[3] & 0xFF) << 24) - | ((long) (bKey[2] & 0xFF) << 16) - | ((long) (bKey[1] & 0xFF) << 8) | (long) (bKey[0] & 0xFF); - return res; - } + md5.reset(); + md5.update(key); + byte[] bKey = md5.digest(); + long res = ((long) (bKey[3] & 0xFF) << 24) + | ((long) (bKey[2] & 0xFF) << 16) + | ((long) (bKey[1] & 0xFF) << 8) | (long) (bKey[0] & 0xFF); + return res; + } }; public long hash(String key); diff --git a/src/main/java/redis/clients/util/JedisByteHashMap.java b/src/main/java/redis/clients/util/JedisByteHashMap.java index e13f3b0..cdef172 100644 --- a/src/main/java/redis/clients/util/JedisByteHashMap.java +++ b/src/main/java/redis/clients/util/JedisByteHashMap.java @@ -10,127 +10,127 @@ import java.util.Map; import java.util.Set; public class JedisByteHashMap implements Map, Cloneable, - Serializable { + Serializable { private static final long serialVersionUID = -6971431362627219416L; private Map internalMap = new HashMap(); public void clear() { - internalMap.clear(); + internalMap.clear(); } public boolean containsKey(Object key) { - if (key instanceof byte[]) - return internalMap.containsKey(new ByteArrayWrapper((byte[]) key)); - return internalMap.containsKey(key); + if (key instanceof byte[]) + return internalMap.containsKey(new ByteArrayWrapper((byte[]) key)); + return internalMap.containsKey(key); } public boolean containsValue(Object value) { - return internalMap.containsValue(value); + return internalMap.containsValue(value); } public Set> entrySet() { - Iterator> iterator = internalMap - .entrySet().iterator(); - HashSet> hashSet = new HashSet>(); - while (iterator.hasNext()) { - Entry entry = iterator.next(); - hashSet.add(new JedisByteEntry(entry.getKey().data, entry - .getValue())); - } - return hashSet; + Iterator> iterator = internalMap + .entrySet().iterator(); + HashSet> hashSet = new HashSet>(); + while (iterator.hasNext()) { + Entry entry = iterator.next(); + hashSet.add(new JedisByteEntry(entry.getKey().data, entry + .getValue())); + } + return hashSet; } public byte[] get(Object key) { - if (key instanceof byte[]) - return internalMap.get(new ByteArrayWrapper((byte[]) key)); - return internalMap.get(key); + if (key instanceof byte[]) + return internalMap.get(new ByteArrayWrapper((byte[]) key)); + return internalMap.get(key); } public boolean isEmpty() { - return internalMap.isEmpty(); + return internalMap.isEmpty(); } public Set keySet() { - Set keySet = new HashSet(); - Iterator iterator = internalMap.keySet().iterator(); - while (iterator.hasNext()) { - keySet.add(iterator.next().data); - } - return keySet; + Set keySet = new HashSet(); + Iterator iterator = internalMap.keySet().iterator(); + while (iterator.hasNext()) { + keySet.add(iterator.next().data); + } + return keySet; } public byte[] put(byte[] key, byte[] value) { - return internalMap.put(new ByteArrayWrapper(key), value); + return internalMap.put(new ByteArrayWrapper(key), value); } @SuppressWarnings("unchecked") public void putAll(Map m) { - Iterator iterator = m.entrySet().iterator(); - while (iterator.hasNext()) { - Entry next = (Entry) iterator - .next(); - internalMap.put(new ByteArrayWrapper(next.getKey()), next - .getValue()); - } + Iterator iterator = m.entrySet().iterator(); + while (iterator.hasNext()) { + Entry next = (Entry) iterator + .next(); + internalMap.put(new ByteArrayWrapper(next.getKey()), + next.getValue()); + } } public byte[] remove(Object key) { - if (key instanceof byte[]) - return internalMap.remove(new ByteArrayWrapper((byte[]) key)); - return internalMap.remove(key); + if (key instanceof byte[]) + return internalMap.remove(new ByteArrayWrapper((byte[]) key)); + return internalMap.remove(key); } public int size() { - return internalMap.size(); + return internalMap.size(); } public Collection values() { - return internalMap.values(); + return internalMap.values(); } private static final class ByteArrayWrapper { - private final byte[] data; + private final byte[] data; - public ByteArrayWrapper(byte[] data) { - if (data == null) { - throw new NullPointerException(); - } - this.data = data; - } + public ByteArrayWrapper(byte[] data) { + if (data == null) { + throw new NullPointerException(); + } + this.data = data; + } - public boolean equals(Object other) { - if (!(other instanceof ByteArrayWrapper)) { - return false; - } - return Arrays.equals(data, ((ByteArrayWrapper) other).data); - } + public boolean equals(Object other) { + if (!(other instanceof ByteArrayWrapper)) { + return false; + } + return Arrays.equals(data, ((ByteArrayWrapper) other).data); + } - public int hashCode() { - return Arrays.hashCode(data); - } + public int hashCode() { + return Arrays.hashCode(data); + } } private static final class JedisByteEntry implements Entry { - private byte[] value; - private byte[] key; + private byte[] value; + private byte[] key; - public JedisByteEntry(byte[] key, byte[] value) { - this.key = key; - this.value = value; - } + public JedisByteEntry(byte[] key, byte[] value) { + this.key = key; + this.value = value; + } - public byte[] getKey() { - return this.key; - } + public byte[] getKey() { + return this.key; + } - public byte[] getValue() { - return this.value; - } + public byte[] getValue() { + return this.value; + } - public byte[] setValue(byte[] value) { - this.value = value; - return value; - } + public byte[] setValue(byte[] value) { + this.value = value; + return value; + } } } \ No newline at end of file diff --git a/src/main/java/redis/clients/util/JedisClusterCRC16.java b/src/main/java/redis/clients/util/JedisClusterCRC16.java index 044e003..c0d4afb 100644 --- a/src/main/java/redis/clients/util/JedisClusterCRC16.java +++ b/src/main/java/redis/clients/util/JedisClusterCRC16.java @@ -1,21 +1,23 @@ package redis.clients.util; public class JedisClusterCRC16 { - public final static int polynomial = 0x1021; // Represents x^16+x^12+x^5+1 - static int crc; - - public static int getSlot(String key) { - crc = 0x0000; - for (byte b : key.getBytes()) { - for (int i = 0; i < 8; i++) { - boolean bit = ((b >> (7-i) & 1) == 1); - boolean c15 = ((crc >> 15 & 1) == 1); - crc <<= 1; - // If coefficient of bit and remainder polynomial = 1 xor crc with polynomial - if (c15 ^ bit) crc ^= polynomial; - } - } + public final static int polynomial = 0x1021; // Represents x^16+x^12+x^5+1 + static int crc; - return crc &= 0xffff % 16384; - } + public static int getSlot(String key) { + crc = 0x0000; + for (byte b : key.getBytes()) { + for (int i = 0; i < 8; i++) { + boolean bit = ((b >> (7 - i) & 1) == 1); + boolean c15 = ((crc >> 15 & 1) == 1); + crc <<= 1; + // If coefficient of bit and remainder polynomial = 1 xor crc + // with polynomial + if (c15 ^ bit) + crc ^= polynomial; + } + } + + return crc &= 0xffff % 16384; + } } \ No newline at end of file diff --git a/src/main/java/redis/clients/util/MurmurHash.java b/src/main/java/redis/clients/util/MurmurHash.java index e9327da..7f6aecd 100644 --- a/src/main/java/redis/clients/util/MurmurHash.java +++ b/src/main/java/redis/clients/util/MurmurHash.java @@ -40,7 +40,7 @@ public class MurmurHash implements Hashing { * @return The 32 bit hash of the bytes in question. */ public static int hash(byte[] data, int seed) { - return hash(ByteBuffer.wrap(data), seed); + return hash(ByteBuffer.wrap(data), seed); } /** @@ -57,7 +57,7 @@ public class MurmurHash implements Hashing { * @return The 32-bit hash of the data in question. */ public static int hash(byte[] data, int offset, int length, int seed) { - return hash(ByteBuffer.wrap(data, offset, length), seed); + return hash(ByteBuffer.wrap(data, offset, length), seed); } /** @@ -70,97 +70,97 @@ public class MurmurHash implements Hashing { * @return The 32 bit murmur hash of the bytes in the buffer. */ public static int hash(ByteBuffer buf, int seed) { - // save byte order for later restoration - ByteOrder byteOrder = buf.order(); - buf.order(ByteOrder.LITTLE_ENDIAN); + // save byte order for later restoration + ByteOrder byteOrder = buf.order(); + buf.order(ByteOrder.LITTLE_ENDIAN); - int m = 0x5bd1e995; - int r = 24; + int m = 0x5bd1e995; + int r = 24; - int h = seed ^ buf.remaining(); + int h = seed ^ buf.remaining(); - int k; - while (buf.remaining() >= 4) { - k = buf.getInt(); + int k; + while (buf.remaining() >= 4) { + k = buf.getInt(); - k *= m; - k ^= k >>> r; - k *= m; + k *= m; + k ^= k >>> r; + k *= m; - h *= m; - h ^= k; - } + h *= m; + h ^= k; + } - if (buf.remaining() > 0) { - ByteBuffer finish = ByteBuffer.allocate(4).order( - ByteOrder.LITTLE_ENDIAN); - // for big-endian version, use this first: - // finish.position(4-buf.remaining()); - finish.put(buf).rewind(); - h ^= finish.getInt(); - h *= m; - } + if (buf.remaining() > 0) { + ByteBuffer finish = ByteBuffer.allocate(4).order( + ByteOrder.LITTLE_ENDIAN); + // for big-endian version, use this first: + // finish.position(4-buf.remaining()); + finish.put(buf).rewind(); + h ^= finish.getInt(); + h *= m; + } - h ^= h >>> 13; - h *= m; - h ^= h >>> 15; + h ^= h >>> 13; + h *= m; + h ^= h >>> 15; - buf.order(byteOrder); - return h; + buf.order(byteOrder); + return h; } public static long hash64A(byte[] data, int seed) { - return hash64A(ByteBuffer.wrap(data), seed); + return hash64A(ByteBuffer.wrap(data), seed); } public static long hash64A(byte[] data, int offset, int length, int seed) { - return hash64A(ByteBuffer.wrap(data, offset, length), seed); + return hash64A(ByteBuffer.wrap(data, offset, length), seed); } public static long hash64A(ByteBuffer buf, int seed) { - ByteOrder byteOrder = buf.order(); - buf.order(ByteOrder.LITTLE_ENDIAN); + ByteOrder byteOrder = buf.order(); + buf.order(ByteOrder.LITTLE_ENDIAN); - long m = 0xc6a4a7935bd1e995L; - int r = 47; + long m = 0xc6a4a7935bd1e995L; + int r = 47; - long h = seed ^ (buf.remaining() * m); + long h = seed ^ (buf.remaining() * m); - long k; - while (buf.remaining() >= 8) { - k = buf.getLong(); + long k; + while (buf.remaining() >= 8) { + k = buf.getLong(); - k *= m; - k ^= k >>> r; - k *= m; + k *= m; + k ^= k >>> r; + k *= m; - h ^= k; - h *= m; - } + h ^= k; + h *= m; + } - if (buf.remaining() > 0) { - ByteBuffer finish = ByteBuffer.allocate(8).order( - ByteOrder.LITTLE_ENDIAN); - // for big-endian version, do this first: - // finish.position(8-buf.remaining()); - finish.put(buf).rewind(); - h ^= finish.getLong(); - h *= m; - } + if (buf.remaining() > 0) { + ByteBuffer finish = ByteBuffer.allocate(8).order( + ByteOrder.LITTLE_ENDIAN); + // for big-endian version, do this first: + // finish.position(8-buf.remaining()); + finish.put(buf).rewind(); + h ^= finish.getLong(); + h *= m; + } - h ^= h >>> r; - h *= m; - h ^= h >>> r; + h ^= h >>> r; + h *= m; + h ^= h >>> r; - buf.order(byteOrder); - return h; + buf.order(byteOrder); + return h; } public long hash(byte[] key) { - return hash64A(key, 0x1234ABCD); + return hash64A(key, 0x1234ABCD); } public long hash(String key) { - return hash(SafeEncoder.encode(key)); + return hash(SafeEncoder.encode(key)); } } \ No newline at end of file diff --git a/src/main/java/redis/clients/util/RedisInputStream.java b/src/main/java/redis/clients/util/RedisInputStream.java index 221e756..5ac8c94 100644 --- a/src/main/java/redis/clients/util/RedisInputStream.java +++ b/src/main/java/redis/clients/util/RedisInputStream.java @@ -29,84 +29,84 @@ public class RedisInputStream extends FilterInputStream { protected int count, limit; public RedisInputStream(InputStream in, int size) { - super(in); - if (size <= 0) { - throw new IllegalArgumentException("Buffer size <= 0"); - } - buf = new byte[size]; + super(in); + if (size <= 0) { + throw new IllegalArgumentException("Buffer size <= 0"); + } + buf = new byte[size]; } public RedisInputStream(InputStream in) { - this(in, 8192); + this(in, 8192); } public byte readByte() throws IOException { - if (count == limit) { - fill(); - } + if (count == limit) { + fill(); + } - return buf[count++]; + return buf[count++]; } public String readLine() { - int b; - byte c; - StringBuilder sb = new StringBuilder(); + int b; + byte c; + StringBuilder sb = new StringBuilder(); - try { - while (true) { - if (count == limit) { - fill(); - } - if (limit == -1) - break; + try { + while (true) { + if (count == limit) { + fill(); + } + if (limit == -1) + break; - b = buf[count++]; - if (b == '\r') { - if (count == limit) { - fill(); - } + b = buf[count++]; + if (b == '\r') { + if (count == limit) { + fill(); + } - if (limit == -1) { - sb.append((char) b); - break; - } + if (limit == -1) { + sb.append((char) b); + break; + } - c = buf[count++]; - if (c == '\n') { - break; - } - sb.append((char) b); - sb.append((char) c); - } else { - sb.append((char) b); - } - } - } catch (IOException e) { - throw new JedisConnectionException(e); - } - String reply = sb.toString(); - if (reply.length() == 0) { - throw new JedisConnectionException( - "It seems like server has closed the connection."); - } - return reply; + c = buf[count++]; + if (c == '\n') { + break; + } + sb.append((char) b); + sb.append((char) c); + } else { + sb.append((char) b); + } + } + } catch (IOException e) { + throw new JedisConnectionException(e); + } + String reply = sb.toString(); + if (reply.length() == 0) { + throw new JedisConnectionException( + "It seems like server has closed the connection."); + } + return reply; } public int read(byte[] b, int off, int len) throws IOException { - if (count == limit) { - fill(); - if (limit == -1) - return -1; - } - final int length = Math.min(limit - count, len); - System.arraycopy(buf, count, b, off, length); - count += length; - return length; + if (count == limit) { + fill(); + if (limit == -1) + return -1; + } + final int length = Math.min(limit - count, len); + System.arraycopy(buf, count, b, off, length); + count += length; + return length; } private void fill() throws IOException { - limit = in.read(buf); - count = 0; + limit = in.read(buf); + count = 0; } } diff --git a/src/main/java/redis/clients/util/RedisOutputStream.java b/src/main/java/redis/clients/util/RedisOutputStream.java index 5398f36..4dba859 100644 --- a/src/main/java/redis/clients/util/RedisOutputStream.java +++ b/src/main/java/redis/clients/util/RedisOutputStream.java @@ -1,11 +1,13 @@ package redis.clients.util; -import java.io.*; +import java.io.FilterOutputStream; +import java.io.IOException; +import java.io.OutputStream; /** - * The class implements a buffered output stream without synchronization - * There are also special operations like in-place string encoding. - * This stream fully ignore mark/reset and should not be used outside Jedis + * The class implements a buffered output stream without synchronization There + * are also special operations like in-place string encoding. This stream fully + * ignore mark/reset and should not be used outside Jedis */ public final class RedisOutputStream extends FilterOutputStream { protected final byte buf[]; @@ -13,218 +15,212 @@ public final class RedisOutputStream extends FilterOutputStream { protected int count; public RedisOutputStream(final OutputStream out) { - this(out, 8192); + this(out, 8192); } public RedisOutputStream(final OutputStream out, final int size) { - super(out); - if (size <= 0) { - throw new IllegalArgumentException("Buffer size <= 0"); - } - buf = new byte[size]; + super(out); + if (size <= 0) { + throw new IllegalArgumentException("Buffer size <= 0"); + } + buf = new byte[size]; } private void flushBuffer() throws IOException { - if (count > 0) { - out.write(buf, 0, count); - count = 0; - } + if (count > 0) { + out.write(buf, 0, count); + count = 0; + } } public void write(final byte b) throws IOException { - buf[count++] = b; - if (count == buf.length) { - flushBuffer(); - } + buf[count++] = b; + if (count == buf.length) { + flushBuffer(); + } } - + public void write(final byte[] b) throws IOException { - write(b, 0, b.length); + write(b, 0, b.length); } - public void write(final byte b[], final int off, final int len) throws IOException { - if (len >= buf.length) { - flushBuffer(); - out.write(b, off, len); - } else { - if (len >= buf.length - count) { - flushBuffer(); - } + public void write(final byte b[], final int off, final int len) + throws IOException { + if (len >= buf.length) { + flushBuffer(); + out.write(b, off, len); + } else { + if (len >= buf.length - count) { + flushBuffer(); + } - System.arraycopy(b, off, buf, count, len); - count += len; - } + System.arraycopy(b, off, buf, count, len); + count += len; + } } public void writeAsciiCrLf(final String in) throws IOException { - final int size = in.length(); + final int size = in.length(); - for (int i = 0; i != size; ++i) { - buf[count++] = (byte) in.charAt(i); - if (count == buf.length) { - flushBuffer(); - } - } + for (int i = 0; i != size; ++i) { + buf[count++] = (byte) in.charAt(i); + if (count == buf.length) { + flushBuffer(); + } + } - writeCrLf(); + writeCrLf(); } public static boolean isSurrogate(final char ch) { - return ch >= Character.MIN_SURROGATE && ch <= Character.MAX_SURROGATE; + return ch >= Character.MIN_SURROGATE && ch <= Character.MAX_SURROGATE; } - public static int utf8Length (final String str) { - int strLen = str.length(), utfLen = 0; - for(int i = 0; i != strLen; ++i) { - char c = str.charAt(i); - if (c < 0x80) { - utfLen++; - } else if (c < 0x800) { - utfLen += 2; - } else if (isSurrogate(c)) { - i++; - utfLen += 4; - } else { - utfLen += 3; - } - } - return utfLen; + public static int utf8Length(final String str) { + int strLen = str.length(), utfLen = 0; + for (int i = 0; i != strLen; ++i) { + char c = str.charAt(i); + if (c < 0x80) { + utfLen++; + } else if (c < 0x800) { + utfLen += 2; + } else if (isSurrogate(c)) { + i++; + utfLen += 4; + } else { + utfLen += 3; + } + } + return utfLen; } public void writeCrLf() throws IOException { - if (2 >= buf.length - count) { - flushBuffer(); - } + if (2 >= buf.length - count) { + flushBuffer(); + } - buf[count++] = '\r'; - buf[count++] = '\n'; + buf[count++] = '\r'; + buf[count++] = '\n'; } public void writeUtf8CrLf(final String str) throws IOException { - int strLen = str.length(); + int strLen = str.length(); - int i; - for (i = 0; i < strLen; i++) { - char c = str.charAt(i); - if (!(c < 0x80)) break; - buf[count++] = (byte) c; - if(count == buf.length) { - flushBuffer(); - } - } + int i; + for (i = 0; i < strLen; i++) { + char c = str.charAt(i); + if (!(c < 0x80)) + break; + buf[count++] = (byte) c; + if (count == buf.length) { + flushBuffer(); + } + } - for (; i < strLen; i++) { - char c = str.charAt(i); - if (c < 0x80) { - buf[count++] = (byte) c; - if(count == buf.length) { - flushBuffer(); - } - } else if (c < 0x800) { - if(2 >= buf.length - count) { - flushBuffer(); - } - buf[count++] = (byte)(0xc0 | (c >> 6)); - buf[count++] = (byte)(0x80 | (c & 0x3f)); - } else if (isSurrogate(c)) { - if(4 >= buf.length - count) { - flushBuffer(); - } - int uc = Character.toCodePoint(c, str.charAt(i++)); - buf[count++] = ((byte)(0xf0 | ((uc >> 18)))); - buf[count++] = ((byte)(0x80 | ((uc >> 12) & 0x3f))); - buf[count++] = ((byte)(0x80 | ((uc >> 6) & 0x3f))); - buf[count++] = ((byte)(0x80 | (uc & 0x3f))); - } else { - if(3 >= buf.length - count) { - flushBuffer(); - } - buf[count++] =((byte)(0xe0 | ((c >> 12)))); - buf[count++] =((byte)(0x80 | ((c >> 6) & 0x3f))); - buf[count++] =((byte)(0x80 | (c & 0x3f))); - } - } + for (; i < strLen; i++) { + char c = str.charAt(i); + if (c < 0x80) { + buf[count++] = (byte) c; + if (count == buf.length) { + flushBuffer(); + } + } else if (c < 0x800) { + if (2 >= buf.length - count) { + flushBuffer(); + } + buf[count++] = (byte) (0xc0 | (c >> 6)); + buf[count++] = (byte) (0x80 | (c & 0x3f)); + } else if (isSurrogate(c)) { + if (4 >= buf.length - count) { + flushBuffer(); + } + int uc = Character.toCodePoint(c, str.charAt(i++)); + buf[count++] = ((byte) (0xf0 | ((uc >> 18)))); + buf[count++] = ((byte) (0x80 | ((uc >> 12) & 0x3f))); + buf[count++] = ((byte) (0x80 | ((uc >> 6) & 0x3f))); + buf[count++] = ((byte) (0x80 | (uc & 0x3f))); + } else { + if (3 >= buf.length - count) { + flushBuffer(); + } + buf[count++] = ((byte) (0xe0 | ((c >> 12)))); + buf[count++] = ((byte) (0x80 | ((c >> 6) & 0x3f))); + buf[count++] = ((byte) (0x80 | (c & 0x3f))); + } + } - writeCrLf(); + writeCrLf(); } - private final static int[] sizeTable = {9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, Integer.MAX_VALUE}; + private final static int[] sizeTable = { 9, 99, 999, 9999, 99999, 999999, + 9999999, 99999999, 999999999, Integer.MAX_VALUE }; - private final static byte[] DigitTens = { - '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', - '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', - '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', - '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', - '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', - '5', '5', '5', '5', '5', '5', '5', '5', '5', '5', - '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', - '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', - '8', '8', '8', '8', '8', '8', '8', '8', '8', '8', - '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', - }; + private final static byte[] DigitTens = { '0', '0', '0', '0', '0', '0', + '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', + '1', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '3', '3', + '3', '3', '3', '3', '3', '3', '3', '3', '4', '4', '4', '4', '4', + '4', '4', '4', '4', '4', '5', '5', '5', '5', '5', '5', '5', '5', + '5', '5', '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', '7', + '7', '7', '7', '7', '7', '7', '7', '7', '7', '8', '8', '8', '8', + '8', '8', '8', '8', '8', '8', '9', '9', '9', '9', '9', '9', '9', + '9', '9', '9', }; - private final static byte[] DigitOnes = { - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - }; + private final static byte[] DigitOnes = { '0', '1', '2', '3', '4', '5', + '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', + '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', + '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', + '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', + '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', + '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', + '7', '8', '9', }; - private final static byte[] digits = { - '0', '1', '2', '3', '4', '5', - '6', '7', '8', '9', 'a', 'b', - 'c', 'd', 'e', 'f', 'g', 'h', - 'i', 'j', 'k', 'l', 'm', 'n', - 'o', 'p', 'q', 'r', 's', 't', - 'u', 'v', 'w', 'x', 'y', 'z' - }; + private final static byte[] digits = { '0', '1', '2', '3', '4', '5', '6', + '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', + 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', + 'x', 'y', 'z' }; public void writeIntCrLf(int value) throws IOException { - if (value < 0) { - write((byte)'-'); - value = -value; - } + if (value < 0) { + write((byte) '-'); + value = -value; + } - int size = 0; - while (value > sizeTable[size]) - size++; + int size = 0; + while (value > sizeTable[size]) + size++; - size++; - if (size >= buf.length - count) { - flushBuffer(); - } + size++; + if (size >= buf.length - count) { + flushBuffer(); + } - int q, r; - int charPos = count + size; + int q, r; + int charPos = count + size; - while (value >= 65536) { - q = value / 100; - r = value - ((q << 6) + (q << 5) + (q << 2)); - value = q; - buf[--charPos] = DigitOnes[r]; - buf[--charPos] = DigitTens[r]; - } + while (value >= 65536) { + q = value / 100; + r = value - ((q << 6) + (q << 5) + (q << 2)); + value = q; + buf[--charPos] = DigitOnes[r]; + buf[--charPos] = DigitTens[r]; + } - for (; ;) { - q = (value * 52429) >>> (16 + 3); - r = value - ((q << 3) + (q << 1)); - buf[--charPos] = digits[r]; - value = q; - if (value == 0) break; - } - count += size; + for (;;) { + q = (value * 52429) >>> (16 + 3); + r = value - ((q << 3) + (q << 1)); + buf[--charPos] = digits[r]; + value = q; + if (value == 0) + break; + } + count += size; - writeCrLf(); + writeCrLf(); } public void flush() throws IOException { - flushBuffer(); - out.flush(); + flushBuffer(); + out.flush(); } } diff --git a/src/main/java/redis/clients/util/SafeEncoder.java b/src/main/java/redis/clients/util/SafeEncoder.java index a00e6c4..9ec0a7c 100644 --- a/src/main/java/redis/clients/util/SafeEncoder.java +++ b/src/main/java/redis/clients/util/SafeEncoder.java @@ -11,31 +11,31 @@ import redis.clients.jedis.exceptions.JedisException; * */ public class SafeEncoder { - public static byte[][] encodeMany(final String... strs){ - byte[][] many = new byte[strs.length][]; - for(int i=0;i { } public ShardInfo(int weight) { - this.weight = weight; + this.weight = weight; } public int getWeight() { - return this.weight; + return this.weight; } protected abstract T createResource(); - + public abstract String getName(); } diff --git a/src/main/java/redis/clients/util/Sharded.java b/src/main/java/redis/clients/util/Sharded.java index 5448fcd..98c74de 100644 --- a/src/main/java/redis/clients/util/Sharded.java +++ b/src/main/java/redis/clients/util/Sharded.java @@ -26,91 +26,93 @@ public class Sharded> { private Pattern tagPattern = null; // the tag is anything between {} public static final Pattern DEFAULT_KEY_TAG_PATTERN = Pattern - .compile("\\{(.+?)\\}"); + .compile("\\{(.+?)\\}"); public Sharded(List shards) { - this(shards, Hashing.MURMUR_HASH); // MD5 is really not good as we works - // with 64-bits not 128 + this(shards, Hashing.MURMUR_HASH); // MD5 is really not good as we works + // with 64-bits not 128 } public Sharded(List shards, Hashing algo) { - this.algo = algo; - initialize(shards); + this.algo = algo; + initialize(shards); } public Sharded(List shards, Pattern tagPattern) { - this(shards, Hashing.MURMUR_HASH, tagPattern); // MD5 is really not good - // as we works with - // 64-bits not 128 + this(shards, Hashing.MURMUR_HASH, tagPattern); // MD5 is really not good + // as we works with + // 64-bits not 128 } public Sharded(List shards, Hashing algo, Pattern tagPattern) { - this.algo = algo; - this.tagPattern = tagPattern; - initialize(shards); + this.algo = algo; + this.tagPattern = tagPattern; + initialize(shards); } private void initialize(List shards) { - nodes = new TreeMap(); + nodes = new TreeMap(); - for (int i = 0; i != shards.size(); ++i) { - final S shardInfo = shards.get(i); - if (shardInfo.getName() == null) - for (int n = 0; n < 160 * shardInfo.getWeight(); n++) { - nodes.put(this.algo.hash("SHARD-" + i + "-NODE-" + n), shardInfo); - } - else - for (int n = 0; n < 160 * shardInfo.getWeight(); n++) { - nodes.put(this.algo.hash(shardInfo.getName() + "*" + shardInfo.getWeight() + n), shardInfo); - } - resources.put(shardInfo, shardInfo.createResource()); - } + for (int i = 0; i != shards.size(); ++i) { + final S shardInfo = shards.get(i); + if (shardInfo.getName() == null) + for (int n = 0; n < 160 * shardInfo.getWeight(); n++) { + nodes.put(this.algo.hash("SHARD-" + i + "-NODE-" + n), + shardInfo); + } + else + for (int n = 0; n < 160 * shardInfo.getWeight(); n++) { + nodes.put( + this.algo.hash(shardInfo.getName() + "*" + + shardInfo.getWeight() + n), shardInfo); + } + resources.put(shardInfo, shardInfo.createResource()); + } } public R getShard(byte[] key) { - return resources.get(getShardInfo(key)); + return resources.get(getShardInfo(key)); } public R getShard(String key) { - return resources.get(getShardInfo(key)); + return resources.get(getShardInfo(key)); } public S getShardInfo(byte[] key) { - SortedMap tail = nodes.tailMap(algo.hash(key)); - if (tail.isEmpty()) { - return nodes.get(nodes.firstKey()); - } - return tail.get(tail.firstKey()); + SortedMap tail = nodes.tailMap(algo.hash(key)); + if (tail.isEmpty()) { + return nodes.get(nodes.firstKey()); + } + return tail.get(tail.firstKey()); } public S getShardInfo(String key) { - return getShardInfo(SafeEncoder.encode(getKeyTag(key))); + return getShardInfo(SafeEncoder.encode(getKeyTag(key))); } /** * A key tag is a special pattern inside a key that, if preset, is the only * part of the key hashed in order to select the server for this key. - * + * * @see http://code.google.com/p/redis/wiki/FAQ#I * 'm_using_some_form_of_key_hashing_for_partitioning,_but_wh * @param key * @return The tag if it exists, or the original key */ public String getKeyTag(String key) { - if (tagPattern != null) { - Matcher m = tagPattern.matcher(key); - if (m.find()) - return m.group(1); - } - return key; + if (tagPattern != null) { + Matcher m = tagPattern.matcher(key); + if (m.find()) + return m.group(1); + } + return key; } public Collection getAllShardInfo() { - return Collections.unmodifiableCollection(nodes.values()); + return Collections.unmodifiableCollection(nodes.values()); } public Collection getAllShards() { - return Collections.unmodifiableCollection(resources.values()); + return Collections.unmodifiableCollection(resources.values()); } } - diff --git a/src/main/java/redis/clients/util/Slowlog.java b/src/main/java/redis/clients/util/Slowlog.java index 0a0e7be..6e286d9 100644 --- a/src/main/java/redis/clients/util/Slowlog.java +++ b/src/main/java/redis/clients/util/Slowlog.java @@ -4,50 +4,50 @@ import java.util.ArrayList; import java.util.List; public class Slowlog { - private final long id; - private final long timeStamp; - private final long executionTime; - private final List args; - - @SuppressWarnings("unchecked") - public static List from(List nestedMultiBulkReply){ - List logs = new ArrayList(nestedMultiBulkReply.size()); - for(Object obj : nestedMultiBulkReply){ - List properties = (List)obj; - logs.add(new Slowlog(properties)); - } - - return logs; - } - - @SuppressWarnings("unchecked") - private Slowlog(List properties) { - super(); - this.id = (Long)properties.get(0); - this.timeStamp = (Long)properties.get(1); - this.executionTime = (Long)properties.get(2); - - List bargs = (List)properties.get(3); - this.args = new ArrayList(bargs.size()); - - for(byte[] barg:bargs){ - this.args.add(SafeEncoder.encode(barg)); - } + private final long id; + private final long timeStamp; + private final long executionTime; + private final List args; + + @SuppressWarnings("unchecked") + public static List from(List nestedMultiBulkReply) { + List logs = new ArrayList(nestedMultiBulkReply.size()); + for (Object obj : nestedMultiBulkReply) { + List properties = (List) obj; + logs.add(new Slowlog(properties)); } - public long getId() { - return id; - } + return logs; + } - public long getTimeStamp() { - return timeStamp; - } + @SuppressWarnings("unchecked") + private Slowlog(List properties) { + super(); + this.id = (Long) properties.get(0); + this.timeStamp = (Long) properties.get(1); + this.executionTime = (Long) properties.get(2); - public long getExecutionTime() { - return executionTime; - } + List bargs = (List) properties.get(3); + this.args = new ArrayList(bargs.size()); - public List getArgs() { - return args; + for (byte[] barg : bargs) { + this.args.add(SafeEncoder.encode(barg)); } + } + + public long getId() { + return id; + } + + public long getTimeStamp() { + return timeStamp; + } + + public long getExecutionTime() { + return executionTime; + } + + public List getArgs() { + return args; + } } diff --git a/src/test/java/redis/clients/jedis/tests/BuilderFactoryTest.java b/src/test/java/redis/clients/jedis/tests/BuilderFactoryTest.java index b759134..4521112 100644 --- a/src/test/java/redis/clients/jedis/tests/BuilderFactoryTest.java +++ b/src/test/java/redis/clients/jedis/tests/BuilderFactoryTest.java @@ -8,7 +8,7 @@ import redis.clients.jedis.BuilderFactory; public class BuilderFactoryTest extends Assert { @Test public void buildDouble() { - Double build = BuilderFactory.DOUBLE.build("1.0".getBytes()); - assertEquals(new Double(1.0), build); + Double build = BuilderFactory.DOUBLE.build("1.0".getBytes()); + assertEquals(new Double(1.0), build); } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/ConnectionTest.java b/src/test/java/redis/clients/jedis/tests/ConnectionTest.java index eee7ac9..9cbaa12 100644 --- a/src/test/java/redis/clients/jedis/tests/ConnectionTest.java +++ b/src/test/java/redis/clients/jedis/tests/ConnectionTest.java @@ -13,31 +13,31 @@ public class ConnectionTest extends Assert { @Before public void setUp() throws Exception { - client = new Connection(); + client = new Connection(); } @After public void tearDown() throws Exception { - client.disconnect(); + client.disconnect(); } @Test(expected = JedisConnectionException.class) public void checkUnkownHost() { - client.setHost("someunknownhost"); - client.connect(); + client.setHost("someunknownhost"); + client.connect(); } @Test(expected = JedisConnectionException.class) public void checkWrongPort() { - client.setHost("localhost"); - client.setPort(55665); - client.connect(); + client.setHost("localhost"); + client.setPort(55665); + client.connect(); } - + @Test public void connectIfNotConnectedWhenSettingTimeoutInfinite() { client.setHost("localhost"); - client.setPort(6379); + client.setPort(6379); client.setTimeoutInfinite(); } diff --git a/src/test/java/redis/clients/jedis/tests/FragmentedByteArrayInputStream.java b/src/test/java/redis/clients/jedis/tests/FragmentedByteArrayInputStream.java index 37d7d82..fdf8d13 100644 --- a/src/test/java/redis/clients/jedis/tests/FragmentedByteArrayInputStream.java +++ b/src/test/java/redis/clients/jedis/tests/FragmentedByteArrayInputStream.java @@ -9,22 +9,22 @@ public class FragmentedByteArrayInputStream extends ByteArrayInputStream { private int readMethodCallCount = 0; public FragmentedByteArrayInputStream(final byte[] buf) { - super(buf); + super(buf); } public synchronized int read(final byte[] b, final int off, final int len) { - readMethodCallCount++; - if (len <= 10) { - // if the len <= 10, return as usual .. - return super.read(b, off, len); - } else { - // else return the first half .. - return super.read(b, off, len / 2); - } + readMethodCallCount++; + if (len <= 10) { + // if the len <= 10, return as usual .. + return super.read(b, off, len); + } else { + // else return the first half .. + return super.read(b, off, len / 2); + } } public int getReadMethodCallCount() { - return readMethodCallCount; + return readMethodCallCount; } } diff --git a/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java b/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java index c62e3bd..a501024 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java @@ -19,59 +19,59 @@ public class JedisPoolTest extends Assert { @Test public void checkConnections() { - JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), - hnp.getPort(), 2000); - Jedis jedis = pool.getResource(); - jedis.auth("foobared"); - jedis.set("foo", "bar"); - assertEquals("bar", jedis.get("foo")); - pool.returnResource(jedis); - pool.destroy(); + JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), + hnp.getPort(), 2000); + Jedis jedis = pool.getResource(); + jedis.auth("foobared"); + jedis.set("foo", "bar"); + assertEquals("bar", jedis.get("foo")); + pool.returnResource(jedis); + pool.destroy(); } @Test public void checkConnectionWithDefaultPort() { - JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), - hnp.getPort()); - Jedis jedis = pool.getResource(); - jedis.auth("foobared"); - jedis.set("foo", "bar"); - assertEquals("bar", jedis.get("foo")); - pool.returnResource(jedis); - pool.destroy(); + JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), + hnp.getPort()); + Jedis jedis = pool.getResource(); + jedis.auth("foobared"); + jedis.set("foo", "bar"); + assertEquals("bar", jedis.get("foo")); + pool.returnResource(jedis); + pool.destroy(); } @Test public void checkJedisIsReusedWhenReturned() { - JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), - hnp.getPort()); - Jedis jedis = pool.getResource(); - jedis.auth("foobared"); - jedis.set("foo", "0"); - pool.returnResource(jedis); + JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), + hnp.getPort()); + Jedis jedis = pool.getResource(); + jedis.auth("foobared"); + jedis.set("foo", "0"); + pool.returnResource(jedis); - jedis = pool.getResource(); - jedis.auth("foobared"); - jedis.incr("foo"); - pool.returnResource(jedis); - pool.destroy(); + jedis = pool.getResource(); + jedis.auth("foobared"); + jedis.incr("foo"); + pool.returnResource(jedis); + pool.destroy(); } @Test public void checkPoolRepairedWhenJedisIsBroken() { - JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), - hnp.getPort()); - Jedis jedis = pool.getResource(); - jedis.auth("foobared"); - jedis.quit(); - pool.returnBrokenResource(jedis); + JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), + hnp.getPort()); + Jedis jedis = pool.getResource(); + jedis.auth("foobared"); + jedis.quit(); + pool.returnBrokenResource(jedis); - jedis = pool.getResource(); - jedis.auth("foobared"); - jedis.incr("foo"); - pool.returnResource(jedis); - pool.destroy(); + jedis = pool.getResource(); + jedis.auth("foobared"); + jedis.incr("foo"); + pool.returnResource(jedis); + pool.destroy(); } @Test(expected = JedisConnectionException.class) @@ -93,8 +93,8 @@ public class JedisPoolTest extends Assert { public void securePool() { JedisPoolConfig config = new JedisPoolConfig(); config.setTestOnBorrow(true); - JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(), 2000, - "foobared"); + JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(), + 2000, "foobared"); Jedis jedis = pool.getResource(); jedis.set("foo", "bar"); pool.returnResource(jedis); @@ -177,25 +177,25 @@ public class JedisPoolTest extends Assert { pool0.returnResource(jedis); pool0.destroy(); } - + @Test public void returnResourceShouldResetState() { - GenericObjectPoolConfig config = new GenericObjectPoolConfig(); - config.setMaxTotal(1); - config.setBlockWhenExhausted(false); - JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(), - 2000, "foobared"); - - Jedis jedis = pool.getResource(); - jedis.set("hello", "jedis"); - Transaction t = jedis.multi(); - t.set("hello", "world"); - pool.returnResource(jedis); - - Jedis jedis2 = pool.getResource(); - assertTrue(jedis == jedis2); - assertEquals("jedis", jedis2.get("hello")); - pool.returnResource(jedis2); - pool.destroy(); + GenericObjectPoolConfig config = new GenericObjectPoolConfig(); + config.setMaxTotal(1); + config.setBlockWhenExhausted(false); + JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(), + 2000, "foobared"); + + Jedis jedis = pool.getResource(); + jedis.set("hello", "jedis"); + Transaction t = jedis.multi(); + t.set("hello", "world"); + pool.returnResource(jedis); + + Jedis jedis2 = pool.getResource(); + assertTrue(jedis == jedis2); + assertEquals("jedis", jedis2.get("hello")); + pool.returnResource(jedis2); + pool.destroy(); } } diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java index 9d7fc46..f8a3ee2 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java @@ -11,7 +11,6 @@ import org.junit.Test; import redis.clients.jedis.DebugParams; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPubSub; import redis.clients.jedis.JedisSentinelPool; import redis.clients.jedis.Transaction; @@ -154,22 +153,22 @@ public class JedisSentinelPoolTest extends JedisTestBase { @Test public void returnResourceShouldResetState() { - GenericObjectPoolConfig config = new GenericObjectPoolConfig(); - config.setMaxTotal(1); - config.setBlockWhenExhausted(false); - JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels, - config, 1000, "foobared", 2); - - Jedis jedis = pool.getResource(); - jedis.set("hello", "jedis"); - Transaction t = jedis.multi(); - t.set("hello", "world"); - pool.returnResource(jedis); - - Jedis jedis2 = pool.getResource(); - assertTrue(jedis == jedis2); - assertEquals("jedis", jedis2.get("hello")); - pool.returnResource(jedis2); - pool.destroy(); + GenericObjectPoolConfig config = new GenericObjectPoolConfig(); + config.setMaxTotal(1); + config.setBlockWhenExhausted(false); + JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels, + config, 1000, "foobared", 2); + + Jedis jedis = pool.getResource(); + jedis.set("hello", "jedis"); + Transaction t = jedis.multi(); + t.set("hello", "world"); + pool.returnResource(jedis); + + Jedis jedis2 = pool.getResource(); + assertTrue(jedis == jedis2); + assertEquals("jedis", jedis2.get("hello")); + pool.returnResource(jedis2); + pool.destroy(); } } diff --git a/src/test/java/redis/clients/jedis/tests/JedisTestBase.java b/src/test/java/redis/clients/jedis/tests/JedisTestBase.java index 74ce5bd..158e20c 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisTestBase.java +++ b/src/test/java/redis/clients/jedis/tests/JedisTestBase.java @@ -8,18 +8,18 @@ import org.junit.Assert; public abstract class JedisTestBase extends Assert { protected void assertEquals(List expected, List actual) { - assertEquals(expected.size(), actual.size()); - for (int n = 0; n < expected.size(); n++) { - assertArrayEquals(expected.get(n), actual.get(n)); - } + assertEquals(expected.size(), actual.size()); + for (int n = 0; n < expected.size(); n++) { + assertArrayEquals(expected.get(n), actual.get(n)); + } } protected void assertEquals(Set expected, Set actual) { - assertEquals(expected.size(), actual.size()); - Iterator iterator = expected.iterator(); - Iterator iterator2 = actual.iterator(); - while (iterator.hasNext() || iterator2.hasNext()) { - assertArrayEquals(iterator.next(), iterator2.next()); - } + assertEquals(expected.size(), actual.size()); + Iterator iterator = expected.iterator(); + Iterator iterator2 = actual.iterator(); + while (iterator.hasNext() || iterator2.hasNext()) { + assertArrayEquals(iterator.next(), iterator2.next()); + } } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/PipeliningTest.java b/src/test/java/redis/clients/jedis/tests/PipeliningTest.java index 1fe063c..2b3eabe 100755 --- a/src/test/java/redis/clients/jedis/tests/PipeliningTest.java +++ b/src/test/java/redis/clients/jedis/tests/PipeliningTest.java @@ -27,307 +27,321 @@ public class PipeliningTest extends Assert { @Before public void setUp() throws Exception { - jedis = new Jedis(hnp.getHost(), hnp.getPort(), 500); - jedis.connect(); - jedis.auth("foobared"); - jedis.flushAll(); + jedis = new Jedis(hnp.getHost(), hnp.getPort(), 500); + jedis.connect(); + jedis.auth("foobared"); + jedis.flushAll(); } @Test public void pipeline() throws UnsupportedEncodingException { - List results = jedis.pipelined(new PipelineBlock() { - public void execute() { - set("foo", "bar"); - get("foo"); - } - }); + List results = jedis.pipelined(new PipelineBlock() { + public void execute() { + set("foo", "bar"); + get("foo"); + } + }); - assertEquals(2, results.size()); - assertEquals("OK", results.get(0)); - assertEquals("bar", results.get(1)); + assertEquals(2, results.size()); + assertEquals("OK", results.get(0)); + assertEquals("bar", results.get(1)); - Pipeline p = jedis.pipelined(); - p.set("foo", "bar"); - p.get("foo"); - results = p.syncAndReturnAll(); + Pipeline p = jedis.pipelined(); + p.set("foo", "bar"); + p.get("foo"); + results = p.syncAndReturnAll(); - assertEquals(2, results.size()); - assertEquals("OK", results.get(0)); - assertEquals("bar", results.get(1)); + assertEquals(2, results.size()); + assertEquals("OK", results.get(0)); + assertEquals("bar", results.get(1)); } @Test public void pipelineResponse() { - jedis.set("string", "foo"); - jedis.lpush("list", "foo"); - jedis.hset("hash", "foo", "bar"); - jedis.zadd("zset", 1, "foo"); - jedis.sadd("set", "foo"); + jedis.set("string", "foo"); + jedis.lpush("list", "foo"); + jedis.hset("hash", "foo", "bar"); + jedis.zadd("zset", 1, "foo"); + jedis.sadd("set", "foo"); - Pipeline p = jedis.pipelined(); - Response string = p.get("string"); - Response list = p.lpop("list"); - Response hash = p.hget("hash", "foo"); - Response> zset = p.zrange("zset", 0, -1); - Response set = p.spop("set"); - Response blist = p.exists("list"); - Response zincrby = p.zincrby("zset", 1, "foo"); - Response zcard = p.zcard("zset"); - p.lpush("list", "bar"); - Response> lrange = p.lrange("list", 0, -1); - Response> hgetAll = p.hgetAll("hash"); - p.sadd("set", "foo"); - Response> smembers = p.smembers("set"); - Response> zrangeWithScores = p.zrangeWithScores("zset", 0, - -1); - p.sync(); + Pipeline p = jedis.pipelined(); + Response string = p.get("string"); + Response list = p.lpop("list"); + Response hash = p.hget("hash", "foo"); + Response> zset = p.zrange("zset", 0, -1); + Response set = p.spop("set"); + Response blist = p.exists("list"); + Response zincrby = p.zincrby("zset", 1, "foo"); + Response zcard = p.zcard("zset"); + p.lpush("list", "bar"); + Response> lrange = p.lrange("list", 0, -1); + Response> hgetAll = p.hgetAll("hash"); + p.sadd("set", "foo"); + Response> smembers = p.smembers("set"); + Response> zrangeWithScores = p.zrangeWithScores("zset", 0, + -1); + p.sync(); - assertEquals("foo", string.get()); - assertEquals("foo", list.get()); - assertEquals("bar", hash.get()); - assertEquals("foo", zset.get().iterator().next()); - assertEquals("foo", set.get()); - assertEquals(false, blist.get()); - assertEquals(Double.valueOf(2), zincrby.get()); - assertEquals(Long.valueOf(1), zcard.get()); - assertEquals(1, lrange.get().size()); - assertNotNull(hgetAll.get().get("foo")); - assertEquals(1, smembers.get().size()); - assertEquals(1, zrangeWithScores.get().size()); + assertEquals("foo", string.get()); + assertEquals("foo", list.get()); + assertEquals("bar", hash.get()); + assertEquals("foo", zset.get().iterator().next()); + assertEquals("foo", set.get()); + assertEquals(false, blist.get()); + assertEquals(Double.valueOf(2), zincrby.get()); + assertEquals(Long.valueOf(1), zcard.get()); + assertEquals(1, lrange.get().size()); + assertNotNull(hgetAll.get().get("foo")); + assertEquals(1, smembers.get().size()); + assertEquals(1, zrangeWithScores.get().size()); } - + @Test public void pipelineResponseWithData() { - jedis.zadd("zset", 1, "foo"); - - Pipeline p = jedis.pipelined(); - Response score = p.zscore("zset", "foo"); - p.sync(); + jedis.zadd("zset", 1, "foo"); - assertNotNull(score.get()); + Pipeline p = jedis.pipelined(); + Response score = p.zscore("zset", "foo"); + p.sync(); + + assertNotNull(score.get()); } @Test public void pipelineBinarySafeHashCommands() { - jedis.hset("key".getBytes(), "f1".getBytes(), "v111".getBytes()); - jedis.hset("key".getBytes(), "f22".getBytes(), "v2222".getBytes()); + jedis.hset("key".getBytes(), "f1".getBytes(), "v111".getBytes()); + jedis.hset("key".getBytes(), "f22".getBytes(), "v2222".getBytes()); - Pipeline p = jedis.pipelined(); - Response> fmap = p.hgetAll("key".getBytes()); - Response> fkeys = p.hkeys("key".getBytes()); - Response> fordered = p.hmget("key".getBytes(), "f22".getBytes(), "f1".getBytes()); - Response> fvals = p.hvals("key".getBytes()); - p.sync(); + Pipeline p = jedis.pipelined(); + Response> fmap = p.hgetAll("key".getBytes()); + Response> fkeys = p.hkeys("key".getBytes()); + Response> fordered = p.hmget("key".getBytes(), + "f22".getBytes(), "f1".getBytes()); + Response> fvals = p.hvals("key".getBytes()); + p.sync(); - assertNotNull(fmap.get()); - // we have to do these strange contortions because byte[] is not a very good key - // for a java Map. It only works with equality (you need the exact key object to retrieve - // the value) I recommend we switch to using ByteBuffer or something similar: - // http://stackoverflow.com/questions/1058149/using-a-byte-array-as-hashmap-key-java - Map map = fmap.get(); - Set mapKeys = map.keySet(); - Iterator iterMap = mapKeys.iterator(); - byte[] firstMapKey = iterMap.next(); - byte[] secondMapKey = iterMap.next(); - assertFalse(iterMap.hasNext()); - verifyHasBothValues(firstMapKey, secondMapKey, "f1".getBytes(), "f22".getBytes()); - byte[] firstMapValue = map.get(firstMapKey); - byte[] secondMapValue = map.get(secondMapKey); - verifyHasBothValues(firstMapValue, secondMapValue, "v111".getBytes(), "v2222".getBytes()); + assertNotNull(fmap.get()); + // we have to do these strange contortions because byte[] is not a very + // good key + // for a java Map. It only works with equality (you need the exact key + // object to retrieve + // the value) I recommend we switch to using ByteBuffer or something + // similar: + // http://stackoverflow.com/questions/1058149/using-a-byte-array-as-hashmap-key-java + Map map = fmap.get(); + Set mapKeys = map.keySet(); + Iterator iterMap = mapKeys.iterator(); + byte[] firstMapKey = iterMap.next(); + byte[] secondMapKey = iterMap.next(); + assertFalse(iterMap.hasNext()); + verifyHasBothValues(firstMapKey, secondMapKey, "f1".getBytes(), + "f22".getBytes()); + byte[] firstMapValue = map.get(firstMapKey); + byte[] secondMapValue = map.get(secondMapKey); + verifyHasBothValues(firstMapValue, secondMapValue, "v111".getBytes(), + "v2222".getBytes()); - assertNotNull(fkeys.get()); - Iterator iter = fkeys.get().iterator(); - byte[] firstKey = iter.next(); - byte[] secondKey = iter.next(); - assertFalse(iter.hasNext()); - verifyHasBothValues(firstKey, secondKey, "f1".getBytes(), "f22".getBytes()); + assertNotNull(fkeys.get()); + Iterator iter = fkeys.get().iterator(); + byte[] firstKey = iter.next(); + byte[] secondKey = iter.next(); + assertFalse(iter.hasNext()); + verifyHasBothValues(firstKey, secondKey, "f1".getBytes(), + "f22".getBytes()); - assertNotNull(fordered.get()); - assertArrayEquals("v2222".getBytes(), fordered.get().get(0)); - assertArrayEquals("v111".getBytes(), fordered.get().get(1)); + assertNotNull(fordered.get()); + assertArrayEquals("v2222".getBytes(), fordered.get().get(0)); + assertArrayEquals("v111".getBytes(), fordered.get().get(1)); - assertNotNull(fvals.get()); - assertEquals(2, fvals.get().size()); - byte[] firstValue = fvals.get().get(0); - byte[] secondValue = fvals.get().get(1); - verifyHasBothValues(firstValue, secondValue, "v111".getBytes(), "v2222".getBytes()); + assertNotNull(fvals.get()); + assertEquals(2, fvals.get().size()); + byte[] firstValue = fvals.get().get(0); + byte[] secondValue = fvals.get().get(1); + verifyHasBothValues(firstValue, secondValue, "v111".getBytes(), + "v2222".getBytes()); } - private void verifyHasBothValues(byte[] firstKey, byte[] secondKey, byte[] value1, byte[] value2) { - assertFalse(Arrays.equals(firstKey, secondKey)); - assertTrue(Arrays.equals(firstKey, value1) || Arrays.equals(firstKey, value2)); - assertTrue(Arrays.equals(secondKey, value1) || Arrays.equals(secondKey, value2)); + private void verifyHasBothValues(byte[] firstKey, byte[] secondKey, + byte[] value1, byte[] value2) { + assertFalse(Arrays.equals(firstKey, secondKey)); + assertTrue(Arrays.equals(firstKey, value1) + || Arrays.equals(firstKey, value2)); + assertTrue(Arrays.equals(secondKey, value1) + || Arrays.equals(secondKey, value2)); } @Test public void pipelineSelect() { - Pipeline p = jedis.pipelined(); - p.select(1); - p.sync(); + Pipeline p = jedis.pipelined(); + p.select(1); + p.sync(); } - + @Test public void pipelineResponseWithoutData() { - jedis.zadd("zset", 1, "foo"); - - Pipeline p = jedis.pipelined(); - Response score = p.zscore("zset", "bar"); - p.sync(); + jedis.zadd("zset", 1, "foo"); - assertNull(score.get()); + Pipeline p = jedis.pipelined(); + Response score = p.zscore("zset", "bar"); + p.sync(); + + assertNull(score.get()); } - @Test(expected = JedisDataException.class) public void pipelineResponseWithinPipeline() { - jedis.set("string", "foo"); + jedis.set("string", "foo"); - Pipeline p = jedis.pipelined(); - Response string = p.get("string"); - string.get(); - p.sync(); + Pipeline p = jedis.pipelined(); + Response string = p.get("string"); + string.get(); + p.sync(); } @Test public void pipelineWithPubSub() { - Pipeline pipelined = jedis.pipelined(); - Response p1 = pipelined.publish("foo", "bar"); - Response p2 = pipelined.publish("foo".getBytes(), "bar" - .getBytes()); - pipelined.sync(); - assertEquals(0, p1.get().longValue()); - assertEquals(0, p2.get().longValue()); + Pipeline pipelined = jedis.pipelined(); + Response p1 = pipelined.publish("foo", "bar"); + Response p2 = pipelined.publish("foo".getBytes(), + "bar".getBytes()); + pipelined.sync(); + assertEquals(0, p1.get().longValue()); + assertEquals(0, p2.get().longValue()); } @Test public void canRetrieveUnsetKey() { - Pipeline p = jedis.pipelined(); - Response shouldNotExist = p.get(UUID.randomUUID().toString()); - p.sync(); - assertNull(shouldNotExist.get()); - } - - @Test - public void piplineWithError(){ - Pipeline p = jedis.pipelined(); - p.set("foo", "bar"); - Response> error = p.smembers("foo"); - Response r = p.get("foo"); - p.sync(); - try{ - error.get(); - fail(); - }catch(JedisDataException e){ - //that is fine we should be here - } - assertEquals(r.get(), "bar"); + Pipeline p = jedis.pipelined(); + Response shouldNotExist = p.get(UUID.randomUUID().toString()); + p.sync(); + assertNull(shouldNotExist.get()); } @Test - public void multi(){ - Pipeline p = jedis.pipelined(); - p.multi(); - Response r1 = p.hincrBy("a", "f1", -1); - Response r2 = p.hincrBy("a", "f1", -2); - Response> r3 = p.exec(); - List result = p.syncAndReturnAll(); - - assertEquals(new Long(-1), r1.get()); - assertEquals(new Long(-3), r2.get()); - - assertEquals(4, result.size()); - - assertEquals("OK", result.get(0)); - assertEquals("QUEUED", result.get(1)); - assertEquals("QUEUED", result.get(2)); - - //4th result is a list with the results from the multi - @SuppressWarnings("unchecked") - List multiResult = (List) result.get(3); - assertEquals(new Long(-1), multiResult.get(0)); - assertEquals(new Long(-3), multiResult.get(1)); - - assertEquals(new Long(-1), r3.get().get(0)); - assertEquals(new Long(-3), r3.get().get(1)); + public void piplineWithError() { + Pipeline p = jedis.pipelined(); + p.set("foo", "bar"); + Response> error = p.smembers("foo"); + Response r = p.get("foo"); + p.sync(); + try { + error.get(); + fail(); + } catch (JedisDataException e) { + // that is fine we should be here + } + assertEquals(r.get(), "bar"); + } + + @Test + public void multi() { + Pipeline p = jedis.pipelined(); + p.multi(); + Response r1 = p.hincrBy("a", "f1", -1); + Response r2 = p.hincrBy("a", "f1", -2); + Response> r3 = p.exec(); + List result = p.syncAndReturnAll(); + + assertEquals(new Long(-1), r1.get()); + assertEquals(new Long(-3), r2.get()); + + assertEquals(4, result.size()); + + assertEquals("OK", result.get(0)); + assertEquals("QUEUED", result.get(1)); + assertEquals("QUEUED", result.get(2)); + + // 4th result is a list with the results from the multi + @SuppressWarnings("unchecked") + List multiResult = (List) result.get(3); + assertEquals(new Long(-1), multiResult.get(0)); + assertEquals(new Long(-3), multiResult.get(1)); + + assertEquals(new Long(-1), r3.get().get(0)); + assertEquals(new Long(-3), r3.get().get(1)); } @Test public void testDiscardInPipeline() { - Pipeline pipeline = jedis.pipelined(); - pipeline.multi(); - pipeline.set("foo", "bar"); - Response discard = pipeline.discard(); - Response get = pipeline.get("foo"); - pipeline.sync(); - discard.get(); - get.get(); + Pipeline pipeline = jedis.pipelined(); + pipeline.multi(); + pipeline.set("foo", "bar"); + Response discard = pipeline.discard(); + Response get = pipeline.get("foo"); + pipeline.sync(); + discard.get(); + get.get(); } - - @Test - public void testEval() { - String script = "return 'success!'"; - Pipeline p = jedis.pipelined(); - Response result = p.eval(script); - p.sync(); + @Test + public void testEval() { + String script = "return 'success!'"; - assertEquals("success!", result.get()); - } + Pipeline p = jedis.pipelined(); + Response result = p.eval(script); + p.sync(); - @Test - public void testEvalKeyAndArg() { - String key = "test"; - String arg = "3"; - String script = "redis.call('INCRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[1], ARGV[1])"; + assertEquals("success!", result.get()); + } - Pipeline p = jedis.pipelined(); - p.set(key, "0"); - Response result0 = p.eval(script, Arrays.asList(key), Arrays.asList(arg)); - p.incr(key); - Response result1 = p.eval(script, Arrays.asList(key), Arrays.asList(arg)); - Response result2 = p.get(key); - p.sync(); + @Test + public void testEvalKeyAndArg() { + String key = "test"; + String arg = "3"; + String script = "redis.call('INCRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[1], ARGV[1])"; - assertNull(result0.get()); - assertNull(result1.get()); - assertEquals("13", result2.get()); - } + Pipeline p = jedis.pipelined(); + p.set(key, "0"); + Response result0 = p.eval(script, Arrays.asList(key), + Arrays.asList(arg)); + p.incr(key); + Response result1 = p.eval(script, Arrays.asList(key), + Arrays.asList(arg)); + Response result2 = p.get(key); + p.sync(); - @Test - public void testEvalsha() { - String script = "return 'success!'"; - String sha1 = jedis.scriptLoad(script); + assertNull(result0.get()); + assertNull(result1.get()); + assertEquals("13", result2.get()); + } - assertTrue(jedis.scriptExists(sha1)); + @Test + public void testEvalsha() { + String script = "return 'success!'"; + String sha1 = jedis.scriptLoad(script); - Pipeline p = jedis.pipelined(); - Response result = p.evalsha(sha1); - p.sync(); + assertTrue(jedis.scriptExists(sha1)); - assertEquals("success!", result.get()); - } + Pipeline p = jedis.pipelined(); + Response result = p.evalsha(sha1); + p.sync(); - @Test - public void testEvalshaKeyAndArg() { - String key = "test"; - String arg = "3"; - String script = "redis.call('INCRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[1], ARGV[1])"; - String sha1 = jedis.scriptLoad(script); + assertEquals("success!", result.get()); + } - assertTrue(jedis.scriptExists(sha1)); + @Test + public void testEvalshaKeyAndArg() { + String key = "test"; + String arg = "3"; + String script = "redis.call('INCRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[1], ARGV[1])"; + String sha1 = jedis.scriptLoad(script); - Pipeline p = jedis.pipelined(); - p.set(key, "0"); - Response result0 = p.evalsha(sha1, Arrays.asList(key), Arrays.asList(arg)); - p.incr(key); - Response result1 = p.evalsha(sha1, Arrays.asList(key), Arrays.asList(arg)); - Response result2 = p.get(key); - p.sync(); + assertTrue(jedis.scriptExists(sha1)); - assertNull(result0.get()); - assertNull(result1.get()); - assertEquals("13", result2.get()); - } + Pipeline p = jedis.pipelined(); + p.set(key, "0"); + Response result0 = p.evalsha(sha1, Arrays.asList(key), + Arrays.asList(arg)); + p.incr(key); + Response result1 = p.evalsha(sha1, Arrays.asList(key), + Arrays.asList(arg)); + Response result2 = p.get(key); + p.sync(); + + assertNull(result0.get()); + assertNull(result1.get()); + assertEquals("13", result2.get()); + } } diff --git a/src/test/java/redis/clients/jedis/tests/ProtocolTest.java b/src/test/java/redis/clients/jedis/tests/ProtocolTest.java index 60b82aa..504a66a 100644 --- a/src/test/java/redis/clients/jedis/tests/ProtocolTest.java +++ b/src/test/java/redis/clients/jedis/tests/ProtocolTest.java @@ -19,86 +19,86 @@ import redis.clients.util.SafeEncoder; public class ProtocolTest extends JedisTestBase { @Test public void buildACommand() throws IOException { - PipedInputStream pis = new PipedInputStream(); - BufferedInputStream bis = new BufferedInputStream(pis); - PipedOutputStream pos = new PipedOutputStream(pis); - RedisOutputStream ros = new RedisOutputStream(pos); + PipedInputStream pis = new PipedInputStream(); + BufferedInputStream bis = new BufferedInputStream(pis); + PipedOutputStream pos = new PipedOutputStream(pis); + RedisOutputStream ros = new RedisOutputStream(pos); - Protocol.sendCommand(ros, Protocol.Command.GET, - "SOMEKEY".getBytes(Protocol.CHARSET)); - ros.flush(); - pos.close(); - String expectedCommand = "*2\r\n$3\r\nGET\r\n$7\r\nSOMEKEY\r\n"; + Protocol.sendCommand(ros, Protocol.Command.GET, + "SOMEKEY".getBytes(Protocol.CHARSET)); + ros.flush(); + pos.close(); + String expectedCommand = "*2\r\n$3\r\nGET\r\n$7\r\nSOMEKEY\r\n"; - int b; - StringBuilder sb = new StringBuilder(); - while ((b = bis.read()) != -1) { - sb.append((char) b); - } + int b; + StringBuilder sb = new StringBuilder(); + while ((b = bis.read()) != -1) { + sb.append((char) b); + } - assertEquals(expectedCommand, sb.toString()); + assertEquals(expectedCommand, sb.toString()); } @Test public void bulkReply() { - InputStream is = new ByteArrayInputStream("$6\r\nfoobar\r\n".getBytes()); - byte[] response = (byte[]) Protocol.read(new RedisInputStream(is)); - assertArrayEquals(SafeEncoder.encode("foobar"), response); + InputStream is = new ByteArrayInputStream("$6\r\nfoobar\r\n".getBytes()); + byte[] response = (byte[]) Protocol.read(new RedisInputStream(is)); + assertArrayEquals(SafeEncoder.encode("foobar"), response); } @Test public void fragmentedBulkReply() { - FragmentedByteArrayInputStream fis = new FragmentedByteArrayInputStream( - "$30\r\n012345678901234567890123456789\r\n".getBytes()); - byte[] response = (byte[]) Protocol.read(new RedisInputStream(fis)); - assertArrayEquals(SafeEncoder.encode("012345678901234567890123456789"), - response); + FragmentedByteArrayInputStream fis = new FragmentedByteArrayInputStream( + "$30\r\n012345678901234567890123456789\r\n".getBytes()); + byte[] response = (byte[]) Protocol.read(new RedisInputStream(fis)); + assertArrayEquals(SafeEncoder.encode("012345678901234567890123456789"), + response); } @Test public void nullBulkReply() { - InputStream is = new ByteArrayInputStream("$-1\r\n".getBytes()); - String response = (String) Protocol.read(new RedisInputStream(is)); - assertEquals(null, response); + InputStream is = new ByteArrayInputStream("$-1\r\n".getBytes()); + String response = (String) Protocol.read(new RedisInputStream(is)); + assertEquals(null, response); } @Test public void singleLineReply() { - InputStream is = new ByteArrayInputStream("+OK\r\n".getBytes()); - byte[] response = (byte[]) Protocol.read(new RedisInputStream(is)); - assertArrayEquals(SafeEncoder.encode("OK"), response); + InputStream is = new ByteArrayInputStream("+OK\r\n".getBytes()); + byte[] response = (byte[]) Protocol.read(new RedisInputStream(is)); + assertArrayEquals(SafeEncoder.encode("OK"), response); } @Test public void integerReply() { - InputStream is = new ByteArrayInputStream(":123\r\n".getBytes()); - long response = (Long) Protocol.read(new RedisInputStream(is)); - assertEquals(123, response); + InputStream is = new ByteArrayInputStream(":123\r\n".getBytes()); + long response = (Long) Protocol.read(new RedisInputStream(is)); + assertEquals(123, response); } @SuppressWarnings("unchecked") @Test public void multiBulkReply() { - InputStream is = new ByteArrayInputStream( - "*4\r\n$3\r\nfoo\r\n$3\r\nbar\r\n$5\r\nHello\r\n$5\r\nWorld\r\n" - .getBytes()); - List response = (List) Protocol - .read(new RedisInputStream(is)); - List expected = new ArrayList(); - expected.add(SafeEncoder.encode("foo")); - expected.add(SafeEncoder.encode("bar")); - expected.add(SafeEncoder.encode("Hello")); - expected.add(SafeEncoder.encode("World")); + InputStream is = new ByteArrayInputStream( + "*4\r\n$3\r\nfoo\r\n$3\r\nbar\r\n$5\r\nHello\r\n$5\r\nWorld\r\n" + .getBytes()); + List response = (List) Protocol + .read(new RedisInputStream(is)); + List expected = new ArrayList(); + expected.add(SafeEncoder.encode("foo")); + expected.add(SafeEncoder.encode("bar")); + expected.add(SafeEncoder.encode("Hello")); + expected.add(SafeEncoder.encode("World")); - assertEquals(expected, response); + assertEquals(expected, response); } @SuppressWarnings("unchecked") @Test public void nullMultiBulkReply() { - InputStream is = new ByteArrayInputStream("*-1\r\n".getBytes()); - List response = (List) Protocol - .read(new RedisInputStream(is)); - assertNull(response); + InputStream is = new ByteArrayInputStream("*-1\r\n".getBytes()); + List response = (List) Protocol + .read(new RedisInputStream(is)); + assertNull(response); } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/ShardedJedisTest.java b/src/test/java/redis/clients/jedis/tests/ShardedJedisTest.java index 73532c7..5a71391 100644 --- a/src/test/java/redis/clients/jedis/tests/ShardedJedisTest.java +++ b/src/test/java/redis/clients/jedis/tests/ShardedJedisTest.java @@ -18,286 +18,288 @@ import redis.clients.util.Sharded; public class ShardedJedisTest extends Assert { private static HostAndPort redis1 = HostAndPortUtil.getRedisServers() - .get(0); + .get(0); private static HostAndPort redis2 = HostAndPortUtil.getRedisServers() - .get(1); + .get(1); private List getKeysDifferentShard(ShardedJedis jedis) { - List ret = new ArrayList(); - JedisShardInfo first = jedis.getShardInfo("a0"); - ret.add("a0"); - for (int i = 1; i < 100; ++i) { - JedisShardInfo actual = jedis.getShardInfo("a" + i); - if (actual != first) { - ret.add("a" + i); - break; + List ret = new ArrayList(); + JedisShardInfo first = jedis.getShardInfo("a0"); + ret.add("a0"); + for (int i = 1; i < 100; ++i) { + JedisShardInfo actual = jedis.getShardInfo("a" + i); + if (actual != first) { + ret.add("a" + i); + break; - } + } - } - return ret; + } + return ret; } @Test public void checkSharding() { - List shards = new ArrayList(); - shards.add(new JedisShardInfo(redis1.getHost(), redis1.getPort())); - shards.add(new JedisShardInfo(redis2.getHost(), redis2.getPort())); - ShardedJedis jedis = new ShardedJedis(shards); - List keys = getKeysDifferentShard(jedis); - JedisShardInfo s1 = jedis.getShardInfo(keys.get(0)); - JedisShardInfo s2 = jedis.getShardInfo(keys.get(1)); - assertNotSame(s1, s2); + List shards = new ArrayList(); + shards.add(new JedisShardInfo(redis1.getHost(), redis1.getPort())); + shards.add(new JedisShardInfo(redis2.getHost(), redis2.getPort())); + ShardedJedis jedis = new ShardedJedis(shards); + List keys = getKeysDifferentShard(jedis); + JedisShardInfo s1 = jedis.getShardInfo(keys.get(0)); + JedisShardInfo s2 = jedis.getShardInfo(keys.get(1)); + assertNotSame(s1, s2); } @Test public void trySharding() { - List shards = new ArrayList(); - JedisShardInfo si = new JedisShardInfo(redis1.getHost(), redis1.getPort()); - si.setPassword("foobared"); - shards.add(si); - si = new JedisShardInfo(redis2.getHost(), redis2.getPort()); - si.setPassword("foobared"); - shards.add(si); - ShardedJedis jedis = new ShardedJedis(shards); - jedis.set("a", "bar"); - JedisShardInfo s1 = jedis.getShardInfo("a"); - jedis.set("b", "bar1"); - JedisShardInfo s2 = jedis.getShardInfo("b"); - jedis.disconnect(); + List shards = new ArrayList(); + JedisShardInfo si = new JedisShardInfo(redis1.getHost(), + redis1.getPort()); + si.setPassword("foobared"); + shards.add(si); + si = new JedisShardInfo(redis2.getHost(), redis2.getPort()); + si.setPassword("foobared"); + shards.add(si); + ShardedJedis jedis = new ShardedJedis(shards); + jedis.set("a", "bar"); + JedisShardInfo s1 = jedis.getShardInfo("a"); + jedis.set("b", "bar1"); + JedisShardInfo s2 = jedis.getShardInfo("b"); + jedis.disconnect(); - Jedis j = new Jedis(s1.getHost(), s1.getPort()); - j.auth("foobared"); - assertEquals("bar", j.get("a")); - j.disconnect(); + Jedis j = new Jedis(s1.getHost(), s1.getPort()); + j.auth("foobared"); + assertEquals("bar", j.get("a")); + j.disconnect(); - j = new Jedis(s2.getHost(), s2.getPort()); - j.auth("foobared"); - assertEquals("bar1", j.get("b")); - j.disconnect(); + j = new Jedis(s2.getHost(), s2.getPort()); + j.auth("foobared"); + assertEquals("bar1", j.get("b")); + j.disconnect(); } @Test public void tryShardingWithMurmure() { - List shards = new ArrayList(); - JedisShardInfo si = new JedisShardInfo(redis1.getHost(), redis1.getPort()); - si.setPassword("foobared"); - shards.add(si); - si = new JedisShardInfo(redis2.getHost(), redis2.getPort()); - si.setPassword("foobared"); - shards.add(si); - ShardedJedis jedis = new ShardedJedis(shards, Hashing.MURMUR_HASH); - jedis.set("a", "bar"); - JedisShardInfo s1 = jedis.getShardInfo("a"); - jedis.set("b", "bar1"); - JedisShardInfo s2 = jedis.getShardInfo("b"); - jedis.disconnect(); + List shards = new ArrayList(); + JedisShardInfo si = new JedisShardInfo(redis1.getHost(), + redis1.getPort()); + si.setPassword("foobared"); + shards.add(si); + si = new JedisShardInfo(redis2.getHost(), redis2.getPort()); + si.setPassword("foobared"); + shards.add(si); + ShardedJedis jedis = new ShardedJedis(shards, Hashing.MURMUR_HASH); + jedis.set("a", "bar"); + JedisShardInfo s1 = jedis.getShardInfo("a"); + jedis.set("b", "bar1"); + JedisShardInfo s2 = jedis.getShardInfo("b"); + jedis.disconnect(); - Jedis j = new Jedis(s1.getHost(), s1.getPort()); - j.auth("foobared"); - assertEquals("bar", j.get("a")); - j.disconnect(); + Jedis j = new Jedis(s1.getHost(), s1.getPort()); + j.auth("foobared"); + assertEquals("bar", j.get("a")); + j.disconnect(); - j = new Jedis(s2.getHost(), s2.getPort()); - j.auth("foobared"); - assertEquals("bar1", j.get("b")); - j.disconnect(); + j = new Jedis(s2.getHost(), s2.getPort()); + j.auth("foobared"); + assertEquals("bar1", j.get("b")); + j.disconnect(); } @Test public void checkKeyTags() { - List shards = new ArrayList(); - shards.add(new JedisShardInfo(redis1.getHost(), redis1.getPort())); - shards.add(new JedisShardInfo(redis2.getHost(), redis2.getPort())); - ShardedJedis jedis = new ShardedJedis(shards, - ShardedJedis.DEFAULT_KEY_TAG_PATTERN); + List shards = new ArrayList(); + shards.add(new JedisShardInfo(redis1.getHost(), redis1.getPort())); + shards.add(new JedisShardInfo(redis2.getHost(), redis2.getPort())); + ShardedJedis jedis = new ShardedJedis(shards, + ShardedJedis.DEFAULT_KEY_TAG_PATTERN); - assertEquals(jedis.getKeyTag("foo"), "foo"); - assertEquals(jedis.getKeyTag("foo{bar}"), "bar"); - assertEquals(jedis.getKeyTag("foo{bar}}"), "bar"); // default pattern is - // non greedy - assertEquals(jedis.getKeyTag("{bar}foo"), "bar"); // Key tag may appear - // anywhere - assertEquals(jedis.getKeyTag("f{bar}oo"), "bar"); // Key tag may appear - // anywhere + assertEquals(jedis.getKeyTag("foo"), "foo"); + assertEquals(jedis.getKeyTag("foo{bar}"), "bar"); + assertEquals(jedis.getKeyTag("foo{bar}}"), "bar"); // default pattern is + // non greedy + assertEquals(jedis.getKeyTag("{bar}foo"), "bar"); // Key tag may appear + // anywhere + assertEquals(jedis.getKeyTag("f{bar}oo"), "bar"); // Key tag may appear + // anywhere - JedisShardInfo s1 = jedis.getShardInfo("abc{bar}"); - JedisShardInfo s2 = jedis.getShardInfo("foo{bar}"); - assertSame(s1, s2); + JedisShardInfo s1 = jedis.getShardInfo("abc{bar}"); + JedisShardInfo s2 = jedis.getShardInfo("foo{bar}"); + assertSame(s1, s2); - List keys = getKeysDifferentShard(jedis); - JedisShardInfo s3 = jedis.getShardInfo(keys.get(0)); - JedisShardInfo s4 = jedis.getShardInfo(keys.get(1)); - assertNotSame(s3, s4); + List keys = getKeysDifferentShard(jedis); + JedisShardInfo s3 = jedis.getShardInfo(keys.get(0)); + JedisShardInfo s4 = jedis.getShardInfo(keys.get(1)); + assertNotSame(s3, s4); - ShardedJedis jedis2 = new ShardedJedis(shards); + ShardedJedis jedis2 = new ShardedJedis(shards); - assertEquals(jedis2.getKeyTag("foo"), "foo"); - assertNotSame(jedis2.getKeyTag("foo{bar}"), "bar"); + assertEquals(jedis2.getKeyTag("foo"), "foo"); + assertNotSame(jedis2.getKeyTag("foo{bar}"), "bar"); - JedisShardInfo s5 = jedis2.getShardInfo(keys.get(0) + "{bar}"); - JedisShardInfo s6 = jedis2.getShardInfo(keys.get(1) + "{bar}"); - assertNotSame(s5, s6); + JedisShardInfo s5 = jedis2.getShardInfo(keys.get(0) + "{bar}"); + JedisShardInfo s6 = jedis2.getShardInfo(keys.get(1) + "{bar}"); + assertNotSame(s5, s6); } @Test public void shardedPipeline() { - List shards = new ArrayList(); - shards.add(new JedisShardInfo(redis1.getHost(), redis1.getPort())); - shards.add(new JedisShardInfo(redis2.getHost(), redis2.getPort())); - shards.get(0).setPassword("foobared"); - shards.get(1).setPassword("foobared"); - ShardedJedis jedis = new ShardedJedis(shards); + List shards = new ArrayList(); + shards.add(new JedisShardInfo(redis1.getHost(), redis1.getPort())); + shards.add(new JedisShardInfo(redis2.getHost(), redis2.getPort())); + shards.get(0).setPassword("foobared"); + shards.get(1).setPassword("foobared"); + ShardedJedis jedis = new ShardedJedis(shards); - final List keys = getKeysDifferentShard(jedis); - jedis.set(keys.get(0), "a"); - jedis.set(keys.get(1), "b"); + final List keys = getKeysDifferentShard(jedis); + jedis.set(keys.get(0), "a"); + jedis.set(keys.get(1), "b"); - assertNotSame(jedis.getShard(keys.get(0)), jedis.getShard(keys.get(1))); + assertNotSame(jedis.getShard(keys.get(0)), jedis.getShard(keys.get(1))); - List results = jedis.pipelined(new ShardedJedisPipeline() { - public void execute() { - get(keys.get(0)); - get(keys.get(1)); - } - }); + List results = jedis.pipelined(new ShardedJedisPipeline() { + public void execute() { + get(keys.get(0)); + get(keys.get(1)); + } + }); - List expected = new ArrayList(2); - expected.add(SafeEncoder.encode("a")); - expected.add(SafeEncoder.encode("b")); + List expected = new ArrayList(2); + expected.add(SafeEncoder.encode("a")); + expected.add(SafeEncoder.encode("b")); - assertEquals(2, results.size()); - assertArrayEquals(SafeEncoder.encode("a"), (byte[]) results.get(0)); - assertArrayEquals(SafeEncoder.encode("b"), (byte[]) results.get(1)); + assertEquals(2, results.size()); + assertArrayEquals(SafeEncoder.encode("a"), (byte[]) results.get(0)); + assertArrayEquals(SafeEncoder.encode("b"), (byte[]) results.get(1)); } @Test public void testMD5Sharding() { - List shards = new ArrayList(3); - shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT)); - shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1)); - shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2)); - Sharded sharded = new Sharded( - shards, Hashing.MD5); - int shard_6379 = 0; - int shard_6380 = 0; - int shard_6381 = 0; - for (int i = 0; i < 1000; i++) { - JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer - .toString(i)); - switch (jedisShardInfo.getPort()) { - case 6379: - shard_6379++; - break; - case 6380: - shard_6380++; - break; - case 6381: - shard_6381++; - break; - default: - fail("Attempting to use a non-defined shard!!:" - + jedisShardInfo); - break; - } - } - assertTrue(shard_6379 > 300 && shard_6379 < 400); - assertTrue(shard_6380 > 300 && shard_6380 < 400); - assertTrue(shard_6381 > 300 && shard_6381 < 400); + List shards = new ArrayList(3); + shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT)); + shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1)); + shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2)); + Sharded sharded = new Sharded( + shards, Hashing.MD5); + int shard_6379 = 0; + int shard_6380 = 0; + int shard_6381 = 0; + for (int i = 0; i < 1000; i++) { + JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer + .toString(i)); + switch (jedisShardInfo.getPort()) { + case 6379: + shard_6379++; + break; + case 6380: + shard_6380++; + break; + case 6381: + shard_6381++; + break; + default: + fail("Attempting to use a non-defined shard!!:" + + jedisShardInfo); + break; + } + } + assertTrue(shard_6379 > 300 && shard_6379 < 400); + assertTrue(shard_6380 > 300 && shard_6380 < 400); + assertTrue(shard_6381 > 300 && shard_6381 < 400); } @Test public void testMurmurSharding() { - List shards = new ArrayList(3); - shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT)); - shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1)); - shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2)); - Sharded sharded = new Sharded( - shards, Hashing.MURMUR_HASH); - int shard_6379 = 0; - int shard_6380 = 0; - int shard_6381 = 0; - for (int i = 0; i < 1000; i++) { - JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer - .toString(i)); - switch (jedisShardInfo.getPort()) { - case 6379: - shard_6379++; - break; - case 6380: - shard_6380++; - break; - case 6381: - shard_6381++; - break; - default: - fail("Attempting to use a non-defined shard!!:" - + jedisShardInfo); - break; - } - } - assertTrue(shard_6379 > 300 && shard_6379 < 400); - assertTrue(shard_6380 > 300 && shard_6380 < 400); - assertTrue(shard_6381 > 300 && shard_6381 < 400); + List shards = new ArrayList(3); + shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT)); + shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1)); + shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2)); + Sharded sharded = new Sharded( + shards, Hashing.MURMUR_HASH); + int shard_6379 = 0; + int shard_6380 = 0; + int shard_6381 = 0; + for (int i = 0; i < 1000; i++) { + JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer + .toString(i)); + switch (jedisShardInfo.getPort()) { + case 6379: + shard_6379++; + break; + case 6380: + shard_6380++; + break; + case 6381: + shard_6381++; + break; + default: + fail("Attempting to use a non-defined shard!!:" + + jedisShardInfo); + break; + } + } + assertTrue(shard_6379 > 300 && shard_6379 < 400); + assertTrue(shard_6380 > 300 && shard_6380 < 400); + assertTrue(shard_6381 > 300 && shard_6381 < 400); } @Test public void testMasterSlaveShardingConsistency() { - List shards = new ArrayList(3); - shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT)); - shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1)); - shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2)); - Sharded sharded = new Sharded( - shards, Hashing.MURMUR_HASH); + List shards = new ArrayList(3); + shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT)); + shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1)); + shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2)); + Sharded sharded = new Sharded( + shards, Hashing.MURMUR_HASH); - List otherShards = new ArrayList(3); - otherShards.add(new JedisShardInfo("otherhost", Protocol.DEFAULT_PORT)); - otherShards.add(new JedisShardInfo("otherhost", - Protocol.DEFAULT_PORT + 1)); - otherShards.add(new JedisShardInfo("otherhost", - Protocol.DEFAULT_PORT + 2)); - Sharded sharded2 = new Sharded( - otherShards, Hashing.MURMUR_HASH); + List otherShards = new ArrayList(3); + otherShards.add(new JedisShardInfo("otherhost", Protocol.DEFAULT_PORT)); + otherShards.add(new JedisShardInfo("otherhost", + Protocol.DEFAULT_PORT + 1)); + otherShards.add(new JedisShardInfo("otherhost", + Protocol.DEFAULT_PORT + 2)); + Sharded sharded2 = new Sharded( + otherShards, Hashing.MURMUR_HASH); - for (int i = 0; i < 1000; i++) { - JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer - .toString(i)); - JedisShardInfo jedisShardInfo2 = sharded2.getShardInfo(Integer - .toString(i)); - assertEquals(shards.indexOf(jedisShardInfo), otherShards - .indexOf(jedisShardInfo2)); - } + for (int i = 0; i < 1000; i++) { + JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer + .toString(i)); + JedisShardInfo jedisShardInfo2 = sharded2.getShardInfo(Integer + .toString(i)); + assertEquals(shards.indexOf(jedisShardInfo), + otherShards.indexOf(jedisShardInfo2)); + } } @Test public void testMasterSlaveShardingConsistencyWithShardNaming() { - List shards = new ArrayList(3); - shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT, - "HOST1:1234")); - shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1, - "HOST2:1234")); - shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2, - "HOST3:1234")); - Sharded sharded = new Sharded( - shards, Hashing.MURMUR_HASH); + List shards = new ArrayList(3); + shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT, + "HOST1:1234")); + shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1, + "HOST2:1234")); + shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2, + "HOST3:1234")); + Sharded sharded = new Sharded( + shards, Hashing.MURMUR_HASH); - List otherShards = new ArrayList(3); - otherShards.add(new JedisShardInfo("otherhost", Protocol.DEFAULT_PORT, - "HOST2:1234")); - otherShards.add(new JedisShardInfo("otherhost", - Protocol.DEFAULT_PORT + 1, "HOST3:1234")); - otherShards.add(new JedisShardInfo("otherhost", - Protocol.DEFAULT_PORT + 2, "HOST1:1234")); - Sharded sharded2 = new Sharded( - otherShards, Hashing.MURMUR_HASH); + List otherShards = new ArrayList(3); + otherShards.add(new JedisShardInfo("otherhost", Protocol.DEFAULT_PORT, + "HOST2:1234")); + otherShards.add(new JedisShardInfo("otherhost", + Protocol.DEFAULT_PORT + 1, "HOST3:1234")); + otherShards.add(new JedisShardInfo("otherhost", + Protocol.DEFAULT_PORT + 2, "HOST1:1234")); + Sharded sharded2 = new Sharded( + otherShards, Hashing.MURMUR_HASH); - for (int i = 0; i < 1000; i++) { - JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer - .toString(i)); - JedisShardInfo jedisShardInfo2 = sharded2.getShardInfo(Integer - .toString(i)); - assertEquals(jedisShardInfo.getName(), jedisShardInfo2.getName()); - } + for (int i = 0; i < 1000; i++) { + JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer + .toString(i)); + JedisShardInfo jedisShardInfo2 = sharded2.getShardInfo(Integer + .toString(i)); + assertEquals(jedisShardInfo.getName(), jedisShardInfo2.getName()); + } } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/benchmark/GetSetBenchmark.java b/src/test/java/redis/clients/jedis/tests/benchmark/GetSetBenchmark.java index 9ce403d..4eaa17b 100644 --- a/src/test/java/redis/clients/jedis/tests/benchmark/GetSetBenchmark.java +++ b/src/test/java/redis/clients/jedis/tests/benchmark/GetSetBenchmark.java @@ -9,7 +9,7 @@ import redis.clients.jedis.Jedis; import redis.clients.jedis.tests.HostAndPortUtil; public class GetSetBenchmark { - private static HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); + private static HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); private static final int TOTAL_OPERATIONS = 100000; public static void main(String[] args) throws UnknownHostException, diff --git a/src/test/java/redis/clients/jedis/tests/benchmark/HashingBenchmark.java b/src/test/java/redis/clients/jedis/tests/benchmark/HashingBenchmark.java index 4783754..4c75e5a 100644 --- a/src/test/java/redis/clients/jedis/tests/benchmark/HashingBenchmark.java +++ b/src/test/java/redis/clients/jedis/tests/benchmark/HashingBenchmark.java @@ -19,32 +19,33 @@ public class HashingBenchmark { private static final int TOTAL_OPERATIONS = 100000; public static void main(String[] args) throws UnknownHostException, - IOException { - List shards = new ArrayList(); - JedisShardInfo shard = new JedisShardInfo(hnp1.getHost(), hnp1.getPort()); - shard.setPassword("foobared"); - shards.add(shard); - shard = new JedisShardInfo(hnp2.getHost(), hnp2.getPort()); - shard.setPassword("foobared"); - shards.add(shard); - ShardedJedis jedis = new ShardedJedis(shards); - Collection allShards = jedis.getAllShards(); - for (Jedis j : allShards) { - j.flushAll(); - } + IOException { + List shards = new ArrayList(); + JedisShardInfo shard = new JedisShardInfo(hnp1.getHost(), + hnp1.getPort()); + shard.setPassword("foobared"); + shards.add(shard); + shard = new JedisShardInfo(hnp2.getHost(), hnp2.getPort()); + shard.setPassword("foobared"); + shards.add(shard); + ShardedJedis jedis = new ShardedJedis(shards); + Collection allShards = jedis.getAllShards(); + for (Jedis j : allShards) { + j.flushAll(); + } - long begin = Calendar.getInstance().getTimeInMillis(); + long begin = Calendar.getInstance().getTimeInMillis(); - for (int n = 0; n <= TOTAL_OPERATIONS; n++) { - String key = "foo" + n; - jedis.set(key, "bar" + n); - jedis.get(key); - } + for (int n = 0; n <= TOTAL_OPERATIONS; n++) { + String key = "foo" + n; + jedis.set(key, "bar" + n); + jedis.get(key); + } - long elapsed = Calendar.getInstance().getTimeInMillis() - begin; + long elapsed = Calendar.getInstance().getTimeInMillis() - begin; - jedis.disconnect(); + jedis.disconnect(); - System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops"); + System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops"); } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/benchmark/PipelinedGetSetBenchmark.java b/src/test/java/redis/clients/jedis/tests/benchmark/PipelinedGetSetBenchmark.java index f8c41d7..b783ca4 100644 --- a/src/test/java/redis/clients/jedis/tests/benchmark/PipelinedGetSetBenchmark.java +++ b/src/test/java/redis/clients/jedis/tests/benchmark/PipelinedGetSetBenchmark.java @@ -14,26 +14,26 @@ public class PipelinedGetSetBenchmark { private static final int TOTAL_OPERATIONS = 200000; public static void main(String[] args) throws UnknownHostException, - IOException { - Jedis jedis = new Jedis(hnp.getHost(), hnp.getPort()); - jedis.connect(); - jedis.auth("foobared"); - jedis.flushAll(); + IOException { + Jedis jedis = new Jedis(hnp.getHost(), hnp.getPort()); + jedis.connect(); + jedis.auth("foobared"); + jedis.flushAll(); - long begin = Calendar.getInstance().getTimeInMillis(); + long begin = Calendar.getInstance().getTimeInMillis(); - Pipeline p = jedis.pipelined(); - for (int n = 0; n <= TOTAL_OPERATIONS; n++) { - String key = "foo" + n; - p.set(key, "bar" + n); - p.get(key); - } - p.sync(); + Pipeline p = jedis.pipelined(); + for (int n = 0; n <= TOTAL_OPERATIONS; n++) { + String key = "foo" + n; + p.set(key, "bar" + n); + p.get(key); + } + p.sync(); - long elapsed = Calendar.getInstance().getTimeInMillis() - begin; + long elapsed = Calendar.getInstance().getTimeInMillis() - begin; - jedis.disconnect(); + jedis.disconnect(); - System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops"); + System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops"); } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/benchmark/SafeEncoderBenchmark.java b/src/test/java/redis/clients/jedis/tests/benchmark/SafeEncoderBenchmark.java index bfe1fe9..3444687 100644 --- a/src/test/java/redis/clients/jedis/tests/benchmark/SafeEncoderBenchmark.java +++ b/src/test/java/redis/clients/jedis/tests/benchmark/SafeEncoderBenchmark.java @@ -10,29 +10,29 @@ public class SafeEncoderBenchmark { private static final int TOTAL_OPERATIONS = 10000000; public static void main(String[] args) throws UnknownHostException, - IOException { - long begin = Calendar.getInstance().getTimeInMillis(); + IOException { + long begin = Calendar.getInstance().getTimeInMillis(); - for (int n = 0; n <= TOTAL_OPERATIONS; n++) { - SafeEncoder.encode("foo bar!"); - } + for (int n = 0; n <= TOTAL_OPERATIONS; n++) { + SafeEncoder.encode("foo bar!"); + } - long elapsed = Calendar.getInstance().getTimeInMillis() - begin; + long elapsed = Calendar.getInstance().getTimeInMillis() - begin; - System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed) - + " ops to build byte[]"); + System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed) + + " ops to build byte[]"); - begin = Calendar.getInstance().getTimeInMillis(); + begin = Calendar.getInstance().getTimeInMillis(); - byte[] bytes = "foo bar!".getBytes(); - for (int n = 0; n <= TOTAL_OPERATIONS; n++) { - SafeEncoder.encode(bytes); - } + byte[] bytes = "foo bar!".getBytes(); + for (int n = 0; n <= TOTAL_OPERATIONS; n++) { + SafeEncoder.encode(bytes); + } - elapsed = Calendar.getInstance().getTimeInMillis() - begin; + elapsed = Calendar.getInstance().getTimeInMillis() - begin; - System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed) - + " ops to build Strings"); + System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed) + + " ops to build Strings"); } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/benchmark/ShardedBenchmark.java b/src/test/java/redis/clients/jedis/tests/benchmark/ShardedBenchmark.java index 3fb63ff..ec5fed8 100644 --- a/src/test/java/redis/clients/jedis/tests/benchmark/ShardedBenchmark.java +++ b/src/test/java/redis/clients/jedis/tests/benchmark/ShardedBenchmark.java @@ -10,30 +10,30 @@ public class ShardedBenchmark { private static final int TOTAL_OPERATIONS = 10000000; public static void main(String[] args) throws UnknownHostException, - IOException { + IOException { - long begin = Calendar.getInstance().getTimeInMillis(); + long begin = Calendar.getInstance().getTimeInMillis(); - for (int n = 0; n <= TOTAL_OPERATIONS; n++) { - String key = "foo" + n; - Hashing.MD5.hash(key); - } + for (int n = 0; n <= TOTAL_OPERATIONS; n++) { + String key = "foo" + n; + Hashing.MD5.hash(key); + } - long elapsed = Calendar.getInstance().getTimeInMillis() - begin; + long elapsed = Calendar.getInstance().getTimeInMillis() - begin; - System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed) + " MD5 ops"); + System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed) + " MD5 ops"); - begin = Calendar.getInstance().getTimeInMillis(); + begin = Calendar.getInstance().getTimeInMillis(); - for (int n = 0; n <= TOTAL_OPERATIONS; n++) { - String key = "foo" + n; - Hashing.MURMUR_HASH.hash(key); - } + for (int n = 0; n <= TOTAL_OPERATIONS; n++) { + String key = "foo" + n; + Hashing.MURMUR_HASH.hash(key); + } - elapsed = Calendar.getInstance().getTimeInMillis() - begin; + elapsed = Calendar.getInstance().getTimeInMillis() - begin; - System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed) - + " Murmur ops"); + System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed) + + " Murmur ops"); } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/commands/BinaryValuesCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/BinaryValuesCommandsTest.java index c232dbe..2a09268 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/BinaryValuesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/BinaryValuesCommandsTest.java @@ -1,19 +1,20 @@ package redis.clients.jedis.tests.commands; -import org.junit.Before; -import org.junit.Test; -import redis.clients.jedis.Protocol.Keyword; -import redis.clients.jedis.exceptions.JedisDataException; - import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import org.junit.Before; +import org.junit.Test; + +import redis.clients.jedis.Protocol.Keyword; +import redis.clients.jedis.exceptions.JedisDataException; + public class BinaryValuesCommandsTest extends JedisCommandTestBase { byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; - byte[] bxx = { 0x78, 0x78 }; - byte[] bnx = { 0x6E, 0x78 }; + byte[] bxx = { 0x78, 0x78 }; + byte[] bnx = { 0x6E, 0x78 }; byte[] bex = { 0x65, 0x78 }; byte[] bpx = { 0x70, 0x78 }; long expireSeconds = 2; @@ -22,261 +23,260 @@ public class BinaryValuesCommandsTest extends JedisCommandTestBase { @Before public void startUp() { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); - for (int n = 0; n < 1000; n++) { - sb.append("A"); - } + for (int n = 0; n < 1000; n++) { + sb.append("A"); + } - binaryValue = sb.toString().getBytes(); + binaryValue = sb.toString().getBytes(); } @Test public void setAndGet() { - String status = jedis.set(bfoo, binaryValue); - assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); + String status = jedis.set(bfoo, binaryValue); + assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); - byte[] value = jedis.get(bfoo); - assertTrue(Arrays.equals(binaryValue, value)); + byte[] value = jedis.get(bfoo); + assertTrue(Arrays.equals(binaryValue, value)); - assertNull(jedis.get(bbar)); + assertNull(jedis.get(bbar)); } @Test public void setNxExAndGet() { - String status = jedis.set(bfoo, binaryValue, bnx, bex, expireSeconds); - assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); - byte[] value = jedis.get(bfoo); - assertTrue(Arrays.equals(binaryValue, value)); + String status = jedis.set(bfoo, binaryValue, bnx, bex, expireSeconds); + assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); + byte[] value = jedis.get(bfoo); + assertTrue(Arrays.equals(binaryValue, value)); - assertNull(jedis.get(bbar)); + assertNull(jedis.get(bbar)); } @Test public void setIfNotExistAndGet() { - String status= jedis.set(bfoo, binaryValue); - assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); - // nx should fail if value exists - String statusFail = jedis.set(bfoo, binaryValue, bnx, bex, expireSeconds); - assertNull(statusFail); + String status = jedis.set(bfoo, binaryValue); + assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); + // nx should fail if value exists + String statusFail = jedis.set(bfoo, binaryValue, bnx, bex, + expireSeconds); + assertNull(statusFail); - byte[] value = jedis.get(bfoo); - assertTrue(Arrays.equals(binaryValue, value)); + byte[] value = jedis.get(bfoo); + assertTrue(Arrays.equals(binaryValue, value)); - assertNull(jedis.get(bbar)); + assertNull(jedis.get(bbar)); } @Test public void setIfExistAndGet() { - String status= jedis.set(bfoo, binaryValue); - assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); - // nx should fail if value exists - String statusSuccess = jedis.set(bfoo, binaryValue, bxx, bex, expireSeconds); - assertTrue(Keyword.OK.name().equalsIgnoreCase(statusSuccess)); + String status = jedis.set(bfoo, binaryValue); + assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); + // nx should fail if value exists + String statusSuccess = jedis.set(bfoo, binaryValue, bxx, bex, + expireSeconds); + assertTrue(Keyword.OK.name().equalsIgnoreCase(statusSuccess)); - byte[] value = jedis.get(bfoo); - assertTrue(Arrays.equals(binaryValue, value)); + byte[] value = jedis.get(bfoo); + assertTrue(Arrays.equals(binaryValue, value)); - assertNull(jedis.get(bbar)); + assertNull(jedis.get(bbar)); } @Test public void setFailIfNotExistAndGet() { - // xx should fail if value does NOT exists - String statusFail = jedis.set(bfoo, binaryValue, bxx, bex, expireSeconds); - assertNull(statusFail); + // xx should fail if value does NOT exists + String statusFail = jedis.set(bfoo, binaryValue, bxx, bex, + expireSeconds); + assertNull(statusFail); } @Test public void setAndExpireMillis() { - String status = jedis.set(bfoo, binaryValue, bnx, bpx, expireMillis); - assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); - long ttl = jedis.ttl(bfoo); - assertTrue(ttl > 0 && ttl <= expireSeconds); + String status = jedis.set(bfoo, binaryValue, bnx, bpx, expireMillis); + assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); + long ttl = jedis.ttl(bfoo); + assertTrue(ttl > 0 && ttl <= expireSeconds); } - @Test public void setAndExpire() { - String status = jedis.set(bfoo, binaryValue, bnx, bex, expireSeconds); - assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); - long ttl = jedis.ttl(bfoo); - assertTrue(ttl > 0 && ttl <= expireSeconds); + String status = jedis.set(bfoo, binaryValue, bnx, bex, expireSeconds); + assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); + long ttl = jedis.ttl(bfoo); + assertTrue(ttl > 0 && ttl <= expireSeconds); } - @Test public void getSet() { - byte[] value = jedis.getSet(bfoo, binaryValue); - assertNull(value); - value = jedis.get(bfoo); - assertTrue(Arrays.equals(binaryValue, value)); + byte[] value = jedis.getSet(bfoo, binaryValue); + assertNull(value); + value = jedis.get(bfoo); + assertTrue(Arrays.equals(binaryValue, value)); } @Test public void mget() { - List values = jedis.mget(bfoo, bbar); - List expected = new ArrayList(); - expected.add(null); - expected.add(null); + List values = jedis.mget(bfoo, bbar); + List expected = new ArrayList(); + expected.add(null); + expected.add(null); - assertEquals(expected, values); + assertEquals(expected, values); - jedis.set(bfoo, binaryValue); + jedis.set(bfoo, binaryValue); - expected = new ArrayList(); - expected.add(binaryValue); - expected.add(null); - values = jedis.mget(bfoo, bbar); + expected = new ArrayList(); + expected.add(binaryValue); + expected.add(null); + values = jedis.mget(bfoo, bbar); - assertEquals(expected, values); + assertEquals(expected, values); - jedis.set(bbar, bfoo); + jedis.set(bbar, bfoo); - expected = new ArrayList(); - expected.add(binaryValue); - expected.add(bfoo); - values = jedis.mget(bfoo, bbar); + expected = new ArrayList(); + expected.add(binaryValue); + expected.add(bfoo); + values = jedis.mget(bfoo, bbar); - assertEquals(expected, values); + assertEquals(expected, values); } @Test public void setnx() { - long status = jedis.setnx(bfoo, binaryValue); - assertEquals(1, status); - assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo))); + long status = jedis.setnx(bfoo, binaryValue); + assertEquals(1, status); + assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo))); - status = jedis.setnx(bfoo, bbar); - assertEquals(0, status); - assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo))); + status = jedis.setnx(bfoo, bbar); + assertEquals(0, status); + assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo))); } @Test public void setex() { - String status = jedis.setex(bfoo, 20, binaryValue); - assertEquals(Keyword.OK.name(), status); - long ttl = jedis.ttl(bfoo); - assertTrue(ttl > 0 && ttl <= 20); + String status = jedis.setex(bfoo, 20, binaryValue); + assertEquals(Keyword.OK.name(), status); + long ttl = jedis.ttl(bfoo); + assertTrue(ttl > 0 && ttl <= 20); } @Test public void mset() { - String status = jedis.mset(bfoo, binaryValue, bbar, bfoo); - assertEquals(Keyword.OK.name(), status); - assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo))); - assertTrue(Arrays.equals(bfoo, jedis.get(bbar))); + String status = jedis.mset(bfoo, binaryValue, bbar, bfoo); + assertEquals(Keyword.OK.name(), status); + assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo))); + assertTrue(Arrays.equals(bfoo, jedis.get(bbar))); } @Test public void msetnx() { - long status = jedis.msetnx(bfoo, binaryValue, bbar, bfoo); - assertEquals(1, status); - assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo))); - assertTrue(Arrays.equals(bfoo, jedis.get(bbar))); + long status = jedis.msetnx(bfoo, binaryValue, bbar, bfoo); + assertEquals(1, status); + assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo))); + assertTrue(Arrays.equals(bfoo, jedis.get(bbar))); - status = jedis.msetnx(bfoo, bbar, "bar2".getBytes(), "foo2".getBytes()); - assertEquals(0, status); - assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo))); - assertTrue(Arrays.equals(bfoo, jedis.get(bbar))); + status = jedis.msetnx(bfoo, bbar, "bar2".getBytes(), "foo2".getBytes()); + assertEquals(0, status); + assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo))); + assertTrue(Arrays.equals(bfoo, jedis.get(bbar))); } @Test(expected = JedisDataException.class) public void incrWrongValue() { - jedis.set(bfoo, binaryValue); - jedis.incr(bfoo); + jedis.set(bfoo, binaryValue); + jedis.incr(bfoo); } @Test public void incr() { - long value = jedis.incr(bfoo); - assertEquals(1, value); - value = jedis.incr(bfoo); - assertEquals(2, value); + long value = jedis.incr(bfoo); + assertEquals(1, value); + value = jedis.incr(bfoo); + assertEquals(2, value); } @Test(expected = JedisDataException.class) public void incrByWrongValue() { - jedis.set(bfoo, binaryValue); - jedis.incrBy(bfoo, 2); + jedis.set(bfoo, binaryValue); + jedis.incrBy(bfoo, 2); } @Test public void incrBy() { - long value = jedis.incrBy(bfoo, 2); - assertEquals(2, value); - value = jedis.incrBy(bfoo, 2); - assertEquals(4, value); + long value = jedis.incrBy(bfoo, 2); + assertEquals(2, value); + value = jedis.incrBy(bfoo, 2); + assertEquals(4, value); } @Test(expected = JedisDataException.class) public void decrWrongValue() { - jedis.set(bfoo, binaryValue); - jedis.decr(bfoo); + jedis.set(bfoo, binaryValue); + jedis.decr(bfoo); } @Test public void decr() { - long value = jedis.decr(bfoo); - assertEquals(-1, value); - value = jedis.decr(bfoo); - assertEquals(-2, value); + long value = jedis.decr(bfoo); + assertEquals(-1, value); + value = jedis.decr(bfoo); + assertEquals(-2, value); } @Test(expected = JedisDataException.class) public void decrByWrongValue() { - jedis.set(bfoo, binaryValue); - jedis.decrBy(bfoo, 2); + jedis.set(bfoo, binaryValue); + jedis.decrBy(bfoo, 2); } @Test public void decrBy() { - long value = jedis.decrBy(bfoo, 2); - assertEquals(-2, value); - value = jedis.decrBy(bfoo, 2); - assertEquals(-4, value); + long value = jedis.decrBy(bfoo, 2); + assertEquals(-2, value); + value = jedis.decrBy(bfoo, 2); + assertEquals(-4, value); } @Test public void append() { - byte[] first512 = new byte[512]; - System.arraycopy(binaryValue, 0, first512, 0, 512); - long value = jedis.append(bfoo, first512); - assertEquals(512, value); - assertTrue(Arrays.equals(first512, jedis.get(bfoo))); + byte[] first512 = new byte[512]; + System.arraycopy(binaryValue, 0, first512, 0, 512); + long value = jedis.append(bfoo, first512); + assertEquals(512, value); + assertTrue(Arrays.equals(first512, jedis.get(bfoo))); - byte[] rest = new byte[binaryValue.length - 512]; - System.arraycopy(binaryValue, 512, rest, 0, binaryValue.length - 512); - value = jedis.append(bfoo, rest); - assertEquals(binaryValue.length, value); + byte[] rest = new byte[binaryValue.length - 512]; + System.arraycopy(binaryValue, 512, rest, 0, binaryValue.length - 512); + value = jedis.append(bfoo, rest); + assertEquals(binaryValue.length, value); - assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo))); + assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo))); } @Test public void substr() { - jedis.set(bfoo, binaryValue); + jedis.set(bfoo, binaryValue); - byte[] first512 = new byte[512]; - System.arraycopy(binaryValue, 0, first512, 0, 512); - byte[] rfirst512 = jedis.substr(bfoo, 0, 511); - assertTrue(Arrays.equals(first512, rfirst512)); + byte[] first512 = new byte[512]; + System.arraycopy(binaryValue, 0, first512, 0, 512); + byte[] rfirst512 = jedis.substr(bfoo, 0, 511); + assertTrue(Arrays.equals(first512, rfirst512)); - byte[] last512 = new byte[512]; - System - .arraycopy(binaryValue, binaryValue.length - 512, last512, 0, - 512); - assertTrue(Arrays.equals(last512, jedis.substr(bfoo, -512, -1))); + byte[] last512 = new byte[512]; + System.arraycopy(binaryValue, binaryValue.length - 512, last512, 0, 512); + assertTrue(Arrays.equals(last512, jedis.substr(bfoo, -512, -1))); - assertTrue(Arrays.equals(binaryValue, jedis.substr(bfoo, 0, -1))); + assertTrue(Arrays.equals(binaryValue, jedis.substr(bfoo, 0, -1))); - assertTrue(Arrays.equals(last512, jedis.substr(bfoo, - binaryValue.length - 512, 100000))); + assertTrue(Arrays.equals(last512, + jedis.substr(bfoo, binaryValue.length - 512, 100000))); } @Test public void strlen() { - jedis.set(bfoo, binaryValue); - assertEquals(binaryValue.length, jedis.strlen(bfoo).intValue()); + jedis.set(bfoo, binaryValue); + assertEquals(binaryValue.length, jedis.strlen(bfoo).intValue()); } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/commands/BitCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/BitCommandsTest.java index 87b044f..fb14f21 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/BitCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/BitCommandsTest.java @@ -7,87 +7,85 @@ import redis.clients.jedis.BitOP; public class BitCommandsTest extends JedisCommandTestBase { @Test public void setAndgetbit() { - boolean bit = jedis.setbit("foo", 0, true); - assertEquals(false, bit); + boolean bit = jedis.setbit("foo", 0, true); + assertEquals(false, bit); - bit = jedis.getbit("foo", 0); - assertEquals(true, bit); + bit = jedis.getbit("foo", 0); + assertEquals(true, bit); - boolean bbit = jedis.setbit("bfoo".getBytes(), 0, "1".getBytes()); - assertFalse(bbit); + boolean bbit = jedis.setbit("bfoo".getBytes(), 0, "1".getBytes()); + assertFalse(bbit); - bbit = jedis.getbit("bfoo".getBytes(), 0); - assertTrue(bbit); + bbit = jedis.getbit("bfoo".getBytes(), 0); + assertTrue(bbit); } @Test public void setAndgetrange() { - jedis.set("key1", "Hello World"); - long reply = jedis.setrange("key1", 6, "Jedis"); - assertEquals(11, reply); + jedis.set("key1", "Hello World"); + long reply = jedis.setrange("key1", 6, "Jedis"); + assertEquals(11, reply); - assertEquals(jedis.get("key1"), "Hello Jedis"); + assertEquals(jedis.get("key1"), "Hello Jedis"); - assertEquals("Hello", jedis.getrange("key1", 0, 4)); - assertEquals("Jedis", jedis.getrange("key1", 6, 11)); + assertEquals("Hello", jedis.getrange("key1", 0, 4)); + assertEquals("Jedis", jedis.getrange("key1", 6, 11)); } @Test public void bitCount() { - jedis.del("foo"); + jedis.del("foo"); - jedis.setbit("foo", 16, true); - jedis.setbit("foo", 24, true); - jedis.setbit("foo", 40, true); - jedis.setbit("foo", 56, true); + jedis.setbit("foo", 16, true); + jedis.setbit("foo", 24, true); + jedis.setbit("foo", 40, true); + jedis.setbit("foo", 56, true); - long c4 = jedis.bitcount("foo"); - assertEquals(4, c4); + long c4 = jedis.bitcount("foo"); + assertEquals(4, c4); - long c3 = jedis.bitcount("foo", 2L, 5L); - assertEquals(3, c3); + long c3 = jedis.bitcount("foo", 2L, 5L); + assertEquals(3, c3); - jedis.del("foo"); + jedis.del("foo"); } @Test - public void bitOp() - { - jedis.set("key1", "\u0060"); - jedis.set("key2", "\u0044"); + public void bitOp() { + jedis.set("key1", "\u0060"); + jedis.set("key2", "\u0044"); - jedis.bitop(BitOP.AND, "resultAnd", "key1", "key2"); - String resultAnd = jedis.get("resultAnd"); - assertEquals("\u0040", resultAnd); + jedis.bitop(BitOP.AND, "resultAnd", "key1", "key2"); + String resultAnd = jedis.get("resultAnd"); + assertEquals("\u0040", resultAnd); - jedis.bitop(BitOP.OR, "resultOr", "key1", "key2"); - String resultOr = jedis.get("resultOr"); - assertEquals("\u0064", resultOr); + jedis.bitop(BitOP.OR, "resultOr", "key1", "key2"); + String resultOr = jedis.get("resultOr"); + assertEquals("\u0064", resultOr); - jedis.bitop(BitOP.XOR, "resultXor", "key1", "key2"); - String resultXor = jedis.get("resultXor"); - assertEquals("\u0024", resultXor); + jedis.bitop(BitOP.XOR, "resultXor", "key1", "key2"); + String resultXor = jedis.get("resultXor"); + assertEquals("\u0024", resultXor); - jedis.del("resultAnd"); - jedis.del("resultOr"); - jedis.del("resultXor"); - jedis.del("key1"); - jedis.del("key2"); + jedis.del("resultAnd"); + jedis.del("resultOr"); + jedis.del("resultXor"); + jedis.del("key1"); + jedis.del("key2"); } @Test - public void bitOpNot() - { - jedis.del("key"); - jedis.setbit("key", 0, true); - jedis.setbit("key", 4, true); + public void bitOpNot() { + jedis.del("key"); + jedis.setbit("key", 0, true); + jedis.setbit("key", 4, true); - jedis.bitop(BitOP.NOT, "resultNot", "key"); + jedis.bitop(BitOP.NOT, "resultNot", "key"); - String resultNot = jedis.get("resultNot"); - assertEquals("\u0077", resultNot); + String resultNot = jedis.get("resultNot"); + assertEquals("\u0077", resultNot); - jedis.del("key"); - jedis.del("resultNot"); + jedis.del("key"); + jedis.del("resultNot"); } } diff --git a/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java index a7045a6..d2bc584 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java @@ -37,42 +37,45 @@ public class ClusterCommandsTest extends JedisTestBase { node1.disconnect(); node2.disconnect(); } - + @AfterClass public static void removeSlots() throws InterruptedException { - //This is to wait for gossip to replicate data. - waitForEqualClusterSize(); - String[] nodes = node1.clusterNodes().split("\n"); - String node1Id = nodes[0].split(" ")[0]; - node1.clusterDelSlots(1,2,3,4,5,500); - node1.clusterSetSlotNode(5000, node1Id); - node1.clusterDelSlots(5000, 10000); - node1.clusterDelSlots(6000); - node2.clusterDelSlots(6000,1,2,3,4,5,500,5000); - try { - node2.clusterDelSlots(10000); - } catch (JedisDataException jde) { - //Do nothing, slot may or may not be assigned depending on gossip - } + // This is to wait for gossip to replicate data. + waitForEqualClusterSize(); + String[] nodes = node1.clusterNodes().split("\n"); + String node1Id = nodes[0].split(" ")[0]; + node1.clusterDelSlots(1, 2, 3, 4, 5, 500); + node1.clusterSetSlotNode(5000, node1Id); + node1.clusterDelSlots(5000, 10000); + node1.clusterDelSlots(6000); + node2.clusterDelSlots(6000, 1, 2, 3, 4, 5, 500, 5000); + try { + node2.clusterDelSlots(10000); + } catch (JedisDataException jde) { + // Do nothing, slot may or may not be assigned depending on gossip + } } private static void waitForEqualClusterSize() throws InterruptedException { - boolean notEqualSize = true; - while (notEqualSize) { - notEqualSize = getClusterAttribute(node1.clusterInfo(), "cluster_known_nodes") == getClusterAttribute(node2.clusterInfo(), "cluster_size") ? false : true; - } + boolean notEqualSize = true; + while (notEqualSize) { + notEqualSize = getClusterAttribute(node1.clusterInfo(), + "cluster_known_nodes") == getClusterAttribute( + node2.clusterInfo(), "cluster_size") ? false : true; } + } - private static int getClusterAttribute(String clusterInfo, String attributeName) { - for (String infoElement: clusterInfo.split("\n")) { - if (infoElement.contains(attributeName)) { - return Integer.valueOf(infoElement.split(":")[1].trim()); - } - } - return 0; + private static int getClusterAttribute(String clusterInfo, + String attributeName) { + for (String infoElement : clusterInfo.split("\n")) { + if (infoElement.contains(attributeName)) { + return Integer.valueOf(infoElement.split(":")[1].trim()); + } } + return 0; + } - @Test + @Test public void clusterNodes() { String nodes = node1.clusterNodes(); assertTrue(nodes.split("\n").length > 0); diff --git a/src/test/java/redis/clients/jedis/tests/commands/ConnectionHandlingCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/ConnectionHandlingCommandsTest.java index c6d91c2..1201e8c 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ConnectionHandlingCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ConnectionHandlingCommandsTest.java @@ -11,12 +11,12 @@ public class ConnectionHandlingCommandsTest extends JedisCommandTestBase { @Test public void quit() { - assertEquals("OK", jedis.quit()); + assertEquals("OK", jedis.quit()); } @Test public void binary_quit() { - BinaryJedis bj = new BinaryJedis(hnp.getHost()); - assertEquals("OK", bj.quit()); + BinaryJedis bj = new BinaryJedis(hnp.getHost()); + assertEquals("OK", bj.quit()); } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/commands/ControlCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/ControlCommandsTest.java index bba56c1..59ec6bc 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ControlCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ControlCommandsTest.java @@ -61,11 +61,11 @@ public class ControlCommandsTest extends JedisCommandTestBase { public void monitor() { new Thread(new Runnable() { public void run() { - try { - // sleep 100ms to make sure that monitor thread runs first - Thread.sleep(100); - } catch (InterruptedException e) { - } + try { + // sleep 100ms to make sure that monitor thread runs first + Thread.sleep(100); + } catch (InterruptedException e) { + } Jedis j = new Jedis("localhost"); j.auth("foobared"); for (int i = 0; i < 5; i++) { @@ -117,10 +117,10 @@ public class ControlCommandsTest extends JedisCommandTestBase { resp = jedis.debug(DebugParams.RELOAD()); assertNotNull(resp); } - + @Test public void waitReplicas() { Long replicas = jedis.waitReplicas(1, 100); - assertEquals(1, replicas.longValue()); + assertEquals(1, replicas.longValue()); } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java index c7ef2c7..1210259 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java @@ -309,7 +309,8 @@ public class HashesCommandsTest extends JedisCommandTestBase { jedis.hset("foo", "b", "b"); jedis.hset("foo", "a", "a"); jedis.hset("foo", "aa", "aa"); - ScanResult> result = jedis.hscan("foo", 0, params); + ScanResult> result = jedis.hscan("foo", 0, + params); assertEquals(0, result.getCursor()); assertFalse(result.getResult().isEmpty()); @@ -324,7 +325,8 @@ public class HashesCommandsTest extends JedisCommandTestBase { jedis.hset("foo", "a" + i, "a" + i); } - ScanResult> result = jedis.hscan("foo", 0, params); + ScanResult> result = jedis.hscan("foo", 0, + params); assertFalse(result.getResult().isEmpty()); } diff --git a/src/test/java/redis/clients/jedis/tests/commands/JedisCommandTestBase.java b/src/test/java/redis/clients/jedis/tests/commands/JedisCommandTestBase.java index bf787f9..c6f8d69 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/JedisCommandTestBase.java +++ b/src/test/java/redis/clients/jedis/tests/commands/JedisCommandTestBase.java @@ -20,77 +20,77 @@ public abstract class JedisCommandTestBase extends JedisTestBase { protected Jedis jedis; public JedisCommandTestBase() { - super(); + super(); } @Before public void setUp() throws Exception { - jedis = new Jedis(hnp.getHost(), hnp.getPort(), 500); - jedis.connect(); - jedis.auth("foobared"); - jedis.configSet("timeout", "300"); - jedis.flushAll(); + jedis = new Jedis(hnp.getHost(), hnp.getPort(), 500); + jedis.connect(); + jedis.auth("foobared"); + jedis.configSet("timeout", "300"); + jedis.flushAll(); } @After public void tearDown() { - jedis.disconnect(); + jedis.disconnect(); } protected Jedis createJedis() { - Jedis j = new Jedis(hnp.getHost(), hnp.getPort()); - j.connect(); - j.auth("foobared"); - j.flushAll(); - return j; + Jedis j = new Jedis(hnp.getHost(), hnp.getPort()); + j.connect(); + j.auth("foobared"); + j.flushAll(); + return j; } protected void assertEquals(List expected, List actual) { - assertEquals(expected.size(), actual.size()); - for (int n = 0; n < expected.size(); n++) { - assertArrayEquals(expected.get(n), actual.get(n)); - } + assertEquals(expected.size(), actual.size()); + for (int n = 0; n < expected.size(); n++) { + assertArrayEquals(expected.get(n), actual.get(n)); + } } protected void assertEquals(Set expected, Set actual) { - assertEquals(expected.size(), actual.size()); - Iterator e = expected.iterator(); - while (e.hasNext()) { - byte[] next = e.next(); - boolean contained = false; - for (byte[] element : expected) { - if (Arrays.equals(next, element)) { - contained = true; - } - } - if (!contained) { - throw new ComparisonFailure("element is missing", - Arrays.toString(next), actual.toString()); - } - } + assertEquals(expected.size(), actual.size()); + Iterator e = expected.iterator(); + while (e.hasNext()) { + byte[] next = e.next(); + boolean contained = false; + for (byte[] element : expected) { + if (Arrays.equals(next, element)) { + contained = true; + } + } + if (!contained) { + throw new ComparisonFailure("element is missing", + Arrays.toString(next), actual.toString()); + } + } } protected boolean arrayContains(List array, byte[] expected) { - for (byte[] a : array) { - try { - assertArrayEquals(a, expected); - return true; - } catch (AssertionError e) { + for (byte[] a : array) { + try { + assertArrayEquals(a, expected); + return true; + } catch (AssertionError e) { - } - } - return false; + } + } + return false; } protected boolean setContains(Set set, byte[] expected) { - for (byte[] a : set) { - try { - assertArrayEquals(a, expected); - return true; - } catch (AssertionError e) { + for (byte[] a : set) { + try { + assertArrayEquals(a, expected); + return true; + } catch (AssertionError e) { - } - } - return false; + } + } + return false; } } diff --git a/src/test/java/redis/clients/jedis/tests/commands/ListCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/ListCommandsTest.java index 296877b..ce157d8 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ListCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ListCommandsTest.java @@ -26,561 +26,559 @@ public class ListCommandsTest extends JedisCommandTestBase { @Test public void rpush() { - long size = jedis.rpush("foo", "bar"); - assertEquals(1, size); - size = jedis.rpush("foo", "foo"); - assertEquals(2, size); - size = jedis.rpush("foo", "bar", "foo"); - assertEquals(4, size); - + long size = jedis.rpush("foo", "bar"); + assertEquals(1, size); + size = jedis.rpush("foo", "foo"); + assertEquals(2, size); + size = jedis.rpush("foo", "bar", "foo"); + assertEquals(4, size); - // Binary - long bsize = jedis.rpush(bfoo, bbar); - assertEquals(1, bsize); - bsize = jedis.rpush(bfoo, bfoo); - assertEquals(2, bsize); - bsize = jedis.rpush(bfoo, bbar, bfoo); - assertEquals(4, bsize); + // Binary + long bsize = jedis.rpush(bfoo, bbar); + assertEquals(1, bsize); + bsize = jedis.rpush(bfoo, bfoo); + assertEquals(2, bsize); + bsize = jedis.rpush(bfoo, bbar, bfoo); + assertEquals(4, bsize); } @Test public void lpush() { - long size = jedis.lpush("foo", "bar"); - assertEquals(1, size); - size = jedis.lpush("foo", "foo"); - assertEquals(2, size); - size = jedis.lpush("foo", "bar", "foo"); - assertEquals(4, size); + long size = jedis.lpush("foo", "bar"); + assertEquals(1, size); + size = jedis.lpush("foo", "foo"); + assertEquals(2, size); + size = jedis.lpush("foo", "bar", "foo"); + assertEquals(4, size); - // Binary - long bsize = jedis.lpush(bfoo, bbar); - assertEquals(1, bsize); - bsize = jedis.lpush(bfoo, bfoo); - assertEquals(2, bsize); - bsize = jedis.lpush(bfoo, bbar, bfoo); - assertEquals(4, bsize); + // Binary + long bsize = jedis.lpush(bfoo, bbar); + assertEquals(1, bsize); + bsize = jedis.lpush(bfoo, bfoo); + assertEquals(2, bsize); + bsize = jedis.lpush(bfoo, bbar, bfoo); + assertEquals(4, bsize); } @Test public void llen() { - assertEquals(0, jedis.llen("foo").intValue()); - jedis.lpush("foo", "bar"); - jedis.lpush("foo", "car"); - assertEquals(2, jedis.llen("foo").intValue()); + assertEquals(0, jedis.llen("foo").intValue()); + jedis.lpush("foo", "bar"); + jedis.lpush("foo", "car"); + assertEquals(2, jedis.llen("foo").intValue()); - // Binary - assertEquals(0, jedis.llen(bfoo).intValue()); - jedis.lpush(bfoo, bbar); - jedis.lpush(bfoo, bcar); - assertEquals(2, jedis.llen(bfoo).intValue()); + // Binary + assertEquals(0, jedis.llen(bfoo).intValue()); + jedis.lpush(bfoo, bbar); + jedis.lpush(bfoo, bcar); + assertEquals(2, jedis.llen(bfoo).intValue()); } @Test public void llenNotOnList() { - try { - jedis.set("foo", "bar"); - jedis.llen("foo"); - fail("JedisDataException expected"); - } catch (final JedisDataException e) { - } + try { + jedis.set("foo", "bar"); + jedis.llen("foo"); + fail("JedisDataException expected"); + } catch (final JedisDataException e) { + } - // Binary - try { - jedis.set(bfoo, bbar); - jedis.llen(bfoo); - fail("JedisDataException expected"); - } catch (final JedisDataException e) { - } + // Binary + try { + jedis.set(bfoo, bbar); + jedis.llen(bfoo); + fail("JedisDataException expected"); + } catch (final JedisDataException e) { + } } @Test public void lrange() { - jedis.rpush("foo", "a"); - jedis.rpush("foo", "b"); - jedis.rpush("foo", "c"); + jedis.rpush("foo", "a"); + jedis.rpush("foo", "b"); + jedis.rpush("foo", "c"); - List expected = new ArrayList(); - expected.add("a"); - expected.add("b"); - expected.add("c"); + List expected = new ArrayList(); + expected.add("a"); + expected.add("b"); + expected.add("c"); - List range = jedis.lrange("foo", 0, 2); - assertEquals(expected, range); + List range = jedis.lrange("foo", 0, 2); + assertEquals(expected, range); - range = jedis.lrange("foo", 0, 20); - assertEquals(expected, range); + range = jedis.lrange("foo", 0, 20); + assertEquals(expected, range); - expected = new ArrayList(); - expected.add("b"); - expected.add("c"); + expected = new ArrayList(); + expected.add("b"); + expected.add("c"); - range = jedis.lrange("foo", 1, 2); - assertEquals(expected, range); + range = jedis.lrange("foo", 1, 2); + assertEquals(expected, range); - expected = new ArrayList(); - range = jedis.lrange("foo", 2, 1); - assertEquals(expected, range); + expected = new ArrayList(); + range = jedis.lrange("foo", 2, 1); + assertEquals(expected, range); - // Binary - jedis.rpush(bfoo, bA); - jedis.rpush(bfoo, bB); - jedis.rpush(bfoo, bC); + // Binary + jedis.rpush(bfoo, bA); + jedis.rpush(bfoo, bB); + jedis.rpush(bfoo, bC); - List bexpected = new ArrayList(); - bexpected.add(bA); - bexpected.add(bB); - bexpected.add(bC); + List bexpected = new ArrayList(); + bexpected.add(bA); + bexpected.add(bB); + bexpected.add(bC); - List brange = jedis.lrange(bfoo, 0, 2); - assertEquals(bexpected, brange); + List brange = jedis.lrange(bfoo, 0, 2); + assertEquals(bexpected, brange); - brange = jedis.lrange(bfoo, 0, 20); - assertEquals(bexpected, brange); + brange = jedis.lrange(bfoo, 0, 20); + assertEquals(bexpected, brange); - bexpected = new ArrayList(); - bexpected.add(bB); - bexpected.add(bC); + bexpected = new ArrayList(); + bexpected.add(bB); + bexpected.add(bC); - brange = jedis.lrange(bfoo, 1, 2); - assertEquals(bexpected, brange); + brange = jedis.lrange(bfoo, 1, 2); + assertEquals(bexpected, brange); - bexpected = new ArrayList(); - brange = jedis.lrange(bfoo, 2, 1); - assertEquals(bexpected, brange); + bexpected = new ArrayList(); + brange = jedis.lrange(bfoo, 2, 1); + assertEquals(bexpected, brange); } @Test public void ltrim() { - jedis.lpush("foo", "1"); - jedis.lpush("foo", "2"); - jedis.lpush("foo", "3"); - String status = jedis.ltrim("foo", 0, 1); + jedis.lpush("foo", "1"); + jedis.lpush("foo", "2"); + jedis.lpush("foo", "3"); + String status = jedis.ltrim("foo", 0, 1); - List expected = new ArrayList(); - expected.add("3"); - expected.add("2"); + List expected = new ArrayList(); + expected.add("3"); + expected.add("2"); - assertEquals("OK", status); - assertEquals(2, jedis.llen("foo").intValue()); - assertEquals(expected, jedis.lrange("foo", 0, 100)); + assertEquals("OK", status); + assertEquals(2, jedis.llen("foo").intValue()); + assertEquals(expected, jedis.lrange("foo", 0, 100)); - // Binary - jedis.lpush(bfoo, b1); - jedis.lpush(bfoo, b2); - jedis.lpush(bfoo, b3); - String bstatus = jedis.ltrim(bfoo, 0, 1); + // Binary + jedis.lpush(bfoo, b1); + jedis.lpush(bfoo, b2); + jedis.lpush(bfoo, b3); + String bstatus = jedis.ltrim(bfoo, 0, 1); - List bexpected = new ArrayList(); - bexpected.add(b3); - bexpected.add(b2); + List bexpected = new ArrayList(); + bexpected.add(b3); + bexpected.add(b2); - assertEquals("OK", bstatus); - assertEquals(2, jedis.llen(bfoo).intValue()); - assertEquals(bexpected, jedis.lrange(bfoo, 0, 100)); + assertEquals("OK", bstatus); + assertEquals(2, jedis.llen(bfoo).intValue()); + assertEquals(bexpected, jedis.lrange(bfoo, 0, 100)); } @Test public void lindex() { - jedis.lpush("foo", "1"); - jedis.lpush("foo", "2"); - jedis.lpush("foo", "3"); + jedis.lpush("foo", "1"); + jedis.lpush("foo", "2"); + jedis.lpush("foo", "3"); - List expected = new ArrayList(); - expected.add("3"); - expected.add("bar"); - expected.add("1"); + List expected = new ArrayList(); + expected.add("3"); + expected.add("bar"); + expected.add("1"); - String status = jedis.lset("foo", 1, "bar"); + String status = jedis.lset("foo", 1, "bar"); - assertEquals("OK", status); - assertEquals(expected, jedis.lrange("foo", 0, 100)); + assertEquals("OK", status); + assertEquals(expected, jedis.lrange("foo", 0, 100)); - // Binary - jedis.lpush(bfoo, b1); - jedis.lpush(bfoo, b2); - jedis.lpush(bfoo, b3); + // Binary + jedis.lpush(bfoo, b1); + jedis.lpush(bfoo, b2); + jedis.lpush(bfoo, b3); - List bexpected = new ArrayList(); - bexpected.add(b3); - bexpected.add(bbar); - bexpected.add(b1); + List bexpected = new ArrayList(); + bexpected.add(b3); + bexpected.add(bbar); + bexpected.add(b1); - String bstatus = jedis.lset(bfoo, 1, bbar); + String bstatus = jedis.lset(bfoo, 1, bbar); - assertEquals("OK", bstatus); - assertEquals(bexpected, jedis.lrange(bfoo, 0, 100)); + assertEquals("OK", bstatus); + assertEquals(bexpected, jedis.lrange(bfoo, 0, 100)); } @Test public void lset() { - jedis.lpush("foo", "1"); - jedis.lpush("foo", "2"); - jedis.lpush("foo", "3"); + jedis.lpush("foo", "1"); + jedis.lpush("foo", "2"); + jedis.lpush("foo", "3"); - assertEquals("3", jedis.lindex("foo", 0)); - assertEquals(null, jedis.lindex("foo", 100)); + assertEquals("3", jedis.lindex("foo", 0)); + assertEquals(null, jedis.lindex("foo", 100)); - // Binary - jedis.lpush(bfoo, b1); - jedis.lpush(bfoo, b2); - jedis.lpush(bfoo, b3); + // Binary + jedis.lpush(bfoo, b1); + jedis.lpush(bfoo, b2); + jedis.lpush(bfoo, b3); - assertArrayEquals(b3, jedis.lindex(bfoo, 0)); - assertEquals(null, jedis.lindex(bfoo, 100)); + assertArrayEquals(b3, jedis.lindex(bfoo, 0)); + assertEquals(null, jedis.lindex(bfoo, 100)); } @Test public void lrem() { - jedis.lpush("foo", "hello"); - jedis.lpush("foo", "hello"); - jedis.lpush("foo", "x"); - jedis.lpush("foo", "hello"); - jedis.lpush("foo", "c"); - jedis.lpush("foo", "b"); - jedis.lpush("foo", "a"); + jedis.lpush("foo", "hello"); + jedis.lpush("foo", "hello"); + jedis.lpush("foo", "x"); + jedis.lpush("foo", "hello"); + jedis.lpush("foo", "c"); + jedis.lpush("foo", "b"); + jedis.lpush("foo", "a"); - long count = jedis.lrem("foo", -2, "hello"); + long count = jedis.lrem("foo", -2, "hello"); - List expected = new ArrayList(); - expected.add("a"); - expected.add("b"); - expected.add("c"); - expected.add("hello"); - expected.add("x"); + List expected = new ArrayList(); + expected.add("a"); + expected.add("b"); + expected.add("c"); + expected.add("hello"); + expected.add("x"); - assertEquals(2, count); - assertEquals(expected, jedis.lrange("foo", 0, 1000)); - assertEquals(0, jedis.lrem("bar", 100, "foo").intValue()); + assertEquals(2, count); + assertEquals(expected, jedis.lrange("foo", 0, 1000)); + assertEquals(0, jedis.lrem("bar", 100, "foo").intValue()); - // Binary - jedis.lpush(bfoo, bhello); - jedis.lpush(bfoo, bhello); - jedis.lpush(bfoo, bx); - jedis.lpush(bfoo, bhello); - jedis.lpush(bfoo, bC); - jedis.lpush(bfoo, bB); - jedis.lpush(bfoo, bA); + // Binary + jedis.lpush(bfoo, bhello); + jedis.lpush(bfoo, bhello); + jedis.lpush(bfoo, bx); + jedis.lpush(bfoo, bhello); + jedis.lpush(bfoo, bC); + jedis.lpush(bfoo, bB); + jedis.lpush(bfoo, bA); - long bcount = jedis.lrem(bfoo, -2, bhello); + long bcount = jedis.lrem(bfoo, -2, bhello); - List bexpected = new ArrayList(); - bexpected.add(bA); - bexpected.add(bB); - bexpected.add(bC); - bexpected.add(bhello); - bexpected.add(bx); + List bexpected = new ArrayList(); + bexpected.add(bA); + bexpected.add(bB); + bexpected.add(bC); + bexpected.add(bhello); + bexpected.add(bx); - assertEquals(2, bcount); - assertEquals(bexpected, jedis.lrange(bfoo, 0, 1000)); - assertEquals(0, jedis.lrem(bbar, 100, bfoo).intValue()); + assertEquals(2, bcount); + assertEquals(bexpected, jedis.lrange(bfoo, 0, 1000)); + assertEquals(0, jedis.lrem(bbar, 100, bfoo).intValue()); } @Test public void lpop() { - jedis.rpush("foo", "a"); - jedis.rpush("foo", "b"); - jedis.rpush("foo", "c"); + jedis.rpush("foo", "a"); + jedis.rpush("foo", "b"); + jedis.rpush("foo", "c"); - String element = jedis.lpop("foo"); - assertEquals("a", element); + String element = jedis.lpop("foo"); + assertEquals("a", element); - List expected = new ArrayList(); - expected.add("b"); - expected.add("c"); + List expected = new ArrayList(); + expected.add("b"); + expected.add("c"); - assertEquals(expected, jedis.lrange("foo", 0, 1000)); - jedis.lpop("foo"); - jedis.lpop("foo"); + assertEquals(expected, jedis.lrange("foo", 0, 1000)); + jedis.lpop("foo"); + jedis.lpop("foo"); - element = jedis.lpop("foo"); - assertEquals(null, element); + element = jedis.lpop("foo"); + assertEquals(null, element); - // Binary - jedis.rpush(bfoo, bA); - jedis.rpush(bfoo, bB); - jedis.rpush(bfoo, bC); + // Binary + jedis.rpush(bfoo, bA); + jedis.rpush(bfoo, bB); + jedis.rpush(bfoo, bC); - byte[] belement = jedis.lpop(bfoo); - assertArrayEquals(bA, belement); + byte[] belement = jedis.lpop(bfoo); + assertArrayEquals(bA, belement); - List bexpected = new ArrayList(); - bexpected.add(bB); - bexpected.add(bC); + List bexpected = new ArrayList(); + bexpected.add(bB); + bexpected.add(bC); - assertEquals(bexpected, jedis.lrange(bfoo, 0, 1000)); - jedis.lpop(bfoo); - jedis.lpop(bfoo); + assertEquals(bexpected, jedis.lrange(bfoo, 0, 1000)); + jedis.lpop(bfoo); + jedis.lpop(bfoo); - belement = jedis.lpop(bfoo); - assertEquals(null, belement); + belement = jedis.lpop(bfoo); + assertEquals(null, belement); } @Test public void rpop() { - jedis.rpush("foo", "a"); - jedis.rpush("foo", "b"); - jedis.rpush("foo", "c"); + jedis.rpush("foo", "a"); + jedis.rpush("foo", "b"); + jedis.rpush("foo", "c"); - String element = jedis.rpop("foo"); - assertEquals("c", element); + String element = jedis.rpop("foo"); + assertEquals("c", element); - List expected = new ArrayList(); - expected.add("a"); - expected.add("b"); + List expected = new ArrayList(); + expected.add("a"); + expected.add("b"); - assertEquals(expected, jedis.lrange("foo", 0, 1000)); - jedis.rpop("foo"); - jedis.rpop("foo"); + assertEquals(expected, jedis.lrange("foo", 0, 1000)); + jedis.rpop("foo"); + jedis.rpop("foo"); - element = jedis.rpop("foo"); - assertEquals(null, element); + element = jedis.rpop("foo"); + assertEquals(null, element); - // Binary - jedis.rpush(bfoo, bA); - jedis.rpush(bfoo, bB); - jedis.rpush(bfoo, bC); + // Binary + jedis.rpush(bfoo, bA); + jedis.rpush(bfoo, bB); + jedis.rpush(bfoo, bC); - byte[] belement = jedis.rpop(bfoo); - assertArrayEquals(bC, belement); + byte[] belement = jedis.rpop(bfoo); + assertArrayEquals(bC, belement); - List bexpected = new ArrayList(); - bexpected.add(bA); - bexpected.add(bB); + List bexpected = new ArrayList(); + bexpected.add(bA); + bexpected.add(bB); - assertEquals(bexpected, jedis.lrange(bfoo, 0, 1000)); - jedis.rpop(bfoo); - jedis.rpop(bfoo); + assertEquals(bexpected, jedis.lrange(bfoo, 0, 1000)); + jedis.rpop(bfoo); + jedis.rpop(bfoo); - belement = jedis.rpop(bfoo); - assertEquals(null, belement); + belement = jedis.rpop(bfoo); + assertEquals(null, belement); } @Test public void rpoplpush() { - jedis.rpush("foo", "a"); - jedis.rpush("foo", "b"); - jedis.rpush("foo", "c"); + jedis.rpush("foo", "a"); + jedis.rpush("foo", "b"); + jedis.rpush("foo", "c"); - jedis.rpush("dst", "foo"); - jedis.rpush("dst", "bar"); + jedis.rpush("dst", "foo"); + jedis.rpush("dst", "bar"); - String element = jedis.rpoplpush("foo", "dst"); + String element = jedis.rpoplpush("foo", "dst"); - assertEquals("c", element); + assertEquals("c", element); - List srcExpected = new ArrayList(); - srcExpected.add("a"); - srcExpected.add("b"); + List srcExpected = new ArrayList(); + srcExpected.add("a"); + srcExpected.add("b"); - List dstExpected = new ArrayList(); - dstExpected.add("c"); - dstExpected.add("foo"); - dstExpected.add("bar"); + List dstExpected = new ArrayList(); + dstExpected.add("c"); + dstExpected.add("foo"); + dstExpected.add("bar"); - assertEquals(srcExpected, jedis.lrange("foo", 0, 1000)); - assertEquals(dstExpected, jedis.lrange("dst", 0, 1000)); + assertEquals(srcExpected, jedis.lrange("foo", 0, 1000)); + assertEquals(dstExpected, jedis.lrange("dst", 0, 1000)); - // Binary - jedis.rpush(bfoo, bA); - jedis.rpush(bfoo, bB); - jedis.rpush(bfoo, bC); + // Binary + jedis.rpush(bfoo, bA); + jedis.rpush(bfoo, bB); + jedis.rpush(bfoo, bC); - jedis.rpush(bdst, bfoo); - jedis.rpush(bdst, bbar); + jedis.rpush(bdst, bfoo); + jedis.rpush(bdst, bbar); - byte[] belement = jedis.rpoplpush(bfoo, bdst); + byte[] belement = jedis.rpoplpush(bfoo, bdst); - assertArrayEquals(bC, belement); + assertArrayEquals(bC, belement); - List bsrcExpected = new ArrayList(); - bsrcExpected.add(bA); - bsrcExpected.add(bB); + List bsrcExpected = new ArrayList(); + bsrcExpected.add(bA); + bsrcExpected.add(bB); - List bdstExpected = new ArrayList(); - bdstExpected.add(bC); - bdstExpected.add(bfoo); - bdstExpected.add(bbar); + List bdstExpected = new ArrayList(); + bdstExpected.add(bC); + bdstExpected.add(bfoo); + bdstExpected.add(bbar); - assertEquals(bsrcExpected, jedis.lrange(bfoo, 0, 1000)); - assertEquals(bdstExpected, jedis.lrange(bdst, 0, 1000)); + assertEquals(bsrcExpected, jedis.lrange(bfoo, 0, 1000)); + assertEquals(bdstExpected, jedis.lrange(bdst, 0, 1000)); } @Test public void blpop() throws InterruptedException { - List result = jedis.blpop(1, "foo"); - assertNull(result); + List result = jedis.blpop(1, "foo"); + assertNull(result); - jedis.lpush("foo", "bar"); - result = jedis.blpop(1, "foo"); + jedis.lpush("foo", "bar"); + result = jedis.blpop(1, "foo"); - assertNotNull(result); - assertEquals(2, result.size()); - assertEquals("foo", result.get(0)); - assertEquals("bar", result.get(1)); + assertNotNull(result); + assertEquals(2, result.size()); + assertEquals("foo", result.get(0)); + assertEquals("bar", result.get(1)); - // Binary - jedis.lpush(bfoo, bbar); - List bresult = jedis.blpop(1, bfoo); + // Binary + jedis.lpush(bfoo, bbar); + List bresult = jedis.blpop(1, bfoo); - assertNotNull(bresult); - assertEquals(2, bresult.size()); - assertArrayEquals(bfoo, bresult.get(0)); - assertArrayEquals(bbar, bresult.get(1)); + assertNotNull(bresult); + assertEquals(2, bresult.size()); + assertArrayEquals(bfoo, bresult.get(0)); + assertArrayEquals(bbar, bresult.get(1)); } @Test public void brpop() throws InterruptedException { - List result = jedis.brpop(1, "foo"); - assertNull(result); + List result = jedis.brpop(1, "foo"); + assertNull(result); + jedis.lpush("foo", "bar"); + result = jedis.brpop(1, "foo"); + assertNotNull(result); + assertEquals(2, result.size()); + assertEquals("foo", result.get(0)); + assertEquals("bar", result.get(1)); - jedis.lpush("foo", "bar"); - result = jedis.brpop(1, "foo"); - assertNotNull(result); - assertEquals(2, result.size()); - assertEquals("foo", result.get(0)); - assertEquals("bar", result.get(1)); + // Binary - // Binary - - jedis.lpush(bfoo, bbar); - List bresult = jedis.brpop(1, bfoo); - assertNotNull(bresult); - assertEquals(2, bresult.size()); - assertArrayEquals(bfoo, bresult.get(0)); - assertArrayEquals(bbar, bresult.get(1)); + jedis.lpush(bfoo, bbar); + List bresult = jedis.brpop(1, bfoo); + assertNotNull(bresult); + assertEquals(2, bresult.size()); + assertArrayEquals(bfoo, bresult.get(0)); + assertArrayEquals(bbar, bresult.get(1)); } @Test public void lpushx() { - long status = jedis.lpushx("foo", "bar"); - assertEquals(0, status); + long status = jedis.lpushx("foo", "bar"); + assertEquals(0, status); - jedis.lpush("foo", "a"); - status = jedis.lpushx("foo", "b"); - assertEquals(2, status); + jedis.lpush("foo", "a"); + status = jedis.lpushx("foo", "b"); + assertEquals(2, status); - // Binary - long bstatus = jedis.lpushx(bfoo, bbar); - assertEquals(0, bstatus); + // Binary + long bstatus = jedis.lpushx(bfoo, bbar); + assertEquals(0, bstatus); - jedis.lpush(bfoo, bA); - bstatus = jedis.lpushx(bfoo, bB); - assertEquals(2, bstatus); + jedis.lpush(bfoo, bA); + bstatus = jedis.lpushx(bfoo, bB); + assertEquals(2, bstatus); } @Test public void rpushx() { - long status = jedis.rpushx("foo", "bar"); - assertEquals(0, status); + long status = jedis.rpushx("foo", "bar"); + assertEquals(0, status); - jedis.lpush("foo", "a"); - status = jedis.rpushx("foo", "b"); - assertEquals(2, status); + jedis.lpush("foo", "a"); + status = jedis.rpushx("foo", "b"); + assertEquals(2, status); - // Binary - long bstatus = jedis.rpushx(bfoo, bbar); - assertEquals(0, bstatus); + // Binary + long bstatus = jedis.rpushx(bfoo, bbar); + assertEquals(0, bstatus); - jedis.lpush(bfoo, bA); - bstatus = jedis.rpushx(bfoo, bB); - assertEquals(2, bstatus); + jedis.lpush(bfoo, bA); + bstatus = jedis.rpushx(bfoo, bB); + assertEquals(2, bstatus); } @Test public void linsert() { - long status = jedis.linsert("foo", Client.LIST_POSITION.BEFORE, "bar", - "car"); - assertEquals(0, status); + long status = jedis.linsert("foo", Client.LIST_POSITION.BEFORE, "bar", + "car"); + assertEquals(0, status); - jedis.lpush("foo", "a"); - status = jedis.linsert("foo", Client.LIST_POSITION.AFTER, "a", "b"); - assertEquals(2, status); + jedis.lpush("foo", "a"); + status = jedis.linsert("foo", Client.LIST_POSITION.AFTER, "a", "b"); + assertEquals(2, status); - List actual = jedis.lrange("foo", 0, 100); - List expected = new ArrayList(); - expected.add("a"); - expected.add("b"); + List actual = jedis.lrange("foo", 0, 100); + List expected = new ArrayList(); + expected.add("a"); + expected.add("b"); - assertEquals(expected, actual); + assertEquals(expected, actual); - status = jedis - .linsert("foo", Client.LIST_POSITION.BEFORE, "bar", "car"); - assertEquals(-1, status); + status = jedis + .linsert("foo", Client.LIST_POSITION.BEFORE, "bar", "car"); + assertEquals(-1, status); - // Binary - long bstatus = jedis.linsert(bfoo, Client.LIST_POSITION.BEFORE, bbar, - bcar); - assertEquals(0, bstatus); + // Binary + long bstatus = jedis.linsert(bfoo, Client.LIST_POSITION.BEFORE, bbar, + bcar); + assertEquals(0, bstatus); - jedis.lpush(bfoo, bA); - bstatus = jedis.linsert(bfoo, Client.LIST_POSITION.AFTER, bA, bB); - assertEquals(2, bstatus); + jedis.lpush(bfoo, bA); + bstatus = jedis.linsert(bfoo, Client.LIST_POSITION.AFTER, bA, bB); + assertEquals(2, bstatus); - List bactual = jedis.lrange(bfoo, 0, 100); - List bexpected = new ArrayList(); - bexpected.add(bA); - bexpected.add(bB); + List bactual = jedis.lrange(bfoo, 0, 100); + List bexpected = new ArrayList(); + bexpected.add(bA); + bexpected.add(bB); - assertEquals(bexpected, bactual); + assertEquals(bexpected, bactual); - bstatus = jedis.linsert(bfoo, Client.LIST_POSITION.BEFORE, bbar, bcar); - assertEquals(-1, bstatus); + bstatus = jedis.linsert(bfoo, Client.LIST_POSITION.BEFORE, bbar, bcar); + assertEquals(-1, bstatus); } @Test public void brpoplpush() { - (new Thread(new Runnable() { - public void run() { - try { - Thread.sleep(100); - Jedis j = createJedis(); - j.lpush("foo", "a"); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - })).start(); + (new Thread(new Runnable() { + public void run() { + try { + Thread.sleep(100); + Jedis j = createJedis(); + j.lpush("foo", "a"); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + })).start(); - String element = jedis.brpoplpush("foo", "bar", 0); + String element = jedis.brpoplpush("foo", "bar", 0); - assertEquals("a", element); - assertEquals(1, jedis.llen("bar").longValue()); - assertEquals("a", jedis.lrange("bar", 0, -1).get(0)); + assertEquals("a", element); + assertEquals(1, jedis.llen("bar").longValue()); + assertEquals("a", jedis.lrange("bar", 0, -1).get(0)); - (new Thread(new Runnable() { - public void run() { - try { - Thread.sleep(100); - Jedis j = createJedis(); - j.lpush("foo", "a"); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - })).start(); + (new Thread(new Runnable() { + public void run() { + try { + Thread.sleep(100); + Jedis j = createJedis(); + j.lpush("foo", "a"); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + })).start(); - byte[] brpoplpush = jedis.brpoplpush("foo".getBytes(), - "bar".getBytes(), 0); + byte[] brpoplpush = jedis.brpoplpush("foo".getBytes(), + "bar".getBytes(), 0); - assertTrue(Arrays.equals("a".getBytes(), brpoplpush)); - assertEquals(1, jedis.llen("bar").longValue()); - assertEquals("a", jedis.lrange("bar", 0, -1).get(0)); + assertTrue(Arrays.equals("a".getBytes(), brpoplpush)); + assertEquals(1, jedis.llen("bar").longValue()); + assertEquals("a", jedis.lrange("bar", 0, -1).get(0)); } } diff --git a/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java index 3ea14d5..d0d8353 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java @@ -5,14 +5,12 @@ import java.net.UnknownHostException; import java.util.Arrays; import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.Ignore; import org.junit.Test; import redis.clients.jedis.BinaryJedisPubSub; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPubSub; import redis.clients.jedis.exceptions.JedisConnectionException; -import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.util.SafeEncoder; public class PublishSubscribeCommandsTest extends JedisCommandTestBase { @@ -29,7 +27,7 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { }); t.start(); } - + @Test public void subscribe() throws InterruptedException { jedis.subscribe(new JedisPubSub() { @@ -42,8 +40,8 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { public void onSubscribe(String channel, int subscribedChannels) { assertEquals("foo", channel); assertEquals(1, subscribedChannels); - - //now that I'm subscribed... publish + + // now that I'm subscribed... publish publishOne("foo", "exit"); } @@ -140,7 +138,7 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { } public void onPSubscribe(String pattern, int subscribedChannels) { - publishOne(pattern.replace("*", "123"), "exit"); + publishOne(pattern.replace("*", "123"), "exit"); } public void onPUnsubscribe(String pattern, int subscribedChannels) { @@ -264,7 +262,8 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { public void onPSubscribe(byte[] pattern, int subscribedChannels) { assertTrue(Arrays.equals(SafeEncoder.encode("foo.*"), pattern)); assertEquals(1, subscribedChannels); - publishOne(SafeEncoder.encode(pattern).replace("*", "bar"), "exit"); + publishOne(SafeEncoder.encode(pattern).replace("*", "bar"), + "exit"); } public void onPUnsubscribe(byte[] pattern, int subscribedChannels) { @@ -297,7 +296,8 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { } public void onPSubscribe(byte[] pattern, int subscribedChannels) { - publishOne(SafeEncoder.encode(pattern).replace("*", "123"), "exit"); + publishOne(SafeEncoder.encode(pattern).replace("*", "123"), + "exit"); } public void onPUnsubscribe(byte[] pattern, int subscribedChannels) { @@ -320,8 +320,8 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { public void onSubscribe(byte[] channel, int subscribedChannels) { publishOne(SafeEncoder.encode(channel), "exit"); - - if(!SafeEncoder.encode(channel).equals("bar")) { + + if (!SafeEncoder.encode(channel).equals("bar")) { this.subscribe(SafeEncoder.encode("bar")); this.psubscribe(SafeEncoder.encode("bar.*")); } @@ -331,7 +331,8 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { } public void onPSubscribe(byte[] pattern, int subscribedChannels) { - publishOne(SafeEncoder.encode(pattern).replace("*", "123"), "exit"); + publishOne(SafeEncoder.encode(pattern).replace("*", "123"), + "exit"); } public void onPUnsubscribe(byte[] pattern, int subscribedChannels) { diff --git a/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java index aca4899..83b0d04 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java @@ -33,31 +33,33 @@ public class ScriptingCommandsTest extends JedisCommandTestBase { assertEquals("second", response.get(3)); assertEquals("third", response.get(4)); } - + @SuppressWarnings("unchecked") @Test public void evalMultiBulkWithBinaryJedis() { - String script = "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2],ARGV[3]}"; - List keys = new ArrayList(); - keys.add("key1".getBytes()); - keys.add("key2".getBytes()); + String script = "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2],ARGV[3]}"; + List keys = new ArrayList(); + keys.add("key1".getBytes()); + keys.add("key2".getBytes()); - List args = new ArrayList(); - args.add("first".getBytes()); - args.add("second".getBytes()); - args.add("third".getBytes()); + List args = new ArrayList(); + args.add("first".getBytes()); + args.add("second".getBytes()); + args.add("third".getBytes()); - BinaryJedis binaryJedis = new BinaryJedis(hnp.getHost(), hnp.getPort(), 500); - binaryJedis.connect(); - binaryJedis.auth("foobared"); - - List responses = (List) binaryJedis.eval(script.getBytes(), keys, args); - assertEquals(5, responses.size()); - assertEquals("key1", new String(responses.get(0))); - assertEquals("key2", new String(responses.get(1))); - assertEquals("first", new String(responses.get(2))); - assertEquals("second", new String(responses.get(3))); - assertEquals("third", new String(responses.get(4))); + BinaryJedis binaryJedis = new BinaryJedis(hnp.getHost(), hnp.getPort(), + 500); + binaryJedis.connect(); + binaryJedis.auth("foobared"); + + List responses = (List) binaryJedis.eval( + script.getBytes(), keys, args); + assertEquals(5, responses.size()); + assertEquals("key1", new String(responses.get(0))); + assertEquals("key2", new String(responses.get(1))); + assertEquals("first", new String(responses.get(2))); + assertEquals("second", new String(responses.get(3))); + assertEquals("third", new String(responses.get(4))); } @Test @@ -166,26 +168,27 @@ public class ScriptingCommandsTest extends JedisCommandTestBase { } } - @Test - public void scriptEvalReturnNullValues() { - String script = "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}"; - List results = (List) jedis.eval(script, 2, "key1", "key2", "1", "2"); - assertEquals(results.get(0), "key1"); - assertEquals(results.get(1), "key2"); - assertEquals(results.get(2), "1"); - assertEquals(results.get(3), "2"); - } + @Test + public void scriptEvalReturnNullValues() { + String script = "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}"; + List results = (List) jedis.eval(script, 2, "key1", + "key2", "1", "2"); + assertEquals(results.get(0), "key1"); + assertEquals(results.get(1), "key2"); + assertEquals(results.get(2), "1"); + assertEquals(results.get(3), "2"); + } - @Test - public void scriptEvalShaReturnNullValues() { - String script = "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}"; - String sha = jedis.scriptLoad(script); - List results = (List) jedis.evalsha(sha, 2, "key1", "key2", "1", "2"); - assertEquals(results.get(0), "key1"); - assertEquals(results.get(1), "key2"); - assertEquals(results.get(2), "1"); - assertEquals(results.get(3), "2"); + @Test + public void scriptEvalShaReturnNullValues() { + String script = "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}"; + String sha = jedis.scriptLoad(script); + List results = (List) jedis.evalsha(sha, 2, "key1", + "key2", "1", "2"); + assertEquals(results.get(0), "key1"); + assertEquals(results.get(1), "key2"); + assertEquals(results.get(2), "1"); + assertEquals(results.get(3), "2"); - } + } } - diff --git a/src/test/java/redis/clients/jedis/tests/commands/SetCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/SetCommandsTest.java index 7d6930b..80e59ad 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/SetCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/SetCommandsTest.java @@ -2,7 +2,6 @@ package redis.clients.jedis.tests.commands; import java.util.Arrays; import java.util.HashSet; -import java.util.Map; import java.util.Set; import org.junit.Test; @@ -22,443 +21,442 @@ public class SetCommandsTest extends JedisCommandTestBase { @Test public void sadd() { - long status = jedis.sadd("foo", "a"); - assertEquals(1, status); + long status = jedis.sadd("foo", "a"); + assertEquals(1, status); - status = jedis.sadd("foo", "a"); - assertEquals(0, status); + status = jedis.sadd("foo", "a"); + assertEquals(0, status); - long bstatus = jedis.sadd(bfoo, ba); - assertEquals(1, bstatus); + long bstatus = jedis.sadd(bfoo, ba); + assertEquals(1, bstatus); - bstatus = jedis.sadd(bfoo, ba); - assertEquals(0, bstatus); + bstatus = jedis.sadd(bfoo, ba); + assertEquals(0, bstatus); } @Test public void smembers() { - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); - Set expected = new HashSet(); - expected.add("a"); - expected.add("b"); + Set expected = new HashSet(); + expected.add("a"); + expected.add("b"); - Set members = jedis.smembers("foo"); + Set members = jedis.smembers("foo"); - assertEquals(expected, members); + assertEquals(expected, members); - // Binary - jedis.sadd(bfoo, ba); - jedis.sadd(bfoo, bb); + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); - Set bexpected = new HashSet(); - bexpected.add(bb); - bexpected.add(ba); + Set bexpected = new HashSet(); + bexpected.add(bb); + bexpected.add(ba); - Set bmembers = jedis.smembers(bfoo); + Set bmembers = jedis.smembers(bfoo); - assertEquals(bexpected, bmembers); + assertEquals(bexpected, bmembers); } - + @Test public void srem() { - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); - long status = jedis.srem("foo", "a"); + long status = jedis.srem("foo", "a"); - Set expected = new HashSet(); - expected.add("b"); + Set expected = new HashSet(); + expected.add("b"); - assertEquals(1, status); - assertEquals(expected, jedis.smembers("foo")); + assertEquals(1, status); + assertEquals(expected, jedis.smembers("foo")); - status = jedis.srem("foo", "bar"); + status = jedis.srem("foo", "bar"); - assertEquals(0, status); + assertEquals(0, status); - // Binary + // Binary - jedis.sadd(bfoo, ba); - jedis.sadd(bfoo, bb); + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); - long bstatus = jedis.srem(bfoo, ba); + long bstatus = jedis.srem(bfoo, ba); - Set bexpected = new HashSet(); - bexpected.add(bb); + Set bexpected = new HashSet(); + bexpected.add(bb); - assertEquals(1, bstatus); - assertEquals(bexpected, jedis.smembers(bfoo)); + assertEquals(1, bstatus); + assertEquals(bexpected, jedis.smembers(bfoo)); - bstatus = jedis.srem(bfoo, bbar); + bstatus = jedis.srem(bfoo, bbar); - assertEquals(0, bstatus); + assertEquals(0, bstatus); } @Test public void spop() { - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); - String member = jedis.spop("foo"); + String member = jedis.spop("foo"); - assertTrue("a".equals(member) || "b".equals(member)); - assertEquals(1, jedis.smembers("foo").size()); + assertTrue("a".equals(member) || "b".equals(member)); + assertEquals(1, jedis.smembers("foo").size()); - member = jedis.spop("bar"); - assertNull(member); + member = jedis.spop("bar"); + assertNull(member); - // Binary - jedis.sadd(bfoo, ba); - jedis.sadd(bfoo, bb); + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); - byte[] bmember = jedis.spop(bfoo); + byte[] bmember = jedis.spop(bfoo); - assertTrue(Arrays.equals(ba, bmember) || Arrays.equals(bb, bmember)); - assertEquals(1, jedis.smembers(bfoo).size()); + assertTrue(Arrays.equals(ba, bmember) || Arrays.equals(bb, bmember)); + assertEquals(1, jedis.smembers(bfoo).size()); - bmember = jedis.spop(bbar); - assertNull(bmember); + bmember = jedis.spop(bbar); + assertNull(bmember); } @Test public void smove() { - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); - jedis.sadd("bar", "c"); + jedis.sadd("bar", "c"); - long status = jedis.smove("foo", "bar", "a"); + long status = jedis.smove("foo", "bar", "a"); - Set expectedSrc = new HashSet(); - expectedSrc.add("b"); + Set expectedSrc = new HashSet(); + expectedSrc.add("b"); - Set expectedDst = new HashSet(); - expectedDst.add("c"); - expectedDst.add("a"); + Set expectedDst = new HashSet(); + expectedDst.add("c"); + expectedDst.add("a"); - assertEquals(status, 1); - assertEquals(expectedSrc, jedis.smembers("foo")); - assertEquals(expectedDst, jedis.smembers("bar")); + assertEquals(status, 1); + assertEquals(expectedSrc, jedis.smembers("foo")); + assertEquals(expectedDst, jedis.smembers("bar")); - status = jedis.smove("foo", "bar", "a"); + status = jedis.smove("foo", "bar", "a"); - assertEquals(status, 0); + assertEquals(status, 0); - // Binary - jedis.sadd(bfoo, ba); - jedis.sadd(bfoo, bb); + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); - jedis.sadd(bbar, bc); + jedis.sadd(bbar, bc); - long bstatus = jedis.smove(bfoo, bbar, ba); + long bstatus = jedis.smove(bfoo, bbar, ba); - Set bexpectedSrc = new HashSet(); - bexpectedSrc.add(bb); + Set bexpectedSrc = new HashSet(); + bexpectedSrc.add(bb); - Set bexpectedDst = new HashSet(); - bexpectedDst.add(bc); - bexpectedDst.add(ba); + Set bexpectedDst = new HashSet(); + bexpectedDst.add(bc); + bexpectedDst.add(ba); - assertEquals(bstatus, 1); - assertEquals(bexpectedSrc, jedis.smembers(bfoo)); - assertEquals(bexpectedDst, jedis.smembers(bbar)); + assertEquals(bstatus, 1); + assertEquals(bexpectedSrc, jedis.smembers(bfoo)); + assertEquals(bexpectedDst, jedis.smembers(bbar)); - bstatus = jedis.smove(bfoo, bbar, ba); - assertEquals(bstatus, 0); + bstatus = jedis.smove(bfoo, bbar, ba); + assertEquals(bstatus, 0); } @Test public void scard() { - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); - long card = jedis.scard("foo"); + long card = jedis.scard("foo"); - assertEquals(2, card); + assertEquals(2, card); - card = jedis.scard("bar"); - assertEquals(0, card); + card = jedis.scard("bar"); + assertEquals(0, card); - // Binary - jedis.sadd(bfoo, ba); - jedis.sadd(bfoo, bb); + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); - long bcard = jedis.scard(bfoo); + long bcard = jedis.scard(bfoo); - assertEquals(2, bcard); + assertEquals(2, bcard); - bcard = jedis.scard(bbar); - assertEquals(0, bcard); + bcard = jedis.scard(bbar); + assertEquals(0, bcard); } @Test public void sismember() { - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); - assertTrue(jedis.sismember("foo", "a")); + assertTrue(jedis.sismember("foo", "a")); - assertFalse(jedis.sismember("foo", "c")); + assertFalse(jedis.sismember("foo", "c")); - // Binary - jedis.sadd(bfoo, ba); - jedis.sadd(bfoo, bb); + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); - assertTrue(jedis.sismember(bfoo, ba)); + assertTrue(jedis.sismember(bfoo, ba)); - assertFalse(jedis.sismember(bfoo, bc)); + assertFalse(jedis.sismember(bfoo, bc)); } @Test public void sinter() { - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); - jedis.sadd("bar", "b"); - jedis.sadd("bar", "c"); + jedis.sadd("bar", "b"); + jedis.sadd("bar", "c"); - Set expected = new HashSet(); - expected.add("b"); + Set expected = new HashSet(); + expected.add("b"); - Set intersection = jedis.sinter("foo", "bar"); - assertEquals(expected, intersection); + Set intersection = jedis.sinter("foo", "bar"); + assertEquals(expected, intersection); - // Binary - jedis.sadd(bfoo, ba); - jedis.sadd(bfoo, bb); + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); - jedis.sadd(bbar, bb); - jedis.sadd(bbar, bc); + jedis.sadd(bbar, bb); + jedis.sadd(bbar, bc); - Set bexpected = new HashSet(); - bexpected.add(bb); + Set bexpected = new HashSet(); + bexpected.add(bb); - Set bintersection = jedis.sinter(bfoo, bbar); - assertEquals(bexpected, bintersection); + Set bintersection = jedis.sinter(bfoo, bbar); + assertEquals(bexpected, bintersection); } @Test public void sinterstore() { - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); - jedis.sadd("bar", "b"); - jedis.sadd("bar", "c"); + jedis.sadd("bar", "b"); + jedis.sadd("bar", "c"); - Set expected = new HashSet(); - expected.add("b"); + Set expected = new HashSet(); + expected.add("b"); - long status = jedis.sinterstore("car", "foo", "bar"); - assertEquals(1, status); + long status = jedis.sinterstore("car", "foo", "bar"); + assertEquals(1, status); - assertEquals(expected, jedis.smembers("car")); + assertEquals(expected, jedis.smembers("car")); - // Binary - jedis.sadd(bfoo, ba); - jedis.sadd(bfoo, bb); + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); - jedis.sadd(bbar, bb); - jedis.sadd(bbar, bc); + jedis.sadd(bbar, bb); + jedis.sadd(bbar, bc); - Set bexpected = new HashSet(); - bexpected.add(bb); + Set bexpected = new HashSet(); + bexpected.add(bb); - long bstatus = jedis.sinterstore(bcar, bfoo, bbar); - assertEquals(1, bstatus); + long bstatus = jedis.sinterstore(bcar, bfoo, bbar); + assertEquals(1, bstatus); - assertEquals(bexpected, jedis.smembers(bcar)); + assertEquals(bexpected, jedis.smembers(bcar)); } @Test public void sunion() { - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); - jedis.sadd("bar", "b"); - jedis.sadd("bar", "c"); + jedis.sadd("bar", "b"); + jedis.sadd("bar", "c"); - Set expected = new HashSet(); - expected.add("a"); - expected.add("b"); - expected.add("c"); + Set expected = new HashSet(); + expected.add("a"); + expected.add("b"); + expected.add("c"); - Set union = jedis.sunion("foo", "bar"); - assertEquals(expected, union); + Set union = jedis.sunion("foo", "bar"); + assertEquals(expected, union); - // Binary - jedis.sadd(bfoo, ba); - jedis.sadd(bfoo, bb); + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); - jedis.sadd(bbar, bb); - jedis.sadd(bbar, bc); + jedis.sadd(bbar, bb); + jedis.sadd(bbar, bc); - Set bexpected = new HashSet(); - bexpected.add(bb); - bexpected.add(bc); - bexpected.add(ba); + Set bexpected = new HashSet(); + bexpected.add(bb); + bexpected.add(bc); + bexpected.add(ba); - Set bunion = jedis.sunion(bfoo, bbar); - assertEquals(bexpected, bunion); + Set bunion = jedis.sunion(bfoo, bbar); + assertEquals(bexpected, bunion); } @Test public void sunionstore() { - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); - jedis.sadd("bar", "b"); - jedis.sadd("bar", "c"); + jedis.sadd("bar", "b"); + jedis.sadd("bar", "c"); - Set expected = new HashSet(); - expected.add("a"); - expected.add("b"); - expected.add("c"); + Set expected = new HashSet(); + expected.add("a"); + expected.add("b"); + expected.add("c"); - long status = jedis.sunionstore("car", "foo", "bar"); - assertEquals(3, status); + long status = jedis.sunionstore("car", "foo", "bar"); + assertEquals(3, status); - assertEquals(expected, jedis.smembers("car")); + assertEquals(expected, jedis.smembers("car")); - // Binary - jedis.sadd(bfoo, ba); - jedis.sadd(bfoo, bb); + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); - jedis.sadd(bbar, bb); - jedis.sadd(bbar, bc); + jedis.sadd(bbar, bb); + jedis.sadd(bbar, bc); - Set bexpected = new HashSet(); - bexpected.add(bb); - bexpected.add(bc); - bexpected.add(ba); + Set bexpected = new HashSet(); + bexpected.add(bb); + bexpected.add(bc); + bexpected.add(ba); - long bstatus = jedis.sunionstore(bcar, bfoo, bbar); - assertEquals(3, bstatus); + long bstatus = jedis.sunionstore(bcar, bfoo, bbar); + assertEquals(3, bstatus); - assertEquals(bexpected, jedis.smembers(bcar)); + assertEquals(bexpected, jedis.smembers(bcar)); } @Test public void sdiff() { - jedis.sadd("foo", "x"); - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); - jedis.sadd("foo", "c"); + jedis.sadd("foo", "x"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); + jedis.sadd("foo", "c"); - jedis.sadd("bar", "c"); + jedis.sadd("bar", "c"); - jedis.sadd("car", "a"); - jedis.sadd("car", "d"); + jedis.sadd("car", "a"); + jedis.sadd("car", "d"); - Set expected = new HashSet(); - expected.add("x"); - expected.add("b"); + Set expected = new HashSet(); + expected.add("x"); + expected.add("b"); - Set diff = jedis.sdiff("foo", "bar", "car"); - assertEquals(expected, diff); + Set diff = jedis.sdiff("foo", "bar", "car"); + assertEquals(expected, diff); - // Binary - jedis.sadd(bfoo, bx); - jedis.sadd(bfoo, ba); - jedis.sadd(bfoo, bb); - jedis.sadd(bfoo, bc); + // Binary + jedis.sadd(bfoo, bx); + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + jedis.sadd(bfoo, bc); - jedis.sadd(bbar, bc); + jedis.sadd(bbar, bc); - jedis.sadd(bcar, ba); - jedis.sadd(bcar, bd); + jedis.sadd(bcar, ba); + jedis.sadd(bcar, bd); - Set bexpected = new HashSet(); - bexpected.add(bb); - bexpected.add(bx); + Set bexpected = new HashSet(); + bexpected.add(bb); + bexpected.add(bx); - Set bdiff = jedis.sdiff(bfoo, bbar, bcar); - assertEquals(bexpected, bdiff); + Set bdiff = jedis.sdiff(bfoo, bbar, bcar); + assertEquals(bexpected, bdiff); } @Test public void sdiffstore() { - jedis.sadd("foo", "x"); - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); - jedis.sadd("foo", "c"); + jedis.sadd("foo", "x"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); + jedis.sadd("foo", "c"); - jedis.sadd("bar", "c"); + jedis.sadd("bar", "c"); - jedis.sadd("car", "a"); - jedis.sadd("car", "d"); + jedis.sadd("car", "a"); + jedis.sadd("car", "d"); - Set expected = new HashSet(); - expected.add("d"); - expected.add("a"); + Set expected = new HashSet(); + expected.add("d"); + expected.add("a"); - long status = jedis.sdiffstore("tar", "foo", "bar", "car"); - assertEquals(2, status); - assertEquals(expected, jedis.smembers("car")); + long status = jedis.sdiffstore("tar", "foo", "bar", "car"); + assertEquals(2, status); + assertEquals(expected, jedis.smembers("car")); - // Binary - jedis.sadd(bfoo, bx); - jedis.sadd(bfoo, ba); - jedis.sadd(bfoo, bb); - jedis.sadd(bfoo, bc); + // Binary + jedis.sadd(bfoo, bx); + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + jedis.sadd(bfoo, bc); - jedis.sadd(bbar, bc); + jedis.sadd(bbar, bc); - jedis.sadd(bcar, ba); - jedis.sadd(bcar, bd); + jedis.sadd(bcar, ba); + jedis.sadd(bcar, bd); - Set bexpected = new HashSet(); - bexpected.add(bd); - bexpected.add(ba); + Set bexpected = new HashSet(); + bexpected.add(bd); + bexpected.add(ba); - long bstatus = jedis.sdiffstore("tar".getBytes(), bfoo, bbar, bcar); - assertEquals(2, bstatus); - assertEquals(bexpected, jedis.smembers(bcar)); + long bstatus = jedis.sdiffstore("tar".getBytes(), bfoo, bbar, bcar); + assertEquals(2, bstatus); + assertEquals(bexpected, jedis.smembers(bcar)); } @Test public void srandmember() { - jedis.sadd("foo", "a"); - jedis.sadd("foo", "b"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); - String member = jedis.srandmember("foo"); + String member = jedis.srandmember("foo"); - assertTrue("a".equals(member) || "b".equals(member)); - assertEquals(2, jedis.smembers("foo").size()); + assertTrue("a".equals(member) || "b".equals(member)); + assertEquals(2, jedis.smembers("foo").size()); - member = jedis.srandmember("bar"); - assertNull(member); + member = jedis.srandmember("bar"); + assertNull(member); - // Binary - jedis.sadd(bfoo, ba); - jedis.sadd(bfoo, bb); + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); - byte[] bmember = jedis.srandmember(bfoo); + byte[] bmember = jedis.srandmember(bfoo); - assertTrue(Arrays.equals(ba, bmember) || Arrays.equals(bb, bmember)); - assertEquals(2, jedis.smembers(bfoo).size()); + assertTrue(Arrays.equals(ba, bmember) || Arrays.equals(bb, bmember)); + assertEquals(2, jedis.smembers(bfoo).size()); - bmember = jedis.srandmember(bbar); - assertNull(bmember); + bmember = jedis.srandmember(bbar); + assertNull(bmember); } - @Test public void sscan() { jedis.sadd("foo", "a", "b"); - + ScanResult result = jedis.sscan("foo", 0); assertEquals(0, result.getCursor()); diff --git a/src/test/java/redis/clients/jedis/tests/commands/SlowlogCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/SlowlogCommandsTest.java index b65bfb7..55ba9c9 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/SlowlogCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/SlowlogCommandsTest.java @@ -7,42 +7,42 @@ import org.junit.Test; import redis.clients.util.Slowlog; public class SlowlogCommandsTest extends JedisCommandTestBase { - + @Test public void slowlog() { - //do something + // do something jedis.configSet("slowlog-log-slower-than", "0"); - jedis.set("foo", "bar"); - jedis.set("foo2", "bar2"); - - List reducedLog = jedis.slowlogGet(1); - assertEquals(1, reducedLog.size()); - - Slowlog log = reducedLog.get(0); - assertTrue(log.getId() > 0); - assertTrue(log.getTimeStamp() > 0); - assertTrue(log.getExecutionTime() > 0); - assertNotNull(log.getArgs()); - - List breducedLog = jedis.slowlogGetBinary(1); - assertEquals(1, breducedLog.size()); - - List log1 = jedis.slowlogGet(); - List blog1 = jedis.slowlogGetBinary(); - - assertNotNull(log1); - assertNotNull(blog1); - - long len1 = jedis.slowlogLen(); - - jedis.slowlogReset(); - - List log2 = jedis.slowlogGet(); - List blog2 = jedis.slowlogGetBinary(); - long len2 = jedis.slowlogLen(); - - assertTrue(len1 > len2); - assertTrue(log1.size() > log2.size()); - assertTrue(blog1.size() > blog2.size()); + jedis.set("foo", "bar"); + jedis.set("foo2", "bar2"); + + List reducedLog = jedis.slowlogGet(1); + assertEquals(1, reducedLog.size()); + + Slowlog log = reducedLog.get(0); + assertTrue(log.getId() > 0); + assertTrue(log.getTimeStamp() > 0); + assertTrue(log.getExecutionTime() > 0); + assertNotNull(log.getArgs()); + + List breducedLog = jedis.slowlogGetBinary(1); + assertEquals(1, breducedLog.size()); + + List log1 = jedis.slowlogGet(); + List blog1 = jedis.slowlogGetBinary(); + + assertNotNull(log1); + assertNotNull(blog1); + + long len1 = jedis.slowlogLen(); + + jedis.slowlogReset(); + + List log2 = jedis.slowlogGet(); + List blog2 = jedis.slowlogGetBinary(); + long len2 = jedis.slowlogLen(); + + assertTrue(len1 > len2); + assertTrue(log1.size() > log2.size()); + assertTrue(blog1.size() > blog2.size()); } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/commands/SortedSetCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/SortedSetCommandsTest.java index c7d652e..b4fd3b6 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/SortedSetCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/SortedSetCommandsTest.java @@ -21,879 +21,879 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { @Test public void zadd() { - long status = jedis.zadd("foo", 1d, "a"); - assertEquals(1, status); + long status = jedis.zadd("foo", 1d, "a"); + assertEquals(1, status); - status = jedis.zadd("foo", 10d, "b"); - assertEquals(1, status); + status = jedis.zadd("foo", 10d, "b"); + assertEquals(1, status); - status = jedis.zadd("foo", 0.1d, "c"); - assertEquals(1, status); + status = jedis.zadd("foo", 0.1d, "c"); + assertEquals(1, status); - status = jedis.zadd("foo", 2d, "a"); - assertEquals(0, status); + status = jedis.zadd("foo", 2d, "a"); + assertEquals(0, status); - // Binary - long bstatus = jedis.zadd(bfoo, 1d, ba); - assertEquals(1, bstatus); + // Binary + long bstatus = jedis.zadd(bfoo, 1d, ba); + assertEquals(1, bstatus); - bstatus = jedis.zadd(bfoo, 10d, bb); - assertEquals(1, bstatus); + bstatus = jedis.zadd(bfoo, 10d, bb); + assertEquals(1, bstatus); - bstatus = jedis.zadd(bfoo, 0.1d, bc); - assertEquals(1, bstatus); + bstatus = jedis.zadd(bfoo, 0.1d, bc); + assertEquals(1, bstatus); - bstatus = jedis.zadd(bfoo, 2d, ba); - assertEquals(0, bstatus); + bstatus = jedis.zadd(bfoo, 2d, ba); + assertEquals(0, bstatus); } @Test public void zrange() { - jedis.zadd("foo", 1d, "a"); - jedis.zadd("foo", 10d, "b"); - jedis.zadd("foo", 0.1d, "c"); - jedis.zadd("foo", 2d, "a"); + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 10d, "b"); + jedis.zadd("foo", 0.1d, "c"); + jedis.zadd("foo", 2d, "a"); - Set expected = new LinkedHashSet(); - expected.add("c"); - expected.add("a"); + Set expected = new LinkedHashSet(); + expected.add("c"); + expected.add("a"); - Set range = jedis.zrange("foo", 0, 1); - assertEquals(expected, range); + Set range = jedis.zrange("foo", 0, 1); + assertEquals(expected, range); - expected.add("b"); - range = jedis.zrange("foo", 0, 100); - assertEquals(expected, range); + expected.add("b"); + range = jedis.zrange("foo", 0, 100); + assertEquals(expected, range); - // Binary - jedis.zadd(bfoo, 1d, ba); - jedis.zadd(bfoo, 10d, bb); - jedis.zadd(bfoo, 0.1d, bc); - jedis.zadd(bfoo, 2d, ba); + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); - Set bexpected = new LinkedHashSet(); - bexpected.add(bc); - bexpected.add(ba); + Set bexpected = new LinkedHashSet(); + bexpected.add(bc); + bexpected.add(ba); - Set brange = jedis.zrange(bfoo, 0, 1); - assertEquals(bexpected, brange); + Set brange = jedis.zrange(bfoo, 0, 1); + assertEquals(bexpected, brange); - bexpected.add(bb); - brange = jedis.zrange(bfoo, 0, 100); - assertEquals(bexpected, brange); + bexpected.add(bb); + brange = jedis.zrange(bfoo, 0, 100); + assertEquals(bexpected, brange); } @Test public void zrevrange() { - jedis.zadd("foo", 1d, "a"); - jedis.zadd("foo", 10d, "b"); - jedis.zadd("foo", 0.1d, "c"); - jedis.zadd("foo", 2d, "a"); + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 10d, "b"); + jedis.zadd("foo", 0.1d, "c"); + jedis.zadd("foo", 2d, "a"); - Set expected = new LinkedHashSet(); - expected.add("b"); - expected.add("a"); + Set expected = new LinkedHashSet(); + expected.add("b"); + expected.add("a"); - Set range = jedis.zrevrange("foo", 0, 1); - assertEquals(expected, range); + Set range = jedis.zrevrange("foo", 0, 1); + assertEquals(expected, range); - expected.add("c"); - range = jedis.zrevrange("foo", 0, 100); - assertEquals(expected, range); + expected.add("c"); + range = jedis.zrevrange("foo", 0, 100); + assertEquals(expected, range); - // Binary - jedis.zadd(bfoo, 1d, ba); - jedis.zadd(bfoo, 10d, bb); - jedis.zadd(bfoo, 0.1d, bc); - jedis.zadd(bfoo, 2d, ba); + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); - Set bexpected = new LinkedHashSet(); - bexpected.add(bb); - bexpected.add(ba); + Set bexpected = new LinkedHashSet(); + bexpected.add(bb); + bexpected.add(ba); - Set brange = jedis.zrevrange(bfoo, 0, 1); - assertEquals(bexpected, brange); + Set brange = jedis.zrevrange(bfoo, 0, 1); + assertEquals(bexpected, brange); - bexpected.add(bc); - brange = jedis.zrevrange(bfoo, 0, 100); - assertEquals(bexpected, brange); + bexpected.add(bc); + brange = jedis.zrevrange(bfoo, 0, 100); + assertEquals(bexpected, brange); } @Test public void zrem() { - jedis.zadd("foo", 1d, "a"); - jedis.zadd("foo", 2d, "b"); + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 2d, "b"); - long status = jedis.zrem("foo", "a"); + long status = jedis.zrem("foo", "a"); - Set expected = new LinkedHashSet(); - expected.add("b"); + Set expected = new LinkedHashSet(); + expected.add("b"); - assertEquals(1, status); - assertEquals(expected, jedis.zrange("foo", 0, 100)); + assertEquals(1, status); + assertEquals(expected, jedis.zrange("foo", 0, 100)); - status = jedis.zrem("foo", "bar"); + status = jedis.zrem("foo", "bar"); - assertEquals(0, status); + assertEquals(0, status); - // Binary - jedis.zadd(bfoo, 1d, ba); - jedis.zadd(bfoo, 2d, bb); + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 2d, bb); - long bstatus = jedis.zrem(bfoo, ba); + long bstatus = jedis.zrem(bfoo, ba); - Set bexpected = new LinkedHashSet(); - bexpected.add(bb); + Set bexpected = new LinkedHashSet(); + bexpected.add(bb); - assertEquals(1, bstatus); - assertEquals(bexpected, jedis.zrange(bfoo, 0, 100)); + assertEquals(1, bstatus); + assertEquals(bexpected, jedis.zrange(bfoo, 0, 100)); - bstatus = jedis.zrem(bfoo, bbar); + bstatus = jedis.zrem(bfoo, bbar); - assertEquals(0, bstatus); + assertEquals(0, bstatus); } @Test public void zincrby() { - jedis.zadd("foo", 1d, "a"); - jedis.zadd("foo", 2d, "b"); + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 2d, "b"); - double score = jedis.zincrby("foo", 2d, "a"); + double score = jedis.zincrby("foo", 2d, "a"); - Set expected = new LinkedHashSet(); - expected.add("a"); - expected.add("b"); + Set expected = new LinkedHashSet(); + expected.add("a"); + expected.add("b"); - assertEquals(3d, score, 0); - assertEquals(expected, jedis.zrange("foo", 0, 100)); + assertEquals(3d, score, 0); + assertEquals(expected, jedis.zrange("foo", 0, 100)); - // Binary - jedis.zadd(bfoo, 1d, ba); - jedis.zadd(bfoo, 2d, bb); + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 2d, bb); - double bscore = jedis.zincrby(bfoo, 2d, ba); + double bscore = jedis.zincrby(bfoo, 2d, ba); - Set bexpected = new LinkedHashSet(); - bexpected.add(bb); - bexpected.add(ba); + Set bexpected = new LinkedHashSet(); + bexpected.add(bb); + bexpected.add(ba); - assertEquals(3d, bscore, 0); - assertEquals(bexpected, jedis.zrange(bfoo, 0, 100)); + assertEquals(3d, bscore, 0); + assertEquals(bexpected, jedis.zrange(bfoo, 0, 100)); } @Test public void zrank() { - jedis.zadd("foo", 1d, "a"); - jedis.zadd("foo", 2d, "b"); + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 2d, "b"); - long rank = jedis.zrank("foo", "a"); - assertEquals(0, rank); + long rank = jedis.zrank("foo", "a"); + assertEquals(0, rank); - rank = jedis.zrank("foo", "b"); - assertEquals(1, rank); + rank = jedis.zrank("foo", "b"); + assertEquals(1, rank); - assertNull(jedis.zrank("car", "b")); + assertNull(jedis.zrank("car", "b")); - // Binary - jedis.zadd(bfoo, 1d, ba); - jedis.zadd(bfoo, 2d, bb); + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 2d, bb); - long brank = jedis.zrank(bfoo, ba); - assertEquals(0, brank); + long brank = jedis.zrank(bfoo, ba); + assertEquals(0, brank); - brank = jedis.zrank(bfoo, bb); - assertEquals(1, brank); + brank = jedis.zrank(bfoo, bb); + assertEquals(1, brank); - assertNull(jedis.zrank(bcar, bb)); + assertNull(jedis.zrank(bcar, bb)); } @Test public void zrevrank() { - jedis.zadd("foo", 1d, "a"); - jedis.zadd("foo", 2d, "b"); + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 2d, "b"); - long rank = jedis.zrevrank("foo", "a"); - assertEquals(1, rank); + long rank = jedis.zrevrank("foo", "a"); + assertEquals(1, rank); - rank = jedis.zrevrank("foo", "b"); - assertEquals(0, rank); + rank = jedis.zrevrank("foo", "b"); + assertEquals(0, rank); - // Binary - jedis.zadd(bfoo, 1d, ba); - jedis.zadd(bfoo, 2d, bb); + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 2d, bb); - long brank = jedis.zrevrank(bfoo, ba); - assertEquals(1, brank); + long brank = jedis.zrevrank(bfoo, ba); + assertEquals(1, brank); - brank = jedis.zrevrank(bfoo, bb); - assertEquals(0, brank); + brank = jedis.zrevrank(bfoo, bb); + assertEquals(0, brank); } @Test public void zrangeWithScores() { - jedis.zadd("foo", 1d, "a"); - jedis.zadd("foo", 10d, "b"); - jedis.zadd("foo", 0.1d, "c"); - jedis.zadd("foo", 2d, "a"); + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 10d, "b"); + jedis.zadd("foo", 0.1d, "c"); + jedis.zadd("foo", 2d, "a"); - Set expected = new LinkedHashSet(); - expected.add(new Tuple("c", 0.1d)); - expected.add(new Tuple("a", 2d)); + Set expected = new LinkedHashSet(); + expected.add(new Tuple("c", 0.1d)); + expected.add(new Tuple("a", 2d)); - Set range = jedis.zrangeWithScores("foo", 0, 1); - assertEquals(expected, range); + Set range = jedis.zrangeWithScores("foo", 0, 1); + assertEquals(expected, range); - expected.add(new Tuple("b", 10d)); - range = jedis.zrangeWithScores("foo", 0, 100); - assertEquals(expected, range); + expected.add(new Tuple("b", 10d)); + range = jedis.zrangeWithScores("foo", 0, 100); + assertEquals(expected, range); - // Binary - jedis.zadd(bfoo, 1d, ba); - jedis.zadd(bfoo, 10d, bb); - jedis.zadd(bfoo, 0.1d, bc); - jedis.zadd(bfoo, 2d, ba); + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); - Set bexpected = new LinkedHashSet(); - bexpected.add(new Tuple(bc, 0.1d)); - bexpected.add(new Tuple(ba, 2d)); + Set bexpected = new LinkedHashSet(); + bexpected.add(new Tuple(bc, 0.1d)); + bexpected.add(new Tuple(ba, 2d)); - Set brange = jedis.zrangeWithScores(bfoo, 0, 1); - assertEquals(bexpected, brange); + Set brange = jedis.zrangeWithScores(bfoo, 0, 1); + assertEquals(bexpected, brange); - bexpected.add(new Tuple(bb, 10d)); - brange = jedis.zrangeWithScores(bfoo, 0, 100); - assertEquals(bexpected, brange); + bexpected.add(new Tuple(bb, 10d)); + brange = jedis.zrangeWithScores(bfoo, 0, 100); + assertEquals(bexpected, brange); } @Test public void zrevrangeWithScores() { - jedis.zadd("foo", 1d, "a"); - jedis.zadd("foo", 10d, "b"); - jedis.zadd("foo", 0.1d, "c"); - jedis.zadd("foo", 2d, "a"); + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 10d, "b"); + jedis.zadd("foo", 0.1d, "c"); + jedis.zadd("foo", 2d, "a"); - Set expected = new LinkedHashSet(); - expected.add(new Tuple("b", 10d)); - expected.add(new Tuple("a", 2d)); + Set expected = new LinkedHashSet(); + expected.add(new Tuple("b", 10d)); + expected.add(new Tuple("a", 2d)); - Set range = jedis.zrevrangeWithScores("foo", 0, 1); - assertEquals(expected, range); + Set range = jedis.zrevrangeWithScores("foo", 0, 1); + assertEquals(expected, range); - expected.add(new Tuple("c", 0.1d)); - range = jedis.zrevrangeWithScores("foo", 0, 100); - assertEquals(expected, range); + expected.add(new Tuple("c", 0.1d)); + range = jedis.zrevrangeWithScores("foo", 0, 100); + assertEquals(expected, range); - // Binary - jedis.zadd(bfoo, 1d, ba); - jedis.zadd(bfoo, 10d, bb); - jedis.zadd(bfoo, 0.1d, bc); - jedis.zadd(bfoo, 2d, ba); + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); - Set bexpected = new LinkedHashSet(); - bexpected.add(new Tuple(bb, 10d)); - bexpected.add(new Tuple(ba, 2d)); + Set bexpected = new LinkedHashSet(); + bexpected.add(new Tuple(bb, 10d)); + bexpected.add(new Tuple(ba, 2d)); - Set brange = jedis.zrevrangeWithScores(bfoo, 0, 1); - assertEquals(bexpected, brange); + Set brange = jedis.zrevrangeWithScores(bfoo, 0, 1); + assertEquals(bexpected, brange); - bexpected.add(new Tuple(bc, 0.1d)); - brange = jedis.zrevrangeWithScores(bfoo, 0, 100); - assertEquals(bexpected, brange); + bexpected.add(new Tuple(bc, 0.1d)); + brange = jedis.zrevrangeWithScores(bfoo, 0, 100); + assertEquals(bexpected, brange); } @Test public void zcard() { - jedis.zadd("foo", 1d, "a"); - jedis.zadd("foo", 10d, "b"); - jedis.zadd("foo", 0.1d, "c"); - jedis.zadd("foo", 2d, "a"); + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 10d, "b"); + jedis.zadd("foo", 0.1d, "c"); + jedis.zadd("foo", 2d, "a"); - long size = jedis.zcard("foo"); - assertEquals(3, size); + long size = jedis.zcard("foo"); + assertEquals(3, size); - // Binary - jedis.zadd(bfoo, 1d, ba); - jedis.zadd(bfoo, 10d, bb); - jedis.zadd(bfoo, 0.1d, bc); - jedis.zadd(bfoo, 2d, ba); + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); - long bsize = jedis.zcard(bfoo); - assertEquals(3, bsize); + long bsize = jedis.zcard(bfoo); + assertEquals(3, bsize); } @Test public void zscore() { - jedis.zadd("foo", 1d, "a"); - jedis.zadd("foo", 10d, "b"); - jedis.zadd("foo", 0.1d, "c"); - jedis.zadd("foo", 2d, "a"); + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 10d, "b"); + jedis.zadd("foo", 0.1d, "c"); + jedis.zadd("foo", 2d, "a"); - Double score = jedis.zscore("foo", "b"); - assertEquals((Double) 10d, score); + Double score = jedis.zscore("foo", "b"); + assertEquals((Double) 10d, score); - score = jedis.zscore("foo", "c"); - assertEquals((Double) 0.1d, score); + score = jedis.zscore("foo", "c"); + assertEquals((Double) 0.1d, score); - score = jedis.zscore("foo", "s"); - assertNull(score); + score = jedis.zscore("foo", "s"); + assertNull(score); - // Binary - jedis.zadd(bfoo, 1d, ba); - jedis.zadd(bfoo, 10d, bb); - jedis.zadd(bfoo, 0.1d, bc); - jedis.zadd(bfoo, 2d, ba); + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); - Double bscore = jedis.zscore(bfoo, bb); - assertEquals((Double) 10d, bscore); + Double bscore = jedis.zscore(bfoo, bb); + assertEquals((Double) 10d, bscore); - bscore = jedis.zscore(bfoo, bc); - assertEquals((Double) 0.1d, bscore); + bscore = jedis.zscore(bfoo, bc); + assertEquals((Double) 0.1d, bscore); - bscore = jedis.zscore(bfoo, SafeEncoder.encode("s")); - assertNull(bscore); + bscore = jedis.zscore(bfoo, SafeEncoder.encode("s")); + assertNull(bscore); } @Test public void zcount() { - jedis.zadd("foo", 1d, "a"); - jedis.zadd("foo", 10d, "b"); - jedis.zadd("foo", 0.1d, "c"); - jedis.zadd("foo", 2d, "a"); + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 10d, "b"); + jedis.zadd("foo", 0.1d, "c"); + jedis.zadd("foo", 2d, "a"); - long result = jedis.zcount("foo", 0.01d, 2.1d); + long result = jedis.zcount("foo", 0.01d, 2.1d); - assertEquals(2, result); + assertEquals(2, result); - result = jedis.zcount("foo", "(0.01", "+inf"); + result = jedis.zcount("foo", "(0.01", "+inf"); - assertEquals(3, result); - - // Binary - jedis.zadd(bfoo, 1d, ba); - jedis.zadd(bfoo, 10d, bb); - jedis.zadd(bfoo, 0.1d, bc); - jedis.zadd(bfoo, 2d, ba); + assertEquals(3, result); - long bresult = jedis.zcount(bfoo, 0.01d, 2.1d); + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); - assertEquals(2, bresult); + long bresult = jedis.zcount(bfoo, 0.01d, 2.1d); - bresult = jedis.zcount(bfoo, SafeEncoder.encode("(0.01"), SafeEncoder.encode("+inf")); + assertEquals(2, bresult); - assertEquals(3, bresult); + bresult = jedis.zcount(bfoo, SafeEncoder.encode("(0.01"), + SafeEncoder.encode("+inf")); + + assertEquals(3, bresult); } @Test public void zrangebyscore() { - jedis.zadd("foo", 1d, "a"); - jedis.zadd("foo", 10d, "b"); - jedis.zadd("foo", 0.1d, "c"); - jedis.zadd("foo", 2d, "a"); + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 10d, "b"); + jedis.zadd("foo", 0.1d, "c"); + jedis.zadd("foo", 2d, "a"); - Set range = jedis.zrangeByScore("foo", 0d, 2d); + Set range = jedis.zrangeByScore("foo", 0d, 2d); - Set expected = new LinkedHashSet(); - expected.add("c"); - expected.add("a"); + Set expected = new LinkedHashSet(); + expected.add("c"); + expected.add("a"); - assertEquals(expected, range); + assertEquals(expected, range); - range = jedis.zrangeByScore("foo", 0d, 2d, 0, 1); + range = jedis.zrangeByScore("foo", 0d, 2d, 0, 1); - expected = new LinkedHashSet(); - expected.add("c"); + expected = new LinkedHashSet(); + expected.add("c"); - assertEquals(expected, range); + assertEquals(expected, range); - range = jedis.zrangeByScore("foo", 0d, 2d, 1, 1); - Set range2 = jedis.zrangeByScore("foo", "-inf", "(2"); - assertEquals(expected, range2); + range = jedis.zrangeByScore("foo", 0d, 2d, 1, 1); + Set range2 = jedis.zrangeByScore("foo", "-inf", "(2"); + assertEquals(expected, range2); - expected = new LinkedHashSet(); - expected.add("a"); + expected = new LinkedHashSet(); + expected.add("a"); - assertEquals(expected, range); + assertEquals(expected, range); - // Binary - jedis.zadd(bfoo, 1d, ba); - jedis.zadd(bfoo, 10d, bb); - jedis.zadd(bfoo, 0.1d, bc); - jedis.zadd(bfoo, 2d, ba); + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); - Set brange = jedis.zrangeByScore(bfoo, 0d, 2d); + Set brange = jedis.zrangeByScore(bfoo, 0d, 2d); - Set bexpected = new LinkedHashSet(); - bexpected.add(bc); - bexpected.add(ba); + Set bexpected = new LinkedHashSet(); + bexpected.add(bc); + bexpected.add(ba); - assertEquals(bexpected, brange); + assertEquals(bexpected, brange); - brange = jedis.zrangeByScore(bfoo, 0d, 2d, 0, 1); + brange = jedis.zrangeByScore(bfoo, 0d, 2d, 0, 1); - bexpected = new LinkedHashSet(); - bexpected.add(bc); + bexpected = new LinkedHashSet(); + bexpected.add(bc); - assertEquals(bexpected, brange); + assertEquals(bexpected, brange); - brange = jedis.zrangeByScore(bfoo, 0d, 2d, 1, 1); - Set brange2 = jedis.zrangeByScore(bfoo, SafeEncoder - .encode("-inf"), SafeEncoder.encode("(2")); - assertEquals(bexpected, brange2); + brange = jedis.zrangeByScore(bfoo, 0d, 2d, 1, 1); + Set brange2 = jedis.zrangeByScore(bfoo, + SafeEncoder.encode("-inf"), SafeEncoder.encode("(2")); + assertEquals(bexpected, brange2); - bexpected = new LinkedHashSet(); - bexpected.add(ba); + bexpected = new LinkedHashSet(); + bexpected.add(ba); - assertEquals(bexpected, brange); + assertEquals(bexpected, brange); } @Test public void zrevrangebyscore() { - jedis.zadd("foo", 1.0d, "a"); - jedis.zadd("foo", 2.0d, "b"); - jedis.zadd("foo", 3.0d, "c"); - jedis.zadd("foo", 4.0d, "d"); - jedis.zadd("foo", 5.0d, "e"); + jedis.zadd("foo", 1.0d, "a"); + jedis.zadd("foo", 2.0d, "b"); + jedis.zadd("foo", 3.0d, "c"); + jedis.zadd("foo", 4.0d, "d"); + jedis.zadd("foo", 5.0d, "e"); - Set range = jedis.zrevrangeByScore("foo", 3d, - Double.NEGATIVE_INFINITY, 0, 1); - Set expected = new LinkedHashSet(); - expected.add("c"); + Set range = jedis.zrevrangeByScore("foo", 3d, + Double.NEGATIVE_INFINITY, 0, 1); + Set expected = new LinkedHashSet(); + expected.add("c"); - assertEquals(expected, range); + assertEquals(expected, range); - range = jedis.zrevrangeByScore("foo", 3.5d, Double.NEGATIVE_INFINITY, - 0, 2); - expected = new LinkedHashSet(); - expected.add("c"); - expected.add("b"); + range = jedis.zrevrangeByScore("foo", 3.5d, Double.NEGATIVE_INFINITY, + 0, 2); + expected = new LinkedHashSet(); + expected.add("c"); + expected.add("b"); - assertEquals(expected, range); + assertEquals(expected, range); - range = jedis.zrevrangeByScore("foo", 3.5d, Double.NEGATIVE_INFINITY, - 1, 1); - expected = new LinkedHashSet(); - expected.add("b"); + range = jedis.zrevrangeByScore("foo", 3.5d, Double.NEGATIVE_INFINITY, + 1, 1); + expected = new LinkedHashSet(); + expected.add("b"); - assertEquals(expected, range); + assertEquals(expected, range); - range = jedis.zrevrangeByScore("foo", 4d, 2d); - expected = new LinkedHashSet(); - expected.add("d"); - expected.add("c"); - expected.add("b"); + range = jedis.zrevrangeByScore("foo", 4d, 2d); + expected = new LinkedHashSet(); + expected.add("d"); + expected.add("c"); + expected.add("b"); - assertEquals(expected, range); + assertEquals(expected, range); - range = jedis.zrevrangeByScore("foo", "+inf", "(4"); - expected = new LinkedHashSet(); - expected.add("e"); + range = jedis.zrevrangeByScore("foo", "+inf", "(4"); + expected = new LinkedHashSet(); + expected.add("e"); - assertEquals(expected, range); + assertEquals(expected, range); - // Binary - jedis.zadd(bfoo, 1d, ba); - jedis.zadd(bfoo, 10d, bb); - jedis.zadd(bfoo, 0.1d, bc); - jedis.zadd(bfoo, 2d, ba); + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); - Set brange = jedis.zrevrangeByScore(bfoo, 2d, 0d); + Set brange = jedis.zrevrangeByScore(bfoo, 2d, 0d); - Set bexpected = new LinkedHashSet(); - bexpected.add(bc); - bexpected.add(ba); + Set bexpected = new LinkedHashSet(); + bexpected.add(bc); + bexpected.add(ba); - assertEquals(bexpected, brange); + assertEquals(bexpected, brange); - brange = jedis.zrevrangeByScore(bfoo, 2d, 0d, 0, 1); + brange = jedis.zrevrangeByScore(bfoo, 2d, 0d, 0, 1); - bexpected = new LinkedHashSet(); - bexpected.add(ba); + bexpected = new LinkedHashSet(); + bexpected.add(ba); - assertEquals(bexpected, brange); + assertEquals(bexpected, brange); - Set brange2 = jedis.zrevrangeByScore(bfoo, SafeEncoder - .encode("+inf"), SafeEncoder.encode("(2")); + Set brange2 = jedis.zrevrangeByScore(bfoo, + SafeEncoder.encode("+inf"), SafeEncoder.encode("(2")); - bexpected = new LinkedHashSet(); - bexpected.add(bb); + bexpected = new LinkedHashSet(); + bexpected.add(bb); - assertEquals(bexpected, brange2); + assertEquals(bexpected, brange2); - brange = jedis.zrevrangeByScore(bfoo, 2d, 0d, 1, 1); - bexpected = new LinkedHashSet(); - bexpected.add(bc); + brange = jedis.zrevrangeByScore(bfoo, 2d, 0d, 1, 1); + bexpected = new LinkedHashSet(); + bexpected.add(bc); - assertEquals(bexpected, brange); + assertEquals(bexpected, brange); } @Test public void zrangebyscoreWithScores() { - jedis.zadd("foo", 1d, "a"); - jedis.zadd("foo", 10d, "b"); - jedis.zadd("foo", 0.1d, "c"); - jedis.zadd("foo", 2d, "a"); + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 10d, "b"); + jedis.zadd("foo", 0.1d, "c"); + jedis.zadd("foo", 2d, "a"); - Set range = jedis.zrangeByScoreWithScores("foo", 0d, 2d); + Set range = jedis.zrangeByScoreWithScores("foo", 0d, 2d); - Set expected = new LinkedHashSet(); - expected.add(new Tuple("c", 0.1d)); - expected.add(new Tuple("a", 2d)); + Set expected = new LinkedHashSet(); + expected.add(new Tuple("c", 0.1d)); + expected.add(new Tuple("a", 2d)); - assertEquals(expected, range); + assertEquals(expected, range); - range = jedis.zrangeByScoreWithScores("foo", 0d, 2d, 0, 1); + range = jedis.zrangeByScoreWithScores("foo", 0d, 2d, 0, 1); - expected = new LinkedHashSet(); - expected.add(new Tuple("c", 0.1d)); + expected = new LinkedHashSet(); + expected.add(new Tuple("c", 0.1d)); - assertEquals(expected, range); + assertEquals(expected, range); - range = jedis.zrangeByScoreWithScores("foo", 0d, 2d, 1, 1); + range = jedis.zrangeByScoreWithScores("foo", 0d, 2d, 1, 1); - expected = new LinkedHashSet(); - expected.add(new Tuple("a", 2d)); + expected = new LinkedHashSet(); + expected.add(new Tuple("a", 2d)); - assertEquals(expected, range); + assertEquals(expected, range); - // Binary + // Binary - jedis.zadd(bfoo, 1d, ba); - jedis.zadd(bfoo, 10d, bb); - jedis.zadd(bfoo, 0.1d, bc); - jedis.zadd(bfoo, 2d, ba); + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); - Set brange = jedis.zrangeByScoreWithScores(bfoo, 0d, 2d); + Set brange = jedis.zrangeByScoreWithScores(bfoo, 0d, 2d); - Set bexpected = new LinkedHashSet(); - bexpected.add(new Tuple(bc, 0.1d)); - bexpected.add(new Tuple(ba, 2d)); + Set bexpected = new LinkedHashSet(); + bexpected.add(new Tuple(bc, 0.1d)); + bexpected.add(new Tuple(ba, 2d)); - assertEquals(bexpected, brange); + assertEquals(bexpected, brange); - brange = jedis.zrangeByScoreWithScores(bfoo, 0d, 2d, 0, 1); + brange = jedis.zrangeByScoreWithScores(bfoo, 0d, 2d, 0, 1); - bexpected = new LinkedHashSet(); - bexpected.add(new Tuple(bc, 0.1d)); + bexpected = new LinkedHashSet(); + bexpected.add(new Tuple(bc, 0.1d)); - assertEquals(bexpected, brange); + assertEquals(bexpected, brange); - brange = jedis.zrangeByScoreWithScores(bfoo, 0d, 2d, 1, 1); + brange = jedis.zrangeByScoreWithScores(bfoo, 0d, 2d, 1, 1); - bexpected = new LinkedHashSet(); - bexpected.add(new Tuple(ba, 2d)); + bexpected = new LinkedHashSet(); + bexpected.add(new Tuple(ba, 2d)); - assertEquals(bexpected, brange); + assertEquals(bexpected, brange); } @Test public void zrevrangebyscoreWithScores() { - jedis.zadd("foo", 1.0d, "a"); - jedis.zadd("foo", 2.0d, "b"); - jedis.zadd("foo", 3.0d, "c"); - jedis.zadd("foo", 4.0d, "d"); - jedis.zadd("foo", 5.0d, "e"); + jedis.zadd("foo", 1.0d, "a"); + jedis.zadd("foo", 2.0d, "b"); + jedis.zadd("foo", 3.0d, "c"); + jedis.zadd("foo", 4.0d, "d"); + jedis.zadd("foo", 5.0d, "e"); - Set range = jedis.zrevrangeByScoreWithScores("foo", 3d, - Double.NEGATIVE_INFINITY, 0, 1); - Set expected = new LinkedHashSet(); - expected.add(new Tuple("c", 3.0d)); + Set range = jedis.zrevrangeByScoreWithScores("foo", 3d, + Double.NEGATIVE_INFINITY, 0, 1); + Set expected = new LinkedHashSet(); + expected.add(new Tuple("c", 3.0d)); - assertEquals(expected, range); + assertEquals(expected, range); - range = jedis.zrevrangeByScoreWithScores("foo", 3.5d, - Double.NEGATIVE_INFINITY, 0, 2); - expected = new LinkedHashSet(); - expected.add(new Tuple("c", 3.0d)); - expected.add(new Tuple("b", 2.0d)); + range = jedis.zrevrangeByScoreWithScores("foo", 3.5d, + Double.NEGATIVE_INFINITY, 0, 2); + expected = new LinkedHashSet(); + expected.add(new Tuple("c", 3.0d)); + expected.add(new Tuple("b", 2.0d)); - assertEquals(expected, range); + assertEquals(expected, range); - range = jedis.zrevrangeByScoreWithScores("foo", 3.5d, - Double.NEGATIVE_INFINITY, 1, 1); - expected = new LinkedHashSet(); - expected.add(new Tuple("b", 2.0d)); + range = jedis.zrevrangeByScoreWithScores("foo", 3.5d, + Double.NEGATIVE_INFINITY, 1, 1); + expected = new LinkedHashSet(); + expected.add(new Tuple("b", 2.0d)); - assertEquals(expected, range); + assertEquals(expected, range); - range = jedis.zrevrangeByScoreWithScores("foo", 4d, 2d); - expected = new LinkedHashSet(); - expected.add(new Tuple("d", 4.0d)); - expected.add(new Tuple("c", 3.0d)); - expected.add(new Tuple("b", 2.0d)); + range = jedis.zrevrangeByScoreWithScores("foo", 4d, 2d); + expected = new LinkedHashSet(); + expected.add(new Tuple("d", 4.0d)); + expected.add(new Tuple("c", 3.0d)); + expected.add(new Tuple("b", 2.0d)); - assertEquals(expected, range); + assertEquals(expected, range); - // Binary - jedis.zadd(bfoo, 1d, ba); - jedis.zadd(bfoo, 10d, bb); - jedis.zadd(bfoo, 0.1d, bc); - jedis.zadd(bfoo, 2d, ba); + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); - Set brange = jedis.zrevrangeByScoreWithScores(bfoo, 2d, 0d); + Set brange = jedis.zrevrangeByScoreWithScores(bfoo, 2d, 0d); - Set bexpected = new LinkedHashSet(); - bexpected.add(new Tuple(bc, 0.1d)); - bexpected.add(new Tuple(ba, 2d)); + Set bexpected = new LinkedHashSet(); + bexpected.add(new Tuple(bc, 0.1d)); + bexpected.add(new Tuple(ba, 2d)); - assertEquals(bexpected, brange); + assertEquals(bexpected, brange); - brange = jedis.zrevrangeByScoreWithScores(bfoo, 2d, 0d, 0, 1); + brange = jedis.zrevrangeByScoreWithScores(bfoo, 2d, 0d, 0, 1); - bexpected = new LinkedHashSet(); - bexpected.add(new Tuple(ba, 2d)); + bexpected = new LinkedHashSet(); + bexpected.add(new Tuple(ba, 2d)); - assertEquals(bexpected, brange); + assertEquals(bexpected, brange); - brange = jedis.zrevrangeByScoreWithScores(bfoo, 2d, 0d, 1, 1); + brange = jedis.zrevrangeByScoreWithScores(bfoo, 2d, 0d, 1, 1); - bexpected = new LinkedHashSet(); - bexpected.add(new Tuple(bc, 0.1d)); + bexpected = new LinkedHashSet(); + bexpected.add(new Tuple(bc, 0.1d)); - assertEquals(bexpected, brange); + assertEquals(bexpected, brange); } - + @Test public void zremrangeByRank() { - jedis.zadd("foo", 1d, "a"); - jedis.zadd("foo", 10d, "b"); - jedis.zadd("foo", 0.1d, "c"); - jedis.zadd("foo", 2d, "a"); + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 10d, "b"); + jedis.zadd("foo", 0.1d, "c"); + jedis.zadd("foo", 2d, "a"); - long result = jedis.zremrangeByRank("foo", 0, 0); + long result = jedis.zremrangeByRank("foo", 0, 0); - assertEquals(1, result); + assertEquals(1, result); - Set expected = new LinkedHashSet(); - expected.add("a"); - expected.add("b"); + Set expected = new LinkedHashSet(); + expected.add("a"); + expected.add("b"); - assertEquals(expected, jedis.zrange("foo", 0, 100)); + assertEquals(expected, jedis.zrange("foo", 0, 100)); - // Binary - jedis.zadd(bfoo, 1d, ba); - jedis.zadd(bfoo, 10d, bb); - jedis.zadd(bfoo, 0.1d, bc); - jedis.zadd(bfoo, 2d, ba); + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); - long bresult = jedis.zremrangeByRank(bfoo, 0, 0); + long bresult = jedis.zremrangeByRank(bfoo, 0, 0); - assertEquals(1, bresult); + assertEquals(1, bresult); - Set bexpected = new LinkedHashSet(); - bexpected.add(ba); - bexpected.add(bb); + Set bexpected = new LinkedHashSet(); + bexpected.add(ba); + bexpected.add(bb); - assertEquals(bexpected, jedis.zrange(bfoo, 0, 100)); + assertEquals(bexpected, jedis.zrange(bfoo, 0, 100)); } @Test public void zremrangeByScore() { - jedis.zadd("foo", 1d, "a"); - jedis.zadd("foo", 10d, "b"); - jedis.zadd("foo", 0.1d, "c"); - jedis.zadd("foo", 2d, "a"); + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 10d, "b"); + jedis.zadd("foo", 0.1d, "c"); + jedis.zadd("foo", 2d, "a"); - long result = jedis.zremrangeByScore("foo", 0, 2); + long result = jedis.zremrangeByScore("foo", 0, 2); - assertEquals(2, result); + assertEquals(2, result); - Set expected = new LinkedHashSet(); - expected.add("b"); + Set expected = new LinkedHashSet(); + expected.add("b"); - assertEquals(expected, jedis.zrange("foo", 0, 100)); + assertEquals(expected, jedis.zrange("foo", 0, 100)); - // Binary - jedis.zadd(bfoo, 1d, ba); - jedis.zadd(bfoo, 10d, bb); - jedis.zadd(bfoo, 0.1d, bc); - jedis.zadd(bfoo, 2d, ba); + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); - long bresult = jedis.zremrangeByScore(bfoo, 0, 2); + long bresult = jedis.zremrangeByScore(bfoo, 0, 2); - assertEquals(2, bresult); + assertEquals(2, bresult); - Set bexpected = new LinkedHashSet(); - bexpected.add(bb); + Set bexpected = new LinkedHashSet(); + bexpected.add(bb); - assertEquals(bexpected, jedis.zrange(bfoo, 0, 100)); + assertEquals(bexpected, jedis.zrange(bfoo, 0, 100)); } @Test public void zunionstore() { - jedis.zadd("foo", 1, "a"); - jedis.zadd("foo", 2, "b"); - jedis.zadd("bar", 2, "a"); - jedis.zadd("bar", 2, "b"); + jedis.zadd("foo", 1, "a"); + jedis.zadd("foo", 2, "b"); + jedis.zadd("bar", 2, "a"); + jedis.zadd("bar", 2, "b"); - long result = jedis.zunionstore("dst", "foo", "bar"); + long result = jedis.zunionstore("dst", "foo", "bar"); - assertEquals(2, result); + assertEquals(2, result); - Set expected = new LinkedHashSet(); - expected.add(new Tuple("b", new Double(4))); - expected.add(new Tuple("a", new Double(3))); + Set expected = new LinkedHashSet(); + expected.add(new Tuple("b", new Double(4))); + expected.add(new Tuple("a", new Double(3))); - assertEquals(expected, jedis.zrangeWithScores("dst", 0, 100)); + assertEquals(expected, jedis.zrangeWithScores("dst", 0, 100)); - // Binary - jedis.zadd(bfoo, 1, ba); - jedis.zadd(bfoo, 2, bb); - jedis.zadd(bbar, 2, ba); - jedis.zadd(bbar, 2, bb); + // Binary + jedis.zadd(bfoo, 1, ba); + jedis.zadd(bfoo, 2, bb); + jedis.zadd(bbar, 2, ba); + jedis.zadd(bbar, 2, bb); - long bresult = jedis.zunionstore(SafeEncoder.encode("dst"), bfoo, bbar); + long bresult = jedis.zunionstore(SafeEncoder.encode("dst"), bfoo, bbar); - assertEquals(2, bresult); + assertEquals(2, bresult); - Set bexpected = new LinkedHashSet(); - bexpected.add(new Tuple(bb, new Double(4))); - bexpected.add(new Tuple(ba, new Double(3))); + Set bexpected = new LinkedHashSet(); + bexpected.add(new Tuple(bb, new Double(4))); + bexpected.add(new Tuple(ba, new Double(3))); - assertEquals(bexpected, jedis.zrangeWithScores(SafeEncoder - .encode("dst"), 0, 100)); + assertEquals(bexpected, + jedis.zrangeWithScores(SafeEncoder.encode("dst"), 0, 100)); } @Test public void zunionstoreParams() { - jedis.zadd("foo", 1, "a"); - jedis.zadd("foo", 2, "b"); - jedis.zadd("bar", 2, "a"); - jedis.zadd("bar", 2, "b"); + jedis.zadd("foo", 1, "a"); + jedis.zadd("foo", 2, "b"); + jedis.zadd("bar", 2, "a"); + jedis.zadd("bar", 2, "b"); - ZParams params = new ZParams(); - params.weights(2, 2); - params.aggregate(ZParams.Aggregate.SUM); - long result = jedis.zunionstore("dst", params, "foo", "bar"); + ZParams params = new ZParams(); + params.weights(2, 2); + params.aggregate(ZParams.Aggregate.SUM); + long result = jedis.zunionstore("dst", params, "foo", "bar"); - assertEquals(2, result); + assertEquals(2, result); - Set expected = new LinkedHashSet(); - expected.add(new Tuple("b", new Double(8))); - expected.add(new Tuple("a", new Double(6))); + Set expected = new LinkedHashSet(); + expected.add(new Tuple("b", new Double(8))); + expected.add(new Tuple("a", new Double(6))); - assertEquals(expected, jedis.zrangeWithScores("dst", 0, 100)); + assertEquals(expected, jedis.zrangeWithScores("dst", 0, 100)); - // Binary - jedis.zadd(bfoo, 1, ba); - jedis.zadd(bfoo, 2, bb); - jedis.zadd(bbar, 2, ba); - jedis.zadd(bbar, 2, bb); + // Binary + jedis.zadd(bfoo, 1, ba); + jedis.zadd(bfoo, 2, bb); + jedis.zadd(bbar, 2, ba); + jedis.zadd(bbar, 2, bb); - ZParams bparams = new ZParams(); - bparams.weights(2, 2); - bparams.aggregate(ZParams.Aggregate.SUM); - long bresult = jedis.zunionstore(SafeEncoder.encode("dst"), bparams, - bfoo, bbar); + ZParams bparams = new ZParams(); + bparams.weights(2, 2); + bparams.aggregate(ZParams.Aggregate.SUM); + long bresult = jedis.zunionstore(SafeEncoder.encode("dst"), bparams, + bfoo, bbar); - assertEquals(2, bresult); + assertEquals(2, bresult); - Set bexpected = new LinkedHashSet(); - bexpected.add(new Tuple(bb, new Double(8))); - bexpected.add(new Tuple(ba, new Double(6))); + Set bexpected = new LinkedHashSet(); + bexpected.add(new Tuple(bb, new Double(8))); + bexpected.add(new Tuple(ba, new Double(6))); - assertEquals(bexpected, jedis.zrangeWithScores(SafeEncoder - .encode("dst"), 0, 100)); + assertEquals(bexpected, + jedis.zrangeWithScores(SafeEncoder.encode("dst"), 0, 100)); } @Test public void zinterstore() { - jedis.zadd("foo", 1, "a"); - jedis.zadd("foo", 2, "b"); - jedis.zadd("bar", 2, "a"); + jedis.zadd("foo", 1, "a"); + jedis.zadd("foo", 2, "b"); + jedis.zadd("bar", 2, "a"); - long result = jedis.zinterstore("dst", "foo", "bar"); + long result = jedis.zinterstore("dst", "foo", "bar"); - assertEquals(1, result); + assertEquals(1, result); - Set expected = new LinkedHashSet(); - expected.add(new Tuple("a", new Double(3))); + Set expected = new LinkedHashSet(); + expected.add(new Tuple("a", new Double(3))); - assertEquals(expected, jedis.zrangeWithScores("dst", 0, 100)); + assertEquals(expected, jedis.zrangeWithScores("dst", 0, 100)); - // Binary - jedis.zadd(bfoo, 1, ba); - jedis.zadd(bfoo, 2, bb); - jedis.zadd(bbar, 2, ba); + // Binary + jedis.zadd(bfoo, 1, ba); + jedis.zadd(bfoo, 2, bb); + jedis.zadd(bbar, 2, ba); - long bresult = jedis.zinterstore(SafeEncoder.encode("dst"), bfoo, bbar); + long bresult = jedis.zinterstore(SafeEncoder.encode("dst"), bfoo, bbar); - assertEquals(1, bresult); + assertEquals(1, bresult); - Set bexpected = new LinkedHashSet(); - bexpected.add(new Tuple(ba, new Double(3))); + Set bexpected = new LinkedHashSet(); + bexpected.add(new Tuple(ba, new Double(3))); - assertEquals(bexpected, jedis.zrangeWithScores(SafeEncoder - .encode("dst"), 0, 100)); + assertEquals(bexpected, + jedis.zrangeWithScores(SafeEncoder.encode("dst"), 0, 100)); } @Test public void zintertoreParams() { - jedis.zadd("foo", 1, "a"); - jedis.zadd("foo", 2, "b"); - jedis.zadd("bar", 2, "a"); + jedis.zadd("foo", 1, "a"); + jedis.zadd("foo", 2, "b"); + jedis.zadd("bar", 2, "a"); - ZParams params = new ZParams(); - params.weights(2, 2); - params.aggregate(ZParams.Aggregate.SUM); - long result = jedis.zinterstore("dst", params, "foo", "bar"); + ZParams params = new ZParams(); + params.weights(2, 2); + params.aggregate(ZParams.Aggregate.SUM); + long result = jedis.zinterstore("dst", params, "foo", "bar"); - assertEquals(1, result); + assertEquals(1, result); - Set expected = new LinkedHashSet(); - expected.add(new Tuple("a", new Double(6))); + Set expected = new LinkedHashSet(); + expected.add(new Tuple("a", new Double(6))); - assertEquals(expected, jedis.zrangeWithScores("dst", 0, 100)); + assertEquals(expected, jedis.zrangeWithScores("dst", 0, 100)); - // Binary - jedis.zadd(bfoo, 1, ba); - jedis.zadd(bfoo, 2, bb); - jedis.zadd(bbar, 2, ba); + // Binary + jedis.zadd(bfoo, 1, ba); + jedis.zadd(bfoo, 2, bb); + jedis.zadd(bbar, 2, ba); - ZParams bparams = new ZParams(); - bparams.weights(2, 2); - bparams.aggregate(ZParams.Aggregate.SUM); - long bresult = jedis.zinterstore(SafeEncoder.encode("dst"), bparams, - bfoo, bbar); + ZParams bparams = new ZParams(); + bparams.weights(2, 2); + bparams.aggregate(ZParams.Aggregate.SUM); + long bresult = jedis.zinterstore(SafeEncoder.encode("dst"), bparams, + bfoo, bbar); - assertEquals(1, bresult); + assertEquals(1, bresult); - Set bexpected = new LinkedHashSet(); - bexpected.add(new Tuple(ba, new Double(6))); + Set bexpected = new LinkedHashSet(); + bexpected.add(new Tuple(ba, new Double(6))); - assertEquals(bexpected, jedis.zrangeWithScores(SafeEncoder - .encode("dst"), 0, 100)); + assertEquals(bexpected, + jedis.zrangeWithScores(SafeEncoder.encode("dst"), 0, 100)); } @Test public void tupleCompare() { - Tuple t1 = new Tuple("foo", 1d); - Tuple t2 = new Tuple("bar", 2d); + Tuple t1 = new Tuple("foo", 1d); + Tuple t2 = new Tuple("bar", 2d); - assertEquals(-1, t1.compareTo(t2)); - assertEquals(1, t2.compareTo(t1)); - assertEquals(0, t2.compareTo(t2)); + assertEquals(-1, t1.compareTo(t2)); + assertEquals(1, t2.compareTo(t1)); + assertEquals(0, t2.compareTo(t2)); } - @Test public void zscan() { jedis.zadd("foo", 1, "a"); jedis.zadd("foo", 2, "b"); - + ScanResult result = jedis.zscan("foo", 0); assertEquals(0, result.getCursor()); diff --git a/src/test/java/redis/clients/jedis/tests/commands/SortingCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/SortingCommandsTest.java index 10d8965..543dacb 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/SortingCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/SortingCommandsTest.java @@ -25,277 +25,277 @@ public class SortingCommandsTest extends JedisCommandTestBase { @Test public void sort() { - jedis.lpush("foo", "3"); - jedis.lpush("foo", "2"); - jedis.lpush("foo", "1"); + jedis.lpush("foo", "3"); + jedis.lpush("foo", "2"); + jedis.lpush("foo", "1"); - List result = jedis.sort("foo"); + List result = jedis.sort("foo"); - List expected = new ArrayList(); - expected.add("1"); - expected.add("2"); - expected.add("3"); + List expected = new ArrayList(); + expected.add("1"); + expected.add("2"); + expected.add("3"); - assertEquals(expected, result); + assertEquals(expected, result); - // Binary - jedis.lpush(bfoo, b3); - jedis.lpush(bfoo, b2); - jedis.lpush(bfoo, b1); + // Binary + jedis.lpush(bfoo, b3); + jedis.lpush(bfoo, b2); + jedis.lpush(bfoo, b1); - List bresult = jedis.sort(bfoo); + List bresult = jedis.sort(bfoo); - List bexpected = new ArrayList(); - bexpected.add(b1); - bexpected.add(b2); - bexpected.add(b3); + List bexpected = new ArrayList(); + bexpected.add(b1); + bexpected.add(b2); + bexpected.add(b3); - assertEquals(bexpected, bresult); + assertEquals(bexpected, bresult); } @Test public void sortBy() { - jedis.lpush("foo", "2"); - jedis.lpush("foo", "3"); - jedis.lpush("foo", "1"); + jedis.lpush("foo", "2"); + jedis.lpush("foo", "3"); + jedis.lpush("foo", "1"); - jedis.set("bar1", "3"); - jedis.set("bar2", "2"); - jedis.set("bar3", "1"); + jedis.set("bar1", "3"); + jedis.set("bar2", "2"); + jedis.set("bar3", "1"); - SortingParams sp = new SortingParams(); - sp.by("bar*"); + SortingParams sp = new SortingParams(); + sp.by("bar*"); - List result = jedis.sort("foo", sp); + List result = jedis.sort("foo", sp); - List expected = new ArrayList(); - expected.add("3"); - expected.add("2"); - expected.add("1"); + List expected = new ArrayList(); + expected.add("3"); + expected.add("2"); + expected.add("1"); - assertEquals(expected, result); + assertEquals(expected, result); - // Binary - jedis.lpush(bfoo, b2); - jedis.lpush(bfoo, b3); - jedis.lpush(bfoo, b1); + // Binary + jedis.lpush(bfoo, b2); + jedis.lpush(bfoo, b3); + jedis.lpush(bfoo, b1); - jedis.set(bbar1, b3); - jedis.set(bbar2, b2); - jedis.set(bbar3, b1); + jedis.set(bbar1, b3); + jedis.set(bbar2, b2); + jedis.set(bbar3, b1); - SortingParams bsp = new SortingParams(); - bsp.by(bbarstar); + SortingParams bsp = new SortingParams(); + bsp.by(bbarstar); - List bresult = jedis.sort(bfoo, bsp); + List bresult = jedis.sort(bfoo, bsp); - List bexpected = new ArrayList(); - bexpected.add(b3); - bexpected.add(b2); - bexpected.add(b1); + List bexpected = new ArrayList(); + bexpected.add(b3); + bexpected.add(b2); + bexpected.add(b1); - assertEquals(bexpected, bresult); + assertEquals(bexpected, bresult); } @Test public void sortDesc() { - jedis.lpush("foo", "3"); - jedis.lpush("foo", "2"); - jedis.lpush("foo", "1"); + jedis.lpush("foo", "3"); + jedis.lpush("foo", "2"); + jedis.lpush("foo", "1"); - SortingParams sp = new SortingParams(); - sp.desc(); + SortingParams sp = new SortingParams(); + sp.desc(); - List result = jedis.sort("foo", sp); + List result = jedis.sort("foo", sp); - List expected = new ArrayList(); - expected.add("3"); - expected.add("2"); - expected.add("1"); + List expected = new ArrayList(); + expected.add("3"); + expected.add("2"); + expected.add("1"); - assertEquals(expected, result); + assertEquals(expected, result); - // Binary - jedis.lpush(bfoo, b3); - jedis.lpush(bfoo, b2); - jedis.lpush(bfoo, b1); + // Binary + jedis.lpush(bfoo, b3); + jedis.lpush(bfoo, b2); + jedis.lpush(bfoo, b1); - SortingParams bsp = new SortingParams(); - bsp.desc(); + SortingParams bsp = new SortingParams(); + bsp.desc(); - List bresult = jedis.sort(bfoo, bsp); + List bresult = jedis.sort(bfoo, bsp); - List bexpected = new ArrayList(); - bexpected.add(b3); - bexpected.add(b2); - bexpected.add(b1); + List bexpected = new ArrayList(); + bexpected.add(b3); + bexpected.add(b2); + bexpected.add(b1); - assertEquals(bexpected, bresult); + assertEquals(bexpected, bresult); } @Test public void sortLimit() { - for (int n = 10; n > 0; n--) { - jedis.lpush("foo", String.valueOf(n)); - } + for (int n = 10; n > 0; n--) { + jedis.lpush("foo", String.valueOf(n)); + } - SortingParams sp = new SortingParams(); - sp.limit(0, 3); + SortingParams sp = new SortingParams(); + sp.limit(0, 3); - List result = jedis.sort("foo", sp); + List result = jedis.sort("foo", sp); - List expected = new ArrayList(); - expected.add("1"); - expected.add("2"); - expected.add("3"); + List expected = new ArrayList(); + expected.add("1"); + expected.add("2"); + expected.add("3"); - assertEquals(expected, result); + assertEquals(expected, result); - // Binary - jedis.rpush(bfoo, new byte[] { (byte) '4' }); - jedis.rpush(bfoo, new byte[] { (byte) '3' }); - jedis.rpush(bfoo, new byte[] { (byte) '2' }); - jedis.rpush(bfoo, new byte[] { (byte) '1' }); + // Binary + jedis.rpush(bfoo, new byte[] { (byte) '4' }); + jedis.rpush(bfoo, new byte[] { (byte) '3' }); + jedis.rpush(bfoo, new byte[] { (byte) '2' }); + jedis.rpush(bfoo, new byte[] { (byte) '1' }); - SortingParams bsp = new SortingParams(); - bsp.limit(0, 3); + SortingParams bsp = new SortingParams(); + bsp.limit(0, 3); - List bresult = jedis.sort(bfoo, bsp); + List bresult = jedis.sort(bfoo, bsp); - List bexpected = new ArrayList(); - bexpected.add(b1); - bexpected.add(b2); - bexpected.add(b3); + List bexpected = new ArrayList(); + bexpected.add(b1); + bexpected.add(b2); + bexpected.add(b3); - assertEquals(bexpected, bresult); + assertEquals(bexpected, bresult); } @Test public void sortAlpha() { - jedis.lpush("foo", "1"); - jedis.lpush("foo", "2"); - jedis.lpush("foo", "10"); + jedis.lpush("foo", "1"); + jedis.lpush("foo", "2"); + jedis.lpush("foo", "10"); - SortingParams sp = new SortingParams(); - sp.alpha(); + SortingParams sp = new SortingParams(); + sp.alpha(); - List result = jedis.sort("foo", sp); + List result = jedis.sort("foo", sp); - List expected = new ArrayList(); - expected.add("1"); - expected.add("10"); - expected.add("2"); + List expected = new ArrayList(); + expected.add("1"); + expected.add("10"); + expected.add("2"); - assertEquals(expected, result); + assertEquals(expected, result); - // Binary - jedis.lpush(bfoo, b1); - jedis.lpush(bfoo, b2); - jedis.lpush(bfoo, b10); + // Binary + jedis.lpush(bfoo, b1); + jedis.lpush(bfoo, b2); + jedis.lpush(bfoo, b10); - SortingParams bsp = new SortingParams(); - bsp.alpha(); + SortingParams bsp = new SortingParams(); + bsp.alpha(); - List bresult = jedis.sort(bfoo, bsp); + List bresult = jedis.sort(bfoo, bsp); - List bexpected = new ArrayList(); - bexpected.add(b1); - bexpected.add(b10); - bexpected.add(b2); + List bexpected = new ArrayList(); + bexpected.add(b1); + bexpected.add(b10); + bexpected.add(b2); - assertEquals(bexpected, bresult); + assertEquals(bexpected, bresult); } @Test public void sortGet() { - jedis.lpush("foo", "1"); - jedis.lpush("foo", "2"); - jedis.lpush("foo", "10"); + jedis.lpush("foo", "1"); + jedis.lpush("foo", "2"); + jedis.lpush("foo", "10"); - jedis.set("bar1", "bar1"); - jedis.set("bar2", "bar2"); - jedis.set("bar10", "bar10"); + jedis.set("bar1", "bar1"); + jedis.set("bar2", "bar2"); + jedis.set("bar10", "bar10"); - jedis.set("car1", "car1"); - jedis.set("car2", "car2"); - jedis.set("car10", "car10"); + jedis.set("car1", "car1"); + jedis.set("car2", "car2"); + jedis.set("car10", "car10"); - SortingParams sp = new SortingParams(); - sp.get("car*", "bar*"); + SortingParams sp = new SortingParams(); + sp.get("car*", "bar*"); - List result = jedis.sort("foo", sp); + List result = jedis.sort("foo", sp); - List expected = new ArrayList(); - expected.add("car1"); - expected.add("bar1"); - expected.add("car2"); - expected.add("bar2"); - expected.add("car10"); - expected.add("bar10"); + List expected = new ArrayList(); + expected.add("car1"); + expected.add("bar1"); + expected.add("car2"); + expected.add("bar2"); + expected.add("car10"); + expected.add("bar10"); - assertEquals(expected, result); + assertEquals(expected, result); - // Binary - jedis.lpush(bfoo, b1); - jedis.lpush(bfoo, b2); - jedis.lpush(bfoo, b10); + // Binary + jedis.lpush(bfoo, b1); + jedis.lpush(bfoo, b2); + jedis.lpush(bfoo, b10); - jedis.set(bbar1, bbar1); - jedis.set(bbar2, bbar2); - jedis.set(bbar10, bbar10); + jedis.set(bbar1, bbar1); + jedis.set(bbar2, bbar2); + jedis.set(bbar10, bbar10); - jedis.set(bcar1, bcar1); - jedis.set(bcar2, bcar2); - jedis.set(bcar10, bcar10); + jedis.set(bcar1, bcar1); + jedis.set(bcar2, bcar2); + jedis.set(bcar10, bcar10); - SortingParams bsp = new SortingParams(); - bsp.get(bcarstar, bbarstar); + SortingParams bsp = new SortingParams(); + bsp.get(bcarstar, bbarstar); - List bresult = jedis.sort(bfoo, bsp); + List bresult = jedis.sort(bfoo, bsp); - List bexpected = new ArrayList(); - bexpected.add(bcar1); - bexpected.add(bbar1); - bexpected.add(bcar2); - bexpected.add(bbar2); - bexpected.add(bcar10); - bexpected.add(bbar10); + List bexpected = new ArrayList(); + bexpected.add(bcar1); + bexpected.add(bbar1); + bexpected.add(bcar2); + bexpected.add(bbar2); + bexpected.add(bcar10); + bexpected.add(bbar10); - assertEquals(bexpected, bresult); + assertEquals(bexpected, bresult); } @Test public void sortStore() { - jedis.lpush("foo", "1"); - jedis.lpush("foo", "2"); - jedis.lpush("foo", "10"); + jedis.lpush("foo", "1"); + jedis.lpush("foo", "2"); + jedis.lpush("foo", "10"); - long result = jedis.sort("foo", "result"); + long result = jedis.sort("foo", "result"); - List expected = new ArrayList(); - expected.add("1"); - expected.add("2"); - expected.add("10"); + List expected = new ArrayList(); + expected.add("1"); + expected.add("2"); + expected.add("10"); - assertEquals(3, result); - assertEquals(expected, jedis.lrange("result", 0, 1000)); + assertEquals(3, result); + assertEquals(expected, jedis.lrange("result", 0, 1000)); - // Binary - jedis.lpush(bfoo, b1); - jedis.lpush(bfoo, b2); - jedis.lpush(bfoo, b10); + // Binary + jedis.lpush(bfoo, b1); + jedis.lpush(bfoo, b2); + jedis.lpush(bfoo, b10); - byte[] bkresult = new byte[] { 0X09, 0x0A, 0x0B, 0x0C }; - long bresult = jedis.sort(bfoo, bkresult); + byte[] bkresult = new byte[] { 0X09, 0x0A, 0x0B, 0x0C }; + long bresult = jedis.sort(bfoo, bkresult); - List bexpected = new ArrayList(); - bexpected.add(b1); - bexpected.add(b2); - bexpected.add(b10); + List bexpected = new ArrayList(); + bexpected.add(b1); + bexpected.add(b2); + bexpected.add(b10); - assertEquals(3, bresult); - assertEquals(bexpected, jedis.lrange(bkresult, 0, 1000)); + assertEquals(3, bresult); + assertEquals(bexpected, jedis.lrange(bkresult, 0, 1000)); } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/commands/StringValuesCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/StringValuesCommandsTest.java index e34eb7b..625fcc9 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/StringValuesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/StringValuesCommandsTest.java @@ -10,200 +10,200 @@ import redis.clients.jedis.exceptions.JedisDataException; public class StringValuesCommandsTest extends JedisCommandTestBase { @Test public void setAndGet() { - String status = jedis.set("foo", "bar"); - assertEquals("OK", status); + String status = jedis.set("foo", "bar"); + assertEquals("OK", status); - String value = jedis.get("foo"); - assertEquals("bar", value); + String value = jedis.get("foo"); + assertEquals("bar", value); - assertEquals(null, jedis.get("bar")); + assertEquals(null, jedis.get("bar")); } @Test public void getSet() { - String value = jedis.getSet("foo", "bar"); - assertEquals(null, value); - value = jedis.get("foo"); - assertEquals("bar", value); + String value = jedis.getSet("foo", "bar"); + assertEquals(null, value); + value = jedis.get("foo"); + assertEquals("bar", value); } @Test public void mget() { - List values = jedis.mget("foo", "bar"); - List expected = new ArrayList(); - expected.add(null); - expected.add(null); + List values = jedis.mget("foo", "bar"); + List expected = new ArrayList(); + expected.add(null); + expected.add(null); - assertEquals(expected, values); + assertEquals(expected, values); - jedis.set("foo", "bar"); + jedis.set("foo", "bar"); - expected = new ArrayList(); - expected.add("bar"); - expected.add(null); - values = jedis.mget("foo", "bar"); + expected = new ArrayList(); + expected.add("bar"); + expected.add(null); + values = jedis.mget("foo", "bar"); - assertEquals(expected, values); + assertEquals(expected, values); - jedis.set("bar", "foo"); + jedis.set("bar", "foo"); - expected = new ArrayList(); - expected.add("bar"); - expected.add("foo"); - values = jedis.mget("foo", "bar"); + expected = new ArrayList(); + expected.add("bar"); + expected.add("foo"); + values = jedis.mget("foo", "bar"); - assertEquals(expected, values); + assertEquals(expected, values); } @Test public void setnx() { - long status = jedis.setnx("foo", "bar"); - assertEquals(1, status); - assertEquals("bar", jedis.get("foo")); + long status = jedis.setnx("foo", "bar"); + assertEquals(1, status); + assertEquals("bar", jedis.get("foo")); - status = jedis.setnx("foo", "bar2"); - assertEquals(0, status); - assertEquals("bar", jedis.get("foo")); + status = jedis.setnx("foo", "bar2"); + assertEquals(0, status); + assertEquals("bar", jedis.get("foo")); } @Test public void setex() { - String status = jedis.setex("foo", 20, "bar"); - assertEquals("OK", status); - long ttl = jedis.ttl("foo"); - assertTrue(ttl > 0 && ttl <= 20); + String status = jedis.setex("foo", 20, "bar"); + assertEquals("OK", status); + long ttl = jedis.ttl("foo"); + assertTrue(ttl > 0 && ttl <= 20); } @Test public void mset() { - String status = jedis.mset("foo", "bar", "bar", "foo"); - assertEquals("OK", status); - assertEquals("bar", jedis.get("foo")); - assertEquals("foo", jedis.get("bar")); + String status = jedis.mset("foo", "bar", "bar", "foo"); + assertEquals("OK", status); + assertEquals("bar", jedis.get("foo")); + assertEquals("foo", jedis.get("bar")); } @Test public void msetnx() { - long status = jedis.msetnx("foo", "bar", "bar", "foo"); - assertEquals(1, status); - assertEquals("bar", jedis.get("foo")); - assertEquals("foo", jedis.get("bar")); + long status = jedis.msetnx("foo", "bar", "bar", "foo"); + assertEquals(1, status); + assertEquals("bar", jedis.get("foo")); + assertEquals("foo", jedis.get("bar")); - status = jedis.msetnx("foo", "bar1", "bar2", "foo2"); - assertEquals(0, status); - assertEquals("bar", jedis.get("foo")); - assertEquals("foo", jedis.get("bar")); + status = jedis.msetnx("foo", "bar1", "bar2", "foo2"); + assertEquals(0, status); + assertEquals("bar", jedis.get("foo")); + assertEquals("foo", jedis.get("bar")); } @Test(expected = JedisDataException.class) public void incrWrongValue() { - jedis.set("foo", "bar"); - jedis.incr("foo"); + jedis.set("foo", "bar"); + jedis.incr("foo"); } @Test public void incr() { - long value = jedis.incr("foo"); - assertEquals(1, value); - value = jedis.incr("foo"); - assertEquals(2, value); + long value = jedis.incr("foo"); + assertEquals(1, value); + value = jedis.incr("foo"); + assertEquals(2, value); } @Test(expected = JedisDataException.class) public void incrByWrongValue() { - jedis.set("foo", "bar"); - jedis.incrBy("foo", 2); + jedis.set("foo", "bar"); + jedis.incrBy("foo", 2); } @Test public void incrBy() { - long value = jedis.incrBy("foo", 2); - assertEquals(2, value); - value = jedis.incrBy("foo", 2); - assertEquals(4, value); + long value = jedis.incrBy("foo", 2); + assertEquals(2, value); + value = jedis.incrBy("foo", 2); + assertEquals(4, value); } @Test(expected = JedisDataException.class) public void decrWrongValue() { - jedis.set("foo", "bar"); - jedis.decr("foo"); + jedis.set("foo", "bar"); + jedis.decr("foo"); } @Test public void decr() { - long value = jedis.decr("foo"); - assertEquals(-1, value); - value = jedis.decr("foo"); - assertEquals(-2, value); + long value = jedis.decr("foo"); + assertEquals(-1, value); + value = jedis.decr("foo"); + assertEquals(-2, value); } @Test(expected = JedisDataException.class) public void decrByWrongValue() { - jedis.set("foo", "bar"); - jedis.decrBy("foo", 2); + jedis.set("foo", "bar"); + jedis.decrBy("foo", 2); } @Test public void decrBy() { - long value = jedis.decrBy("foo", 2); - assertEquals(-2, value); - value = jedis.decrBy("foo", 2); - assertEquals(-4, value); + long value = jedis.decrBy("foo", 2); + assertEquals(-2, value); + value = jedis.decrBy("foo", 2); + assertEquals(-4, value); } @Test public void append() { - long value = jedis.append("foo", "bar"); - assertEquals(3, value); - assertEquals("bar", jedis.get("foo")); - value = jedis.append("foo", "bar"); - assertEquals(6, value); - assertEquals("barbar", jedis.get("foo")); + long value = jedis.append("foo", "bar"); + assertEquals(3, value); + assertEquals("bar", jedis.get("foo")); + value = jedis.append("foo", "bar"); + assertEquals(6, value); + assertEquals("barbar", jedis.get("foo")); } @Test public void substr() { - jedis.set("s", "This is a string"); - assertEquals("This", jedis.substr("s", 0, 3)); - assertEquals("ing", jedis.substr("s", -3, -1)); - assertEquals("This is a string", jedis.substr("s", 0, -1)); - assertEquals(" string", jedis.substr("s", 9, 100000)); + jedis.set("s", "This is a string"); + assertEquals("This", jedis.substr("s", 0, 3)); + assertEquals("ing", jedis.substr("s", -3, -1)); + assertEquals("This is a string", jedis.substr("s", 0, -1)); + assertEquals(" string", jedis.substr("s", 9, 100000)); } @Test public void strlen() { - jedis.set("s", "This is a string"); - assertEquals("This is a string".length(), jedis.strlen("s").intValue()); + jedis.set("s", "This is a string"); + assertEquals("This is a string".length(), jedis.strlen("s").intValue()); } @Test public void incrLargeNumbers() { - long value = jedis.incr("foo"); - assertEquals(1, value); - assertEquals(1L + Integer.MAX_VALUE, (long) jedis.incrBy("foo", - Integer.MAX_VALUE)); + long value = jedis.incr("foo"); + assertEquals(1, value); + assertEquals(1L + Integer.MAX_VALUE, + (long) jedis.incrBy("foo", Integer.MAX_VALUE)); } @Test(expected = JedisDataException.class) public void incrReallyLargeNumbers() { - jedis.set("foo", Long.toString(Long.MAX_VALUE)); - long value = jedis.incr("foo"); - assertEquals(Long.MIN_VALUE, value); + jedis.set("foo", Long.toString(Long.MAX_VALUE)); + long value = jedis.incr("foo"); + assertEquals(Long.MIN_VALUE, value); } - + @Test public void incrByFloat() { - double value = jedis.incrByFloat("foo", 10.5); - assertEquals(10.5, value, 0.0); - value = jedis.incrByFloat("foo", 0.1); - assertEquals(10.6, value, 0.0); + double value = jedis.incrByFloat("foo", 10.5); + assertEquals(10.5, value, 0.0); + value = jedis.incrByFloat("foo", 0.1); + assertEquals(10.6, value, 0.0); } - + @Test public void psetex() { - String status = jedis.psetex("foo", 20000, "bar"); - assertEquals("OK", status); - long ttl = jedis.ttl("foo"); - assertTrue(ttl > 0 && ttl <= 20000); + String status = jedis.psetex("foo", 20000, "bar"); + assertEquals("OK", status); + long ttl = jedis.ttl("foo"); + assertTrue(ttl > 0 && ttl <= 20000); } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java index fb52063..ac3419e 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java @@ -11,13 +11,12 @@ import org.junit.Before; import org.junit.Test; import redis.clients.jedis.Jedis; -import redis.clients.jedis.Protocol.Keyword; import redis.clients.jedis.Pipeline; +import redis.clients.jedis.Protocol.Keyword; import redis.clients.jedis.Response; import redis.clients.jedis.Transaction; import redis.clients.jedis.TransactionBlock; import redis.clients.jedis.exceptions.JedisDataException; -import redis.clients.jedis.exceptions.JedisException; public class TransactionCommandsTest extends JedisCommandTestBase { final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; @@ -296,48 +295,48 @@ public class TransactionCommandsTest extends JedisCommandTestBase { assertNull(results); } - + @Test public void testResetStateWhenInMulti() { - jedis.auth("foobared"); - - Transaction t = jedis.multi(); - t.set("foooo", "barrr"); - - jedis.resetState(); - assertEquals(null, jedis.get("foooo")); + jedis.auth("foobared"); + + Transaction t = jedis.multi(); + t.set("foooo", "barrr"); + + jedis.resetState(); + assertEquals(null, jedis.get("foooo")); } - + @Test public void testResetStateWhenInMultiWithinPipeline() { - jedis.auth("foobared"); - - Pipeline p = jedis.pipelined(); - p.multi(); - p.set("foooo", "barrr"); + jedis.auth("foobared"); - jedis.resetState(); - assertEquals(null, jedis.get("foooo")); + Pipeline p = jedis.pipelined(); + p.multi(); + p.set("foooo", "barrr"); + + jedis.resetState(); + assertEquals(null, jedis.get("foooo")); } @Test public void testResetStateWhenInWatch() { - jedis.watch("mykey", "somekey"); - - // state reset : unwatch - jedis.resetState(); - - Transaction t = jedis.multi(); + jedis.watch("mykey", "somekey"); - nj.connect(); - nj.auth("foobared"); - nj.set("mykey", "bar"); - nj.disconnect(); + // state reset : unwatch + jedis.resetState(); - t.set("mykey", "foo"); - List resp = t.exec(); - assertNotNull(resp); - assertEquals(1, resp.size()); - assertEquals("foo", jedis.get("mykey")); + Transaction t = jedis.multi(); + + nj.connect(); + nj.auth("foobared"); + nj.set("mykey", "bar"); + nj.disconnect(); + + t.set("mykey", "foo"); + List resp = t.exec(); + assertNotNull(resp); + assertEquals(1, resp.size()); + assertEquals("foo", jedis.get("mykey")); } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/commands/VariadicCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/VariadicCommandsTest.java index 5e84ec9..43bb705 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/VariadicCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/VariadicCommandsTest.java @@ -10,181 +10,181 @@ import java.util.Set; import org.junit.Test; public class VariadicCommandsTest 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[] bcar = { 0x09, 0x0A, 0x0B, 0x0C }; final byte[] bfoo1 = { 0x01, 0x02, 0x03, 0x04, 0x0A }; final byte[] bfoo2 = { 0x01, 0x02, 0x03, 0x04, 0x0B }; - - @Test + + @Test public void hdel() { - Map hash = new HashMap(); - hash.put("bar", "car"); - hash.put("car", "bar"); - hash.put("foo2", "bar"); - jedis.hmset("foo", hash); + Map hash = new HashMap(); + hash.put("bar", "car"); + hash.put("car", "bar"); + hash.put("foo2", "bar"); + jedis.hmset("foo", hash); - assertEquals(0, jedis.hdel("bar", "foo", "foo1").intValue()); - assertEquals(0, jedis.hdel("foo", "foo", "foo1").intValue()); - assertEquals(2, jedis.hdel("foo", "bar", "foo2").intValue()); - assertEquals(null, jedis.hget("foo", "bar")); + assertEquals(0, jedis.hdel("bar", "foo", "foo1").intValue()); + assertEquals(0, jedis.hdel("foo", "foo", "foo1").intValue()); + assertEquals(2, jedis.hdel("foo", "bar", "foo2").intValue()); + assertEquals(null, jedis.hget("foo", "bar")); - // Binary - Map bhash = new HashMap(); - bhash.put(bbar, bcar); - bhash.put(bcar, bbar); - bhash.put(bfoo2, bbar); - jedis.hmset(bfoo, bhash); + // Binary + Map bhash = new HashMap(); + bhash.put(bbar, bcar); + bhash.put(bcar, bbar); + bhash.put(bfoo2, bbar); + jedis.hmset(bfoo, bhash); - assertEquals(0, jedis.hdel(bbar, bfoo, bfoo1).intValue()); - assertEquals(0, jedis.hdel(bfoo, bfoo, bfoo1).intValue()); - assertEquals(2, jedis.hdel(bfoo, bbar, bfoo2).intValue()); - assertEquals(null, jedis.hget(bfoo, bbar)); + assertEquals(0, jedis.hdel(bbar, bfoo, bfoo1).intValue()); + assertEquals(0, jedis.hdel(bfoo, bfoo, bfoo1).intValue()); + assertEquals(2, jedis.hdel(bfoo, bbar, bfoo2).intValue()); + assertEquals(null, jedis.hget(bfoo, bbar)); } - - @Test + + @Test public void rpush() { - long size = jedis.rpush("foo", "bar", "foo"); - assertEquals(2, size); - - List expected = new ArrayList(); - expected.add("bar"); - expected.add("foo"); - - List values = jedis.lrange("foo",0,-1); - assertEquals(expected, values); - - // Binary - size = jedis.rpush(bfoo, bbar, bfoo); - assertEquals(2, size); - - List bexpected = new ArrayList(); - bexpected.add(bbar); - bexpected.add(bfoo); + long size = jedis.rpush("foo", "bar", "foo"); + assertEquals(2, size); - List bvalues = jedis.lrange(bfoo, 0, -1); - assertEquals(bexpected, bvalues); + List expected = new ArrayList(); + expected.add("bar"); + expected.add("foo"); + + List values = jedis.lrange("foo", 0, -1); + assertEquals(expected, values); + + // Binary + size = jedis.rpush(bfoo, bbar, bfoo); + assertEquals(2, size); + + List bexpected = new ArrayList(); + bexpected.add(bbar); + bexpected.add(bfoo); + + List bvalues = jedis.lrange(bfoo, 0, -1); + assertEquals(bexpected, bvalues); } - - @Test + + @Test public void lpush() { - long size = jedis.lpush("foo", "bar", "foo"); - assertEquals(2, size); - - List expected = new ArrayList(); - expected.add("foo"); - expected.add("bar"); - - List values = jedis.lrange("foo",0,-1); - assertEquals(expected, values); - - // Binary - size = jedis.lpush(bfoo, bbar, bfoo); - assertEquals(2, size); - - List bexpected = new ArrayList(); - bexpected.add(bfoo); - bexpected.add(bbar); + long size = jedis.lpush("foo", "bar", "foo"); + assertEquals(2, size); + + List expected = new ArrayList(); + expected.add("foo"); + expected.add("bar"); + + List values = jedis.lrange("foo", 0, -1); + assertEquals(expected, values); + + // Binary + size = jedis.lpush(bfoo, bbar, bfoo); + assertEquals(2, size); + + List bexpected = new ArrayList(); + bexpected.add(bfoo); + bexpected.add(bbar); + + List bvalues = jedis.lrange(bfoo, 0, -1); + assertEquals(bexpected, bvalues); - List bvalues = jedis.lrange(bfoo, 0, -1); - assertEquals(bexpected, bvalues); - } - - @Test + + @Test public void sadd() { - long status = jedis.sadd("foo", "bar", "foo1"); - assertEquals(2, status); + long status = jedis.sadd("foo", "bar", "foo1"); + assertEquals(2, status); - status = jedis.sadd("foo", "bar", "car"); - assertEquals(1, status); + status = jedis.sadd("foo", "bar", "car"); + assertEquals(1, status); - status = jedis.sadd("foo", "bar", "foo1"); - assertEquals(0, status); + status = jedis.sadd("foo", "bar", "foo1"); + assertEquals(0, status); - status = jedis.sadd(bfoo, bbar, bfoo1); - assertEquals(2, status); + status = jedis.sadd(bfoo, bbar, bfoo1); + assertEquals(2, status); - status = jedis.sadd(bfoo, bbar, bcar); - assertEquals(1, status); + status = jedis.sadd(bfoo, bbar, bcar); + assertEquals(1, status); - status = jedis.sadd(bfoo, bbar, bfoo1); - assertEquals(0, status); + status = jedis.sadd(bfoo, bbar, bfoo1); + assertEquals(0, status); } - - @Test + + @Test public void zadd() { - Map scoreMembers = new HashMap(); - scoreMembers.put("bar", 1d); - scoreMembers.put("foo", 10d); - - long status = jedis.zadd("foo", scoreMembers); - assertEquals(2, status); + Map scoreMembers = new HashMap(); + scoreMembers.put("bar", 1d); + scoreMembers.put("foo", 10d); - scoreMembers.clear(); - scoreMembers.put("car", 0.1d); - scoreMembers.put("bar", 2d); - - status = jedis.zadd("foo", scoreMembers); - assertEquals(1, status); + long status = jedis.zadd("foo", scoreMembers); + assertEquals(2, status); - Map bscoreMembers = new HashMap(); - bscoreMembers.put(bbar, 1d); - bscoreMembers.put(bfoo, 10d); - - status = jedis.zadd(bfoo, bscoreMembers); - assertEquals(2, status); + scoreMembers.clear(); + scoreMembers.put("car", 0.1d); + scoreMembers.put("bar", 2d); - bscoreMembers.clear(); - bscoreMembers.put(bcar, 0.1d); - bscoreMembers.put(bbar, 2d); - - status = jedis.zadd(bfoo, bscoreMembers); - assertEquals(1, status); + status = jedis.zadd("foo", scoreMembers); + assertEquals(1, status); + + Map bscoreMembers = new HashMap(); + bscoreMembers.put(bbar, 1d); + bscoreMembers.put(bfoo, 10d); + + status = jedis.zadd(bfoo, bscoreMembers); + assertEquals(2, status); + + bscoreMembers.clear(); + bscoreMembers.put(bcar, 0.1d); + bscoreMembers.put(bbar, 2d); + + status = jedis.zadd(bfoo, bscoreMembers); + assertEquals(1, status); } @Test public void zrem() { - jedis.zadd("foo", 1d, "bar"); - jedis.zadd("foo", 2d, "car"); - jedis.zadd("foo", 3d, "foo1"); + jedis.zadd("foo", 1d, "bar"); + jedis.zadd("foo", 2d, "car"); + jedis.zadd("foo", 3d, "foo1"); - long status = jedis.zrem("foo", "bar", "car"); + long status = jedis.zrem("foo", "bar", "car"); - Set expected = new LinkedHashSet(); - expected.add("foo1"); + Set expected = new LinkedHashSet(); + expected.add("foo1"); - assertEquals(2, status); - assertEquals(expected, jedis.zrange("foo", 0, 100)); + assertEquals(2, status); + assertEquals(expected, jedis.zrange("foo", 0, 100)); - status = jedis.zrem("foo", "bar", "car"); - assertEquals(0, status); - - status = jedis.zrem("foo", "bar", "foo1"); - assertEquals(1, status); + status = jedis.zrem("foo", "bar", "car"); + assertEquals(0, status); - //Binary - jedis.zadd(bfoo, 1d, bbar); - jedis.zadd(bfoo, 2d, bcar); - jedis.zadd(bfoo, 3d, bfoo1); + status = jedis.zrem("foo", "bar", "foo1"); + assertEquals(1, status); - status = jedis.zrem(bfoo, bbar, bcar); + // Binary + jedis.zadd(bfoo, 1d, bbar); + jedis.zadd(bfoo, 2d, bcar); + jedis.zadd(bfoo, 3d, bfoo1); - Set bexpected = new LinkedHashSet(); - bexpected.add(bfoo); + status = jedis.zrem(bfoo, bbar, bcar); - assertEquals(2, status); - assertEquals(bexpected, jedis.zrange(bfoo, 0, 100)); + Set bexpected = new LinkedHashSet(); + bexpected.add(bfoo); - status = jedis.zrem(bfoo, bbar, bcar); - assertEquals(0, status); - - status = jedis.zrem(bfoo, bbar, bfoo1); - assertEquals(1, status); + assertEquals(2, status); + assertEquals(bexpected, jedis.zrange(bfoo, 0, 100)); - } + status = jedis.zrem(bfoo, bbar, bcar); + assertEquals(0, status); + + status = jedis.zrem(bfoo, bbar, bfoo1); + assertEquals(1, status); + + } } \ No newline at end of file From 8bec9fd373e91297ef0f1f8fa7fd41ae707542a2 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Sat, 1 Feb 2014 20:13:56 -0300 Subject: [PATCH 016/120] Implement missing pubsub commands and fix indentation --- .../redis/clients/jedis/BinaryClient.java | 5 +- .../redis/clients/jedis/BuilderFactory.java | 21 +++ src/main/java/redis/clients/jedis/Client.java | 26 +++- src/main/java/redis/clients/jedis/Jedis.java | 27 +++- .../java/redis/clients/jedis/Protocol.java | 7 +- .../PublishSubscribeCommandsTest.java | 123 +++++++++++++++++- 6 files changed, 197 insertions(+), 12 deletions(-) diff --git a/src/main/java/redis/clients/jedis/BinaryClient.java b/src/main/java/redis/clients/jedis/BinaryClient.java index 56f97af..2a65d96 100644 --- a/src/main/java/redis/clients/jedis/BinaryClient.java +++ b/src/main/java/redis/clients/jedis/BinaryClient.java @@ -554,7 +554,10 @@ public class BinaryClient extends Connection { public void punsubscribe(final byte[]... patterns) { sendCommand(PUNSUBSCRIBE, patterns); } - + + public void pubSub(final byte[]... args) { + sendCommand(PUBSUB, args); + } public void zcount(final byte[] key, final double min, final double max) { byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); diff --git a/src/main/java/redis/clients/jedis/BuilderFactory.java b/src/main/java/redis/clients/jedis/BuilderFactory.java index bebd2d6..27c728b 100755 --- a/src/main/java/redis/clients/jedis/BuilderFactory.java +++ b/src/main/java/redis/clients/jedis/BuilderFactory.java @@ -2,6 +2,7 @@ package redis.clients.jedis; import redis.clients.util.SafeEncoder; +import java.nio.ByteBuffer; import java.util.*; public class BuilderFactory { @@ -96,6 +97,26 @@ public class BuilderFactory { } }; + + public static final Builder> STRING_LONG_MAP = new Builder>() { + @SuppressWarnings("unchecked") + public Map build(Object data) { + final List flatHash = (List) data; + final Map hash = new HashMap(); + final Iterator iterator = flatHash.iterator(); + while (iterator.hasNext()) { + hash.put(SafeEncoder.encode(iterator.next()), Long.valueOf(SafeEncoder.encode(iterator.next()))); + } + + return hash; + } + + public String toString() { + return "Map"; + } + + }; + public static final Builder> STRING_SET = new Builder>() { @SuppressWarnings("unchecked") public Set build(Object data) { diff --git a/src/main/java/redis/clients/jedis/Client.java b/src/main/java/redis/clients/jedis/Client.java index a2ec464..85f6a2b 100644 --- a/src/main/java/redis/clients/jedis/Client.java +++ b/src/main/java/redis/clients/jedis/Client.java @@ -1,6 +1,6 @@ package redis.clients.jedis; -import redis.clients.util.SafeEncoder; +import static redis.clients.jedis.Protocol.toByteArray; import java.util.ArrayList; import java.util.HashMap; @@ -8,8 +8,7 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; -import static redis.clients.jedis.Protocol.toByteArray; -import static redis.clients.jedis.Protocol.Command.HSCAN; +import redis.clients.util.SafeEncoder; public class Client extends BinaryClient implements Commands { public Client(final String host) { @@ -671,6 +670,18 @@ public class Client extends BinaryClient implements Commands { } subscribe(cs); } + + public void pubSubChannels(String pattern) { + pubSub(Protocol.PUBSUB_CHANNELS, pattern); + } + + public void pubSubNumPat() { + pubSub(Protocol.PUBSUB_NUM_PAT); + } + + public void pubSubNumSub(String... channels) { + pubSub(Protocol.PUBSUB_NUMSUB, channels); + } public void configSet(String parameter, String value) { configSet(SafeEncoder.encode(parameter), SafeEncoder.encode(value)); @@ -831,6 +842,15 @@ public class Client extends BinaryClient implements Commands { arg[0] = SafeEncoder.encode(subcommand); cluster(arg); } + + public void pubSub(final String subcommand, final String... args) { + final byte[][] arg = new byte[args.length+1][]; + for (int i = 1; i < arg.length; i++) { + arg[i] = SafeEncoder.encode(args[i-1]); + } + arg[0] = SafeEncoder.encode(subcommand); + pubSub(arg); + } public void cluster(final String subcommand, final String... args) { final byte[][] arg = new byte[args.length+1][]; diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index cdc3918..6191132 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -13,8 +13,6 @@ import java.util.Set; import redis.clients.jedis.BinaryClient.LIST_POSITION; import redis.clients.util.SafeEncoder; import redis.clients.util.Slowlog; -import java.net.URI; -import java.util.*; public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommands, AdvancedJedisCommands, ScriptingCommands, BasicCommands, ClusterCommands { public Jedis(final String host) { @@ -3209,9 +3207,28 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand return client.getStatusCodeReply(); } - public String asking() { - checkIsInMulti(); + public String asking() { + checkIsInMulti(); client.asking(); return client.getStatusCodeReply(); - } + } + + public List pubSubChannels(String pattern) { + checkIsInMulti(); + client.pubSubChannels(pattern); + return client.getMultiBulkReply(); + } + + public Long pubSubNumPat() { + checkIsInMulti(); + client.pubSubNumPat(); + return client.getIntegerReply(); + } + + public Map pubSubNumSub(String... channels) { + checkIsInMulti(); + client.pubSubNumSub(channels); + return BuilderFactory.STRING_LONG_MAP + .build(client.getBinaryMultiBulkReply()); + } } diff --git a/src/main/java/redis/clients/jedis/Protocol.java b/src/main/java/redis/clients/jedis/Protocol.java index a5e08c6..6a99f01 100644 --- a/src/main/java/redis/clients/jedis/Protocol.java +++ b/src/main/java/redis/clients/jedis/Protocol.java @@ -45,6 +45,11 @@ public final class Protocol { public static final String CLUSTER_SETSLOT_MIGRATING = "migrating"; public static final String CLUSTER_SETSLOT_IMPORTING = "importing"; + public static final String PUBSUB_CHANNELS= "channels"; + public static final String PUBSUB_NUMSUB = "numsub"; + public static final String PUBSUB_NUM_PAT = "numpat"; + + private Protocol() { // this prevent the class from instantiation } @@ -191,7 +196,7 @@ public final class Protocol { } public static enum Command { - PING, SET, GET, QUIT, EXISTS, DEL, TYPE, FLUSHDB, KEYS, RANDOMKEY, RENAME, RENAMENX, RENAMEX, DBSIZE, EXPIRE, EXPIREAT, TTL, SELECT, MOVE, FLUSHALL, GETSET, MGET, SETNX, SETEX, MSET, MSETNX, DECRBY, DECR, INCRBY, INCR, APPEND, SUBSTR, HSET, HGET, HSETNX, HMSET, HMGET, HINCRBY, HEXISTS, HDEL, HLEN, HKEYS, HVALS, HGETALL, RPUSH, LPUSH, LLEN, LRANGE, LTRIM, LINDEX, LSET, LREM, LPOP, RPOP, RPOPLPUSH, SADD, SMEMBERS, SREM, SPOP, SMOVE, SCARD, SISMEMBER, SINTER, SINTERSTORE, SUNION, SUNIONSTORE, SDIFF, SDIFFSTORE, SRANDMEMBER, ZADD, ZRANGE, ZREM, ZINCRBY, ZRANK, ZREVRANK, ZREVRANGE, ZCARD, ZSCORE, MULTI, DISCARD, EXEC, WATCH, UNWATCH, SORT, BLPOP, BRPOP, AUTH, SUBSCRIBE, PUBLISH, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, ZCOUNT, ZRANGEBYSCORE, ZREVRANGEBYSCORE, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZUNIONSTORE, ZINTERSTORE, SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE, SHUTDOWN, INFO, MONITOR, SLAVEOF, CONFIG, STRLEN, SYNC, LPUSHX, PERSIST, RPUSHX, ECHO, LINSERT, DEBUG, BRPOPLPUSH, SETBIT, GETBIT, SETRANGE, GETRANGE, EVAL, EVALSHA, SCRIPT, SLOWLOG, OBJECT, BITCOUNT, BITOP, SENTINEL, DUMP, RESTORE, PEXPIRE, PEXPIREAT, PTTL, INCRBYFLOAT, PSETEX, CLIENT, TIME, MIGRATE, HINCRBYFLOAT, SCAN, HSCAN, SSCAN, ZSCAN, WAIT, CLUSTER, ASKING; + PING, SET, GET, QUIT, EXISTS, DEL, TYPE, FLUSHDB, KEYS, RANDOMKEY, RENAME, RENAMENX, RENAMEX, DBSIZE, EXPIRE, EXPIREAT, TTL, SELECT, MOVE, FLUSHALL, GETSET, MGET, SETNX, SETEX, MSET, MSETNX, DECRBY, DECR, INCRBY, INCR, APPEND, SUBSTR, HSET, HGET, HSETNX, HMSET, HMGET, HINCRBY, HEXISTS, HDEL, HLEN, HKEYS, HVALS, HGETALL, RPUSH, LPUSH, LLEN, LRANGE, LTRIM, LINDEX, LSET, LREM, LPOP, RPOP, RPOPLPUSH, SADD, SMEMBERS, SREM, SPOP, SMOVE, SCARD, SISMEMBER, SINTER, SINTERSTORE, SUNION, SUNIONSTORE, SDIFF, SDIFFSTORE, SRANDMEMBER, ZADD, ZRANGE, ZREM, ZINCRBY, ZRANK, ZREVRANK, ZREVRANGE, ZCARD, ZSCORE, MULTI, DISCARD, EXEC, WATCH, UNWATCH, SORT, BLPOP, BRPOP, AUTH, SUBSCRIBE, PUBLISH, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, PUBSUB, ZCOUNT, ZRANGEBYSCORE, ZREVRANGEBYSCORE, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZUNIONSTORE, ZINTERSTORE, SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE, SHUTDOWN, INFO, MONITOR, SLAVEOF, CONFIG, STRLEN, SYNC, LPUSHX, PERSIST, RPUSHX, ECHO, LINSERT, DEBUG, BRPOPLPUSH, SETBIT, GETBIT, SETRANGE, GETRANGE, EVAL, EVALSHA, SCRIPT, SLOWLOG, OBJECT, BITCOUNT, BITOP, SENTINEL, DUMP, RESTORE, PEXPIRE, PEXPIREAT, PTTL, INCRBYFLOAT, PSETEX, CLIENT, TIME, MIGRATE, HINCRBYFLOAT, SCAN, HSCAN, SSCAN, ZSCAN, WAIT, CLUSTER, ASKING; public final byte[] raw; diff --git a/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java index 3ea14d5..749eda5 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java @@ -3,16 +3,17 @@ package redis.clients.jedis.tests.commands; import java.io.IOException; import java.net.UnknownHostException; import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.Ignore; import org.junit.Test; import redis.clients.jedis.BinaryJedisPubSub; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPubSub; import redis.clients.jedis.exceptions.JedisConnectionException; -import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.util.SafeEncoder; public class PublishSubscribeCommandsTest extends JedisCommandTestBase { @@ -63,6 +64,124 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { } }, "foo"); } + + + @Test + public void pubSubChannels(){ + final List expectedActiveChannels = Arrays.asList("testchan1", "testchan2", "testchan3"); + jedis.subscribe(new JedisPubSub() { + 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 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 + public void onUnsubscribe(String channel, int subscribedChannels) { + } + + @Override + public void onSubscribe(String channel, int subscribedChannels) { + } + + @Override + public void onPUnsubscribe(String pattern, int subscribedChannels) { + } + + @Override + public void onPSubscribe(String pattern, int subscribedChannels) { + count++; + if (count == 3) { + Jedis otherJedis = createJedis(); + Long numPatterns = otherJedis.pubSubNumPat(); + assertEquals(new Long(2l), numPatterns); + punsubscribe(); + } + } + + @Override + public void onPMessage(String pattern, String channel, String message) { + } + + @Override + public void onMessage(String channel, String message) { + } + }, "test*", "test*", "chan*"); + } + + @Test + public void pubSubNumSub(){ + final Map expectedNumSub = new HashMap(); + expectedNumSub.put("testchannel2", 1l); + expectedNumSub.put("testchannel1", 1l); + jedis.subscribe(new JedisPubSub() { + private int count=0; + @Override + public void onUnsubscribe(String channel, int subscribedChannels) { + } + + @Override + public void onSubscribe(String channel, int subscribedChannels) { + count++; + if (count == 2) { + Jedis otherJedis = createJedis(); + Map numSub = otherJedis.pubSubNumSub("testchannel1", "testchannel2"); + assertEquals(expectedNumSub, numSub); + 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) { + } + }, "testchannel1", "testchannel2"); + } @Test public void subscribeMany() throws UnknownHostException, IOException, From 319a241de0d3c52989e88622e4e450252f0714f5 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Sat, 1 Feb 2014 20:15:52 -0300 Subject: [PATCH 017/120] Remove unnecessary imports --- src/main/java/redis/clients/jedis/BuilderFactory.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/redis/clients/jedis/BuilderFactory.java b/src/main/java/redis/clients/jedis/BuilderFactory.java index 27c728b..1e8e5aa 100755 --- a/src/main/java/redis/clients/jedis/BuilderFactory.java +++ b/src/main/java/redis/clients/jedis/BuilderFactory.java @@ -2,7 +2,6 @@ package redis.clients.jedis; import redis.clients.util.SafeEncoder; -import java.nio.ByteBuffer; import java.util.*; public class BuilderFactory { From 4b53160a742cc8e169168d6316a93f5542fe5536 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Sat, 1 Feb 2014 20:50:36 -0300 Subject: [PATCH 018/120] Remove unnecessary Builder and fix merge issue. Fixes #520 --- .../redis/clients/jedis/BuilderFactory.java | 19 ------------------- src/main/java/redis/clients/jedis/Jedis.java | 4 ++-- .../java/redis/clients/jedis/Protocol.java | 2 +- .../PublishSubscribeCommandsTest.java | 8 ++++---- 4 files changed, 7 insertions(+), 26 deletions(-) diff --git a/src/main/java/redis/clients/jedis/BuilderFactory.java b/src/main/java/redis/clients/jedis/BuilderFactory.java index ad0024f..76d013e 100755 --- a/src/main/java/redis/clients/jedis/BuilderFactory.java +++ b/src/main/java/redis/clients/jedis/BuilderFactory.java @@ -104,25 +104,6 @@ public class BuilderFactory { }; - public static final Builder> STRING_LONG_MAP = new Builder>() { - @SuppressWarnings("unchecked") - public Map build(Object data) { - final List flatHash = (List) data; - final Map hash = new HashMap(); - final Iterator iterator = flatHash.iterator(); - while (iterator.hasNext()) { - hash.put(SafeEncoder.encode(iterator.next()), Long.valueOf(SafeEncoder.encode(iterator.next()))); - } - - return hash; - } - - public String toString() { - return "Map"; - } - - }; - public static final Builder> STRING_SET = new Builder>() { @SuppressWarnings("unchecked") public Set build(Object data) { diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index 709bf53..0996359 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -3245,10 +3245,10 @@ public class Jedis extends BinaryJedis implements JedisCommands, return client.getIntegerReply(); } - public Map pubSubNumSub(String... channels) { + public Map pubSubNumSub(String... channels) { checkIsInMulti(); client.pubSubNumSub(channels); - return BuilderFactory.STRING_LONG_MAP + return BuilderFactory.STRING_MAP .build(client.getBinaryMultiBulkReply()); } } diff --git a/src/main/java/redis/clients/jedis/Protocol.java b/src/main/java/redis/clients/jedis/Protocol.java index 49b7fd9..793b58f 100644 --- a/src/main/java/redis/clients/jedis/Protocol.java +++ b/src/main/java/redis/clients/jedis/Protocol.java @@ -200,7 +200,7 @@ public final class Protocol { } public static enum Command { - PING, SET, GET, QUIT, EXISTS, DEL, TYPE, FLUSHDB, KEYS, RANDOMKEY, RENAME, RENAMENX, RENAMEX, DBSIZE, EXPIRE, EXPIREAT, TTL, SELECT, MOVE, FLUSHALL, GETSET, MGET, SETNX, SETEX, MSET, MSETNX, DECRBY, DECR, INCRBY, INCR, APPEND, SUBSTR, HSET, HGET, HSETNX, HMSET, HMGET, HINCRBY, HEXISTS, HDEL, HLEN, HKEYS, HVALS, HGETALL, RPUSH, LPUSH, LLEN, LRANGE, LTRIM, LINDEX, LSET, LREM, LPOP, RPOP, RPOPLPUSH, SADD, SMEMBERS, SREM, SPOP, SMOVE, SCARD, SISMEMBER, SINTER, SINTERSTORE, SUNION, SUNIONSTORE, SDIFF, SDIFFSTORE, SRANDMEMBER, ZADD, ZRANGE, ZREM, ZINCRBY, ZRANK, ZREVRANK, ZREVRANGE, ZCARD, ZSCORE, MULTI, DISCARD, EXEC, WATCH, UNWATCH, SORT, BLPOP, BRPOP, AUTH, SUBSCRIBE, PUBLISH, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, ZCOUNT, ZRANGEBYSCORE, ZREVRANGEBYSCORE, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZUNIONSTORE, ZINTERSTORE, SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE, SHUTDOWN, INFO, MONITOR, SLAVEOF, CONFIG, STRLEN, SYNC, LPUSHX, PERSIST, RPUSHX, ECHO, LINSERT, DEBUG, BRPOPLPUSH, SETBIT, GETBIT, SETRANGE, GETRANGE, EVAL, EVALSHA, SCRIPT, SLOWLOG, OBJECT, BITCOUNT, BITOP, SENTINEL, DUMP, RESTORE, PEXPIRE, PEXPIREAT, PTTL, INCRBYFLOAT, PSETEX, CLIENT, TIME, MIGRATE, HINCRBYFLOAT, SCAN, HSCAN, SSCAN, ZSCAN, WAIT, CLUSTER, ASKING; + PING, SET, GET, QUIT, EXISTS, DEL, TYPE, FLUSHDB, KEYS, RANDOMKEY, RENAME, RENAMENX, RENAMEX, DBSIZE, EXPIRE, EXPIREAT, TTL, SELECT, MOVE, FLUSHALL, GETSET, MGET, SETNX, SETEX, MSET, MSETNX, DECRBY, DECR, INCRBY, INCR, APPEND, SUBSTR, HSET, HGET, HSETNX, HMSET, HMGET, HINCRBY, HEXISTS, HDEL, HLEN, HKEYS, HVALS, HGETALL, RPUSH, LPUSH, LLEN, LRANGE, LTRIM, LINDEX, LSET, LREM, LPOP, RPOP, RPOPLPUSH, SADD, SMEMBERS, SREM, SPOP, SMOVE, SCARD, SISMEMBER, SINTER, SINTERSTORE, SUNION, SUNIONSTORE, SDIFF, SDIFFSTORE, SRANDMEMBER, ZADD, ZRANGE, ZREM, ZINCRBY, ZRANK, ZREVRANK, ZREVRANGE, ZCARD, ZSCORE, MULTI, DISCARD, EXEC, WATCH, UNWATCH, SORT, BLPOP, BRPOP, AUTH, SUBSCRIBE, PUBLISH, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, PUBSUB, ZCOUNT, ZRANGEBYSCORE, ZREVRANGEBYSCORE, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZUNIONSTORE, ZINTERSTORE, SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE, SHUTDOWN, INFO, MONITOR, SLAVEOF, CONFIG, STRLEN, SYNC, LPUSHX, PERSIST, RPUSHX, ECHO, LINSERT, DEBUG, BRPOPLPUSH, SETBIT, GETBIT, SETRANGE, GETRANGE, EVAL, EVALSHA, SCRIPT, SLOWLOG, OBJECT, BITCOUNT, BITOP, SENTINEL, DUMP, RESTORE, PEXPIRE, PEXPIREAT, PTTL, INCRBYFLOAT, PSETEX, CLIENT, TIME, MIGRATE, HINCRBYFLOAT, SCAN, HSCAN, SSCAN, ZSCAN, WAIT, CLUSTER, ASKING; public final byte[] raw; diff --git a/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java index b85fc0c..2d3e0d6 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java @@ -145,9 +145,9 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { @Test public void pubSubNumSub(){ - final Map expectedNumSub = new HashMap(); - expectedNumSub.put("testchannel2", 1l); - expectedNumSub.put("testchannel1", 1l); + final Map expectedNumSub = new HashMap(); + expectedNumSub.put("testchannel2", "1"); + expectedNumSub.put("testchannel1", "1"); jedis.subscribe(new JedisPubSub() { private int count=0; @Override @@ -159,7 +159,7 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { count++; if (count == 2) { Jedis otherJedis = createJedis(); - Map numSub = otherJedis.pubSubNumSub("testchannel1", "testchannel2"); + Map numSub = otherJedis.pubSubNumSub("testchannel1", "testchannel2"); assertEquals(expectedNumSub, numSub); unsubscribe(); } From 4ab54d955d9e8dd01501b9a30e6f3f2576109464 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Mon, 3 Feb 2014 12:44:40 -0300 Subject: [PATCH 019/120] Change pubSub to pubsub --- .../java/redis/clients/jedis/BinaryClient.java | 2 +- src/main/java/redis/clients/jedis/Client.java | 16 ++++++++-------- src/main/java/redis/clients/jedis/Jedis.java | 12 ++++++------ .../commands/PublishSubscribeCommandsTest.java | 6 +++--- 4 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/main/java/redis/clients/jedis/BinaryClient.java b/src/main/java/redis/clients/jedis/BinaryClient.java index 19b6f55..26cd8f2 100644 --- a/src/main/java/redis/clients/jedis/BinaryClient.java +++ b/src/main/java/redis/clients/jedis/BinaryClient.java @@ -561,7 +561,7 @@ public class BinaryClient extends Connection { sendCommand(PUNSUBSCRIBE, patterns); } - public void pubSub(final byte[]... args) { + public void pubsub(final byte[]... args) { sendCommand(PUBSUB, args); } public void zcount(final byte[] key, final double min, final double max) { diff --git a/src/main/java/redis/clients/jedis/Client.java b/src/main/java/redis/clients/jedis/Client.java index e596baa..96d0560 100644 --- a/src/main/java/redis/clients/jedis/Client.java +++ b/src/main/java/redis/clients/jedis/Client.java @@ -673,16 +673,16 @@ public class Client extends BinaryClient implements Commands { subscribe(cs); } - public void pubSubChannels(String pattern) { - pubSub(Protocol.PUBSUB_CHANNELS, pattern); + public void pubsubChannels(String pattern) { + pubsub(Protocol.PUBSUB_CHANNELS, pattern); } - public void pubSubNumPat() { - pubSub(Protocol.PUBSUB_NUM_PAT); + public void pubsubNumPat() { + pubsub(Protocol.PUBSUB_NUM_PAT); } - public void pubSubNumSub(String... channels) { - pubSub(Protocol.PUBSUB_NUMSUB, channels); + public void pubsubNumSub(String... channels) { + pubsub(Protocol.PUBSUB_NUMSUB, channels); } public void configSet(String parameter, String value) { @@ -854,13 +854,13 @@ public class Client extends BinaryClient implements Commands { 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][]; for (int i = 1; i < arg.length; i++) { arg[i] = SafeEncoder.encode(args[i-1]); } arg[0] = SafeEncoder.encode(subcommand); - pubSub(arg); + pubsub(arg); } public void cluster(final String subcommand, final String... args) { diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index 0996359..d5f7283 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -3233,21 +3233,21 @@ public class Jedis extends BinaryJedis implements JedisCommands, return client.getStatusCodeReply(); } - public List pubSubChannels(String pattern) { + public List pubsubChannels(String pattern) { checkIsInMulti(); - client.pubSubChannels(pattern); + client.pubsubChannels(pattern); return client.getMultiBulkReply(); } - public Long pubSubNumPat() { + public Long pubsubNumPat() { checkIsInMulti(); - client.pubSubNumPat(); + client.pubsubNumPat(); return client.getIntegerReply(); } - public Map pubSubNumSub(String... channels) { + public Map pubsubNumSub(String... channels) { checkIsInMulti(); - client.pubSubNumSub(channels); + client.pubsubNumSub(channels); return BuilderFactory.STRING_MAP .build(client.getBinaryMultiBulkReply()); } diff --git a/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java index 2d3e0d6..5149ff2 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java @@ -82,7 +82,7 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { //All channels are subscribed if (count == 3) { Jedis otherJedis = createJedis(); - List activeChannels = otherJedis.pubSubChannels("test*"); + List activeChannels = otherJedis.pubsubChannels("test*"); assertTrue(expectedActiveChannels.containsAll(activeChannels)); unsubscribe(); } @@ -127,7 +127,7 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { count++; if (count == 3) { Jedis otherJedis = createJedis(); - Long numPatterns = otherJedis.pubSubNumPat(); + Long numPatterns = otherJedis.pubsubNumPat(); assertEquals(new Long(2l), numPatterns); punsubscribe(); } @@ -159,7 +159,7 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { count++; if (count == 2) { Jedis otherJedis = createJedis(); - Map numSub = otherJedis.pubSubNumSub("testchannel1", "testchannel2"); + Map numSub = otherJedis.pubsubNumSub("testchannel1", "testchannel2"); assertEquals(expectedNumSub, numSub); unsubscribe(); } From 56cec8f6ec80695d145f958dec5ec98700633845 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Mon, 3 Feb 2014 10:50:59 -0500 Subject: [PATCH 020/120] version bump to 2.3.0-snapshot --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index f6575eb..169987a 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ jar redis.clients jedis - 2.2.2-SNAPSHOT + 2.3.0-SNAPSHOT Jedis Jedis is a blazingly small and sane Redis java client. https://github.com/xetorthio/jedis From 35291bf17dff75162f609b5f674e5caba732bdec Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Mon, 3 Feb 2014 13:01:20 -0300 Subject: [PATCH 021/120] Make makefile remove temp files as it makes tests to fail sometimes --- Makefile | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index e00fb83..a5328e2 100644 --- a/Makefile +++ b/Makefile @@ -166,7 +166,8 @@ start: cleanup echo "$$REDIS_CLUSTER_NODE3_CONF" | redis-server - cleanup: - rm -vf /tmp/redis_cluster_node*.conf + - rm -vf /tmp/redis_cluster_node*.conf 2>/dev/null + - rm dump.rdb appendonly.aof - 2>/dev/null stop: kill `cat /tmp/redis1.pid` From aa63c98d8efe52d7f1ee35fec1cf34ed9f7a0414 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Mon, 3 Feb 2014 11:09:48 -0500 Subject: [PATCH 022/120] [maven-release-plugin] prepare release jedis-2.3.0 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 169987a..7df11ab 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ jar redis.clients jedis - 2.3.0-SNAPSHOT + 2.3.0 Jedis Jedis is a blazingly small and sane Redis java client. https://github.com/xetorthio/jedis @@ -41,7 +41,7 @@ scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git - jedis-2.2.0 + jedis-2.3.0 From 2d04a3845b1b5eb6a529f2443f0325b4b87fd6be Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Mon, 3 Feb 2014 11:09:50 -0500 Subject: [PATCH 023/120] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 7df11ab..25d523f 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ jar redis.clients jedis - 2.3.0 + 2.3.1-SNAPSHOT Jedis Jedis is a blazingly small and sane Redis java client. https://github.com/xetorthio/jedis @@ -41,7 +41,7 @@ scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git - jedis-2.3.0 + jedis-2.2.0 From 13f0c32f7cbccc12cd00eb42dd1551d001eebcd5 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Wed, 5 Feb 2014 00:41:34 +0900 Subject: [PATCH 024/120] Add unit test for "sentinel set quorum" introduced by Redis 2.8.5 --- .../java/redis/clients/jedis/tests/JedisSentinelTest.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java b/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java index 833151e..da0d5af 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java @@ -134,6 +134,7 @@ public class JedisSentinelTest extends JedisTestBase { Map parameterMap = new HashMap(); parameterMap.put("down-after-milliseconds", String.valueOf(1234)); parameterMap.put("parallel-syncs", String.valueOf(3)); + parameterMap.put("quorum", String.valueOf(2)); j.sentinelSet(MASTER_NAME, parameterMap); List> masters = j.sentinelMasters(); @@ -141,8 +142,12 @@ public class JedisSentinelTest extends JedisTestBase { if (master.get("name").equals(MASTER_NAME)) { assertEquals(1234, Integer.parseInt(master.get("down-after-milliseconds"))); assertEquals(3, Integer.parseInt(master.get("parallel-syncs"))); + assertEquals(2, Integer.parseInt(master.get("quorum"))); } } + + parameterMap.put("quorum", String.valueOf(1)); + j.sentinelSet(MASTER_NAME, parameterMap); } private void ensureMonitored(HostAndPort sentinel, String masterName, String ip, int port, int quorum) { From dd62e360fa714c6c93722f362772a71179a0ddda Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Wed, 5 Feb 2014 00:45:48 +0900 Subject: [PATCH 025/120] Apply "Java Convention" to met Jedis's preferred source code Convention --- .../jedis/tests/JedisSentinelTest.java | 221 +++++++++--------- 1 file changed, 117 insertions(+), 104 deletions(-) diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java b/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java index da0d5af..4445072 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java @@ -22,14 +22,16 @@ public class JedisSentinelTest extends JedisTestBase { protected static HostAndPort master = HostAndPortUtil.getRedisServers() .get(0); - protected static HostAndPort slave = HostAndPortUtil.getRedisServers().get(5); + protected static HostAndPort slave = HostAndPortUtil.getRedisServers().get( + 5); protected static HostAndPort sentinel = HostAndPortUtil .getSentinelServers().get(0); - - protected static HostAndPort sentinelForFailover = HostAndPortUtil.getSentinelServers() - .get(3); - protected static HostAndPort masterForFailover = HostAndPortUtil.getRedisServers().get(6); - + + protected static HostAndPort sentinelForFailover = HostAndPortUtil + .getSentinelServers().get(3); + protected static HostAndPort masterForFailover = HostAndPortUtil + .getRedisServers().get(6); + @Before public void setup() throws InterruptedException { } @@ -41,128 +43,139 @@ public class JedisSentinelTest extends JedisTestBase { // to restore it (demote) // so, promote(slaveof) slave to master has no effect, not same to old // Sentinel's behavior - ensureRemoved(MONITOR_MASTER_NAME); - ensureRemoved(REMOVE_MASTER_NAME); + ensureRemoved(MONITOR_MASTER_NAME); + ensureRemoved(REMOVE_MASTER_NAME); } @Test public void sentinel() { - Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); + Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); List> masters = j.sentinelMasters(); - + boolean inMasters = false; for (Map master : masters) - if (MASTER_NAME.equals(master.get("name"))) - inMasters = true; - + if (MASTER_NAME.equals(master.get("name"))) + inMasters = true; + assertTrue(inMasters); - - List masterHostAndPort = j.sentinelGetMasterAddrByName(MASTER_NAME); + + List masterHostAndPort = j + .sentinelGetMasterAddrByName(MASTER_NAME); HostAndPort masterFromSentinel = new HostAndPort( masterHostAndPort.get(0), Integer.parseInt(masterHostAndPort .get(1))); assertEquals(master, masterFromSentinel); - + List> slaves = j.sentinelSlaves(MASTER_NAME); assertTrue(slaves.size() > 0); - assertEquals(master.getPort(), Integer.parseInt(slaves.get(0).get("master-port"))); - + assertEquals(master.getPort(), + Integer.parseInt(slaves.get(0).get("master-port"))); + // DO NOT RE-RUN TEST TOO FAST, RESET TAKES SOME TIME TO... RESET assertEquals(Long.valueOf(1), j.sentinelReset(MASTER_NAME)); assertEquals(Long.valueOf(0), j.sentinelReset("woof" + MASTER_NAME)); } @Test - public void sentinelFailover() throws InterruptedException { - Jedis j = new Jedis(sentinelForFailover.getHost(), sentinelForFailover.getPort()); - - HostAndPort currentMaster = new HostAndPort(masterForFailover.getHost(), masterForFailover.getPort()); - - List masterHostAndPort = j.sentinelGetMasterAddrByName(FAILOVER_MASTER_NAME); - String result = j.sentinelFailover(FAILOVER_MASTER_NAME); - assertEquals("OK", result); - - JedisSentinelTestUtil.waitForNewPromotedMaster(sentinelForFailover, FAILOVER_MASTER_NAME, currentMaster); - - masterHostAndPort = j.sentinelGetMasterAddrByName(FAILOVER_MASTER_NAME); - HostAndPort newMaster = new HostAndPort(masterHostAndPort.get(0), - Integer.parseInt(masterHostAndPort.get(1))); - - assertNotEquals(newMaster, currentMaster); + public void sentinelFailover() throws InterruptedException { + Jedis j = new Jedis(sentinelForFailover.getHost(), + sentinelForFailover.getPort()); + + HostAndPort currentMaster = new HostAndPort( + masterForFailover.getHost(), masterForFailover.getPort()); + + List masterHostAndPort = j + .sentinelGetMasterAddrByName(FAILOVER_MASTER_NAME); + String result = j.sentinelFailover(FAILOVER_MASTER_NAME); + assertEquals("OK", result); + + JedisSentinelTestUtil.waitForNewPromotedMaster(sentinelForFailover, + FAILOVER_MASTER_NAME, currentMaster); + + masterHostAndPort = j.sentinelGetMasterAddrByName(FAILOVER_MASTER_NAME); + HostAndPort newMaster = new HostAndPort(masterHostAndPort.get(0), + Integer.parseInt(masterHostAndPort.get(1))); + + assertNotEquals(newMaster, currentMaster); } - - @Test - public void sentinelMonitor() { - Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); - - // monitor new master - String result = j.sentinelMonitor(MONITOR_MASTER_NAME, MASTER_IP, master.getPort(), 1); - assertEquals("OK", result); - - // already monitored - try { - j.sentinelMonitor(MONITOR_MASTER_NAME, MASTER_IP, master.getPort(), 1); - fail(); - } catch (JedisDataException e) { - // pass - } + + @Test + public void sentinelMonitor() { + Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); + + // monitor new master + String result = j.sentinelMonitor(MONITOR_MASTER_NAME, MASTER_IP, + master.getPort(), 1); + assertEquals("OK", result); + + // already monitored + try { + j.sentinelMonitor(MONITOR_MASTER_NAME, MASTER_IP, master.getPort(), + 1); + fail(); + } catch (JedisDataException e) { + // pass } - - @Test - public void sentinelRemove() { - Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); - - ensureMonitored(sentinel, REMOVE_MASTER_NAME, MASTER_IP, master.getPort(), 1); - - String result = j.sentinelRemove(REMOVE_MASTER_NAME); - assertEquals("OK", result); - - // not exist - try { - result = j.sentinelRemove(REMOVE_MASTER_NAME); - assertNotEquals("OK", result); - fail(); - } catch (JedisDataException e) { - // pass - } + } + + @Test + public void sentinelRemove() { + Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); + + ensureMonitored(sentinel, REMOVE_MASTER_NAME, MASTER_IP, + master.getPort(), 1); + + String result = j.sentinelRemove(REMOVE_MASTER_NAME); + assertEquals("OK", result); + + // not exist + try { + result = j.sentinelRemove(REMOVE_MASTER_NAME); + assertNotEquals("OK", result); + fail(); + } catch (JedisDataException e) { + // pass } - - @Test - public void sentinelSet() { - Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); - - Map parameterMap = new HashMap(); - parameterMap.put("down-after-milliseconds", String.valueOf(1234)); - parameterMap.put("parallel-syncs", String.valueOf(3)); - parameterMap.put("quorum", String.valueOf(2)); - j.sentinelSet(MASTER_NAME, parameterMap); - - List> masters = j.sentinelMasters(); - for (Map master : masters) { - if (master.get("name").equals(MASTER_NAME)) { - assertEquals(1234, Integer.parseInt(master.get("down-after-milliseconds"))); - assertEquals(3, Integer.parseInt(master.get("parallel-syncs"))); - assertEquals(2, Integer.parseInt(master.get("quorum"))); - } - } - - parameterMap.put("quorum", String.valueOf(1)); - j.sentinelSet(MASTER_NAME, parameterMap); + } + + @Test + public void sentinelSet() { + Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); + + Map parameterMap = new HashMap(); + parameterMap.put("down-after-milliseconds", String.valueOf(1234)); + parameterMap.put("parallel-syncs", String.valueOf(3)); + parameterMap.put("quorum", String.valueOf(2)); + j.sentinelSet(MASTER_NAME, parameterMap); + + List> masters = j.sentinelMasters(); + for (Map master : masters) { + if (master.get("name").equals(MASTER_NAME)) { + assertEquals(1234, + Integer.parseInt(master.get("down-after-milliseconds"))); + assertEquals(3, Integer.parseInt(master.get("parallel-syncs"))); + assertEquals(2, Integer.parseInt(master.get("quorum"))); + } } - - private void ensureMonitored(HostAndPort sentinel, String masterName, String ip, int port, int quorum) { - Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); - try { - j.sentinelMonitor(masterName, ip, port, quorum); - } catch (JedisDataException e) { - } + + parameterMap.put("quorum", String.valueOf(1)); + j.sentinelSet(MASTER_NAME, parameterMap); + } + + private void ensureMonitored(HostAndPort sentinel, String masterName, + String ip, int port, int quorum) { + Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); + try { + j.sentinelMonitor(masterName, ip, port, quorum); + } catch (JedisDataException e) { } - - private void ensureRemoved(String masterName) { - Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); - try { - j.sentinelRemove(masterName); - } catch (JedisDataException e) { - } + } + + private void ensureRemoved(String masterName) { + Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); + try { + j.sentinelRemove(masterName); + } catch (JedisDataException e) { } + } } From a5363582a6831cca4ec00f2428222cbeffb088d1 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Wed, 5 Feb 2014 07:52:53 +0900 Subject: [PATCH 026/120] Apply "Java Convention" to met Jedis's preferred source code Convention --- src/main/java/redis/clients/jedis/Jedis.java | 66 ++++++++++---------- 1 file changed, 34 insertions(+), 32 deletions(-) diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index ec3929a..6e06fef 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -3012,37 +3012,39 @@ public class Jedis extends BinaryJedis implements JedisCommands, return slaves; } - public String sentinelFailover(String masterName) { - client.sentinel(Protocol.SENTINEL_FAILOVER, masterName); - return client.getStatusCodeReply(); + public String sentinelFailover(String masterName) { + client.sentinel(Protocol.SENTINEL_FAILOVER, masterName); + return client.getStatusCodeReply(); + } + + public String sentinelMonitor(String masterName, String ip, int port, + int quorum) { + client.sentinel(Protocol.SENTINEL_MONITOR, masterName, ip, + String.valueOf(port), String.valueOf(quorum)); + return client.getStatusCodeReply(); + } + + public String sentinelRemove(String masterName) { + client.sentinel(Protocol.SENTINEL_REMOVE, masterName); + return client.getStatusCodeReply(); + } + + public String sentinelSet(String masterName, + Map parameterMap) { + int index = 0; + int paramsLength = parameterMap.size() * 2 + 2; + String[] params = new String[paramsLength]; + + params[index++] = Protocol.SENTINEL_SET; + params[index++] = masterName; + for (Entry entry : parameterMap.entrySet()) { + params[index++] = entry.getKey(); + params[index++] = entry.getValue(); } - public String sentinelMonitor(String masterName, String ip, int port, - int quorum) { - client.sentinel(Protocol.SENTINEL_MONITOR, masterName, ip, String.valueOf(port), String.valueOf(quorum)); - return client.getStatusCodeReply(); - } - - public String sentinelRemove(String masterName) { - client.sentinel(Protocol.SENTINEL_REMOVE, masterName); - return client.getStatusCodeReply(); - } - - public String sentinelSet(String masterName, Map parameterMap) { - int index = 0; - int paramsLength = parameterMap.size() * 2 + 2; - String[] params = new String[paramsLength]; - - params[index++] = Protocol.SENTINEL_SET; - params[index++] = masterName; - for (Entry entry : parameterMap.entrySet()) { - params[index++] = entry.getKey(); - params[index++] = entry.getValue(); - } - - client.sentinel(params); - return client.getStatusCodeReply(); - } + client.sentinel(params); + return client.getStatusCodeReply(); + } public byte[] dump(final String key) { checkIsInMulti(); @@ -3280,8 +3282,8 @@ public class Jedis extends BinaryJedis implements JedisCommands, public Map pubsubNumSub(String... channels) { checkIsInMulti(); - client.pubsubNumSub(channels); - return BuilderFactory.STRING_MAP - .build(client.getBinaryMultiBulkReply()); + client.pubsubNumSub(channels); + return BuilderFactory.STRING_MAP + .build(client.getBinaryMultiBulkReply()); } } From d846149ae16739b55cc891eba1f2455a4acc28c3 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Tue, 4 Feb 2014 22:34:48 -0300 Subject: [PATCH 027/120] Fix #526. Node parsing error uppon :0 --- .../jedis/JedisClusterConnectionHandler.java | 16 +++++++++++----- .../clients/jedis/tests/JedisClusterTest.java | 1 - 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java index 045d365..15d5d41 100644 --- a/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java +++ b/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java @@ -27,15 +27,17 @@ public abstract class JedisClusterConnectionHandler { JedisPool jp = new JedisPool(hostAndPort.getHost(), hostAndPort.getPort()); this.nodes.put(hostAndPort.getHost() + hostAndPort.getPort(), jp); - discoverClusterNodesAndSlots(jp); + Jedis jedis = jp.getResource(); + discoverClusterNodesAndSlots(jedis); + jp.returnResource(jedis); } } - private void discoverClusterNodesAndSlots(JedisPool jp) { - String localNodes = jp.getResource().clusterNodes(); + private void discoverClusterNodesAndSlots(Jedis jedis) { + String localNodes = jedis.clusterNodes(); for (String nodeInfo : localNodes.split("\n")) { - HostAndPort node = getHostAndPortFromNodeLine(nodeInfo); + HostAndPort node = getHostAndPortFromNodeLine(nodeInfo, jedis); JedisPool nodePool = new JedisPool(node.getHost(), node.getPort()); this.nodes.put(node.getHost() + node.getPort(), nodePool); populateNodeSlots(nodeInfo, nodePool); @@ -63,8 +65,12 @@ public abstract class JedisClusterConnectionHandler { } } - private HostAndPort getHostAndPortFromNodeLine(String nodeInfo) { + private HostAndPort getHostAndPortFromNodeLine(String nodeInfo, Jedis currentConnection) { String stringHostAndPort = nodeInfo.split(" ", 3)[1]; + if (":0".equals(stringHostAndPort)) { + return new HostAndPort(currentConnection.getClient().getHost(), + currentConnection.getClient().getPort()); + } String[] arrayHostAndPort = stringHostAndPort.split(":"); return new HostAndPort(arrayHostAndPort[0], Integer.valueOf(arrayHostAndPort[1])); diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java index c32a9be..356e642 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java @@ -44,7 +44,6 @@ public class JedisClusterTest extends Assert { // ---- configure cluster // add nodes to cluster - node1.clusterMeet("127.0.0.1", nodeInfo1.getPort()); node1.clusterMeet("127.0.0.1", nodeInfo2.getPort()); node1.clusterMeet("127.0.0.1", nodeInfo3.getPort()); From a69dd4e2429b86dc901dea63b84a509387d27a45 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Wed, 5 Feb 2014 00:06:29 -0300 Subject: [PATCH 028/120] Add exception handling in caso of unexecpected errors --- .../clients/jedis/JedisClusterConnectionHandler.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java index 15d5d41..d30b5f7 100644 --- a/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java +++ b/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java @@ -28,10 +28,12 @@ public abstract class JedisClusterConnectionHandler { hostAndPort.getPort()); this.nodes.put(hostAndPort.getHost() + hostAndPort.getPort(), jp); Jedis jedis = jp.getResource(); - discoverClusterNodesAndSlots(jedis); - jp.returnResource(jedis); + try { + discoverClusterNodesAndSlots(jedis); + } finally { + jp.returnResource(jedis); + } } - } private void discoverClusterNodesAndSlots(Jedis jedis) { From b35e1f94823841cc5f459ebf2c53502a02d83bd5 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Wed, 5 Feb 2014 10:34:17 -0500 Subject: [PATCH 029/120] Update README on supported redis version --- README.md | 2 +- .../clients/jedis/tests/ConnectionTest.java | 57 +++++++++++++++++++ .../redis/clients/jedis/tests/JedisTest.java | 3 + 3 files changed, 61 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 0a05970..ac3c67d 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Jedis is a blazingly small and sane [Redis](http://github.com/antirez/redis "Red Jedis was conceived to be EASY to use. -Jedis is fully compatible with redis 2.6.14. +Jedis is fully compatible with redis 2.8.5. ## Community diff --git a/src/test/java/redis/clients/jedis/tests/ConnectionTest.java b/src/test/java/redis/clients/jedis/tests/ConnectionTest.java index 9cbaa12..5790562 100644 --- a/src/test/java/redis/clients/jedis/tests/ConnectionTest.java +++ b/src/test/java/redis/clients/jedis/tests/ConnectionTest.java @@ -1,11 +1,21 @@ package redis.clients.jedis.tests; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import redis.clients.jedis.Connection; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.SortingParams; import redis.clients.jedis.exceptions.JedisConnectionException; public class ConnectionTest extends Assert { @@ -41,4 +51,51 @@ public class ConnectionTest extends Assert { client.setTimeoutInfinite(); } + @Test + public void lala() throws InterruptedException { + final JedisPool jedisPool = new JedisPool("localhost"); + ExecutorService executor = Executors.newFixedThreadPool(10); + final AtomicBoolean ended = new AtomicBoolean(false); + + for (int n = 0; n < 10; n++) { + executor.execute(new Runnable() { + @Override + public void run() { + while (!ended.get()) { + Jedis jedis = jedisPool.getResource(); + SortingParams sortingParameters = new SortingParams(); + String sortBy = "1:2:*->status";// assume key is 1:2: + String filterSetName = "1:2:jobIds"; + sortingParameters.get("a", "b", "c");// assume that + // col1, + // col2, col3 are + // defined + sortingParameters.by(sortBy); + List filteredAndsortedList = null; + try { + filteredAndsortedList = jedis.sort(filterSetName, + sortingParameters); + System.out.println("Sorted List size " + + filteredAndsortedList.size()); + for (String str : filteredAndsortedList) { + // System.out.println(str); + } + } catch (Exception e) { + System.out.println("-----Exception thrown-----"); + System.out.println(e); + System.out.println(" returned value is " + + filteredAndsortedList); + e.printStackTrace(); + } finally { + jedisPool.returnResource(jedis); + } + } + } + }); + } + Thread.sleep(10000); + ended.set(true); + executor.shutdown(); + executor.awaitTermination(10, TimeUnit.SECONDS); + } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/JedisTest.java b/src/test/java/redis/clients/jedis/tests/JedisTest.java index b123b05..8e4e524 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisTest.java @@ -4,13 +4,16 @@ import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; +import java.util.List; import java.util.Map; import org.junit.Test; import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisShardInfo; import redis.clients.jedis.Protocol; +import redis.clients.jedis.SortingParams; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.tests.commands.JedisCommandTestBase; From 28e7d2af10e8468b5e1be9fef9b7e9943f9ff193 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Wed, 5 Feb 2014 10:47:11 -0500 Subject: [PATCH 030/120] Revert "Update README on supported redis version" This reverts commit b35e1f94823841cc5f459ebf2c53502a02d83bd5. --- README.md | 2 +- .../clients/jedis/tests/ConnectionTest.java | 57 ------------------- .../redis/clients/jedis/tests/JedisTest.java | 3 - 3 files changed, 1 insertion(+), 61 deletions(-) diff --git a/README.md b/README.md index ac3c67d..0a05970 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Jedis is a blazingly small and sane [Redis](http://github.com/antirez/redis "Red Jedis was conceived to be EASY to use. -Jedis is fully compatible with redis 2.8.5. +Jedis is fully compatible with redis 2.6.14. ## Community diff --git a/src/test/java/redis/clients/jedis/tests/ConnectionTest.java b/src/test/java/redis/clients/jedis/tests/ConnectionTest.java index 5790562..9cbaa12 100644 --- a/src/test/java/redis/clients/jedis/tests/ConnectionTest.java +++ b/src/test/java/redis/clients/jedis/tests/ConnectionTest.java @@ -1,21 +1,11 @@ package redis.clients.jedis.tests; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import redis.clients.jedis.Connection; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.SortingParams; import redis.clients.jedis.exceptions.JedisConnectionException; public class ConnectionTest extends Assert { @@ -51,51 +41,4 @@ public class ConnectionTest extends Assert { client.setTimeoutInfinite(); } - @Test - public void lala() throws InterruptedException { - final JedisPool jedisPool = new JedisPool("localhost"); - ExecutorService executor = Executors.newFixedThreadPool(10); - final AtomicBoolean ended = new AtomicBoolean(false); - - for (int n = 0; n < 10; n++) { - executor.execute(new Runnable() { - @Override - public void run() { - while (!ended.get()) { - Jedis jedis = jedisPool.getResource(); - SortingParams sortingParameters = new SortingParams(); - String sortBy = "1:2:*->status";// assume key is 1:2: - String filterSetName = "1:2:jobIds"; - sortingParameters.get("a", "b", "c");// assume that - // col1, - // col2, col3 are - // defined - sortingParameters.by(sortBy); - List filteredAndsortedList = null; - try { - filteredAndsortedList = jedis.sort(filterSetName, - sortingParameters); - System.out.println("Sorted List size " - + filteredAndsortedList.size()); - for (String str : filteredAndsortedList) { - // System.out.println(str); - } - } catch (Exception e) { - System.out.println("-----Exception thrown-----"); - System.out.println(e); - System.out.println(" returned value is " - + filteredAndsortedList); - e.printStackTrace(); - } finally { - jedisPool.returnResource(jedis); - } - } - } - }); - } - Thread.sleep(10000); - ended.set(true); - executor.shutdown(); - executor.awaitTermination(10, TimeUnit.SECONDS); - } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/JedisTest.java b/src/test/java/redis/clients/jedis/tests/JedisTest.java index 8e4e524..b123b05 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisTest.java @@ -4,16 +4,13 @@ import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; -import java.util.List; import java.util.Map; import org.junit.Test; import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisShardInfo; import redis.clients.jedis.Protocol; -import redis.clients.jedis.SortingParams; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.tests.commands.JedisCommandTestBase; From 75bc7542278b2e2b8e267f47d1aad9b75c13c2a2 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Wed, 5 Feb 2014 10:48:40 -0500 Subject: [PATCH 031/120] Update README to indicate that redis 2.8.5 is supported --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0a05970..ac3c67d 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Jedis is a blazingly small and sane [Redis](http://github.com/antirez/redis "Red Jedis was conceived to be EASY to use. -Jedis is fully compatible with redis 2.6.14. +Jedis is fully compatible with redis 2.8.5. ## Community From f7f689efaf55632830f7b6136d924efe8846d584 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Wed, 5 Feb 2014 10:51:36 -0500 Subject: [PATCH 032/120] [maven-release-plugin] prepare release jedis-2.3.1 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 25d523f..d7b2fa6 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ jar redis.clients jedis - 2.3.1-SNAPSHOT + 2.3.1 Jedis Jedis is a blazingly small and sane Redis java client. https://github.com/xetorthio/jedis @@ -41,7 +41,7 @@ scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git - jedis-2.2.0 + jedis-2.3.1 From 51a4bf9a56e074a44a3e5828181de3d6b98e46a9 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Wed, 5 Feb 2014 10:51:37 -0500 Subject: [PATCH 033/120] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index d7b2fa6..c2c7766 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ jar redis.clients jedis - 2.3.1 + 2.3.2-SNAPSHOT Jedis Jedis is a blazingly small and sane Redis java client. https://github.com/xetorthio/jedis @@ -41,7 +41,7 @@ scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git - jedis-2.3.1 + jedis-2.2.0 From 7449619fcaebb9cd669e491d578fc1c1099b05fb Mon Sep 17 00:00:00 2001 From: Henning Schmiedehausen Date: Fri, 7 Feb 2014 13:39:41 -0800 Subject: [PATCH 034/120] Implement Closeable for Jedis, BinaryJedis etc. This allows a Jedis object to participate in try-with-resources when using Java 7+. This change is fully backwards compatible to Java 6 and previous releases of the Jedis client. --- src/main/java/redis/clients/jedis/BinaryClient.java | 6 ++++++ src/main/java/redis/clients/jedis/BinaryJedis.java | 8 +++++++- src/main/java/redis/clients/jedis/Connection.java | 8 +++++++- 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/main/java/redis/clients/jedis/BinaryClient.java b/src/main/java/redis/clients/jedis/BinaryClient.java index 26cd8f2..d371d28 100644 --- a/src/main/java/redis/clients/jedis/BinaryClient.java +++ b/src/main/java/redis/clients/jedis/BinaryClient.java @@ -948,6 +948,12 @@ public class BinaryClient extends Connection { super.disconnect(); } + @Override + public void close() { + db = 0; + super.close(); + } + public void resetState() { if (isInMulti()) discard(); diff --git a/src/main/java/redis/clients/jedis/BinaryJedis.java b/src/main/java/redis/clients/jedis/BinaryJedis.java index 991d046..5b4fdd7 100644 --- a/src/main/java/redis/clients/jedis/BinaryJedis.java +++ b/src/main/java/redis/clients/jedis/BinaryJedis.java @@ -2,6 +2,7 @@ package redis.clients.jedis; import static redis.clients.jedis.Protocol.toByteArray; +import java.io.Closeable; import java.net.URI; import java.util.ArrayList; import java.util.HashSet; @@ -19,7 +20,7 @@ import redis.clients.util.SafeEncoder; public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKeyBinaryCommands, AdvancedBinaryJedisCommands, - BinaryScriptingCommands { + BinaryScriptingCommands, Closeable { protected Client client = null; public BinaryJedis(final String host) { @@ -1735,6 +1736,11 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, return client.getStatusCodeReply(); } + @Override + public void close() { + client.close(); + } + /** * Sort a Set or a List. *

diff --git a/src/main/java/redis/clients/jedis/Connection.java b/src/main/java/redis/clients/jedis/Connection.java index 74bcc09..e913d68 100644 --- a/src/main/java/redis/clients/jedis/Connection.java +++ b/src/main/java/redis/clients/jedis/Connection.java @@ -1,5 +1,6 @@ package redis.clients.jedis; +import java.io.Closeable; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; @@ -15,7 +16,7 @@ import redis.clients.util.RedisInputStream; import redis.clients.util.RedisOutputStream; import redis.clients.util.SafeEncoder; -public class Connection { +public class Connection implements Closeable { private String host; private int port = Protocol.DEFAULT_PORT; private Socket socket; @@ -143,6 +144,11 @@ public class Connection { } } + @Override + public void close() { + disconnect(); + } + public void disconnect() { if (isConnected()) { try { From f81f75177c4387eb9d2265f84bce91ad156e1550 Mon Sep 17 00:00:00 2001 From: Daniel Josefsson Date: Sat, 8 Feb 2014 10:10:45 +0000 Subject: [PATCH 035/120] Simplified unit test for compatibility with JDK6. --- .../jedis/tests/commands/ScriptingCommandsTest.java | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java index 8752311..f40c8d3 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java @@ -1,9 +1,8 @@ package redis.clients.jedis.tests.commands; import org.hamcrest.CoreMatchers; -import org.hamcrest.core.CombinableMatcher; +import org.hamcrest.Matcher; import org.junit.Test; - import redis.clients.jedis.BinaryJedis; import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.util.SafeEncoder; @@ -11,9 +10,7 @@ import redis.clients.util.SafeEncoder; import java.util.ArrayList; import java.util.List; -import static org.hamcrest.CoreMatchers.both; import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.hasItem; public class ScriptingCommandsTest extends JedisCommandTestBase { @@ -204,7 +201,7 @@ public class ScriptingCommandsTest extends JedisCommandTestBase { assertEquals("2", results.get(3)); } - private CombinableMatcher> listWithItem(T expected) { - return both(CoreMatchers.>instanceOf(List.class)).and(hasItem(equalTo(expected))); + private Matcher> listWithItem(T expected) { + return CoreMatchers.hasItem(equalTo(expected)); } } From ed81f37d1b2684ec50e80ad1d73bc5fb0d5109b0 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Mon, 10 Feb 2014 07:08:39 +0900 Subject: [PATCH 036/120] Introduce *scan with "string" cursor parameter to support unsigned long cursor * overload all *scan method to change "int" cursor to "string" cursor * set @Deprecated and leave reason to deprecate and when to remove to current *scan method * modify unit tests to make it work with new *scan method --- .../redis/clients/jedis/BinaryClient.java | 59 ++++++++- src/main/java/redis/clients/jedis/Client.java | 34 +++++ .../java/redis/clients/jedis/Commands.java | 32 +++++ src/main/java/redis/clients/jedis/Jedis.java | 125 ++++++++++++++++++ .../redis/clients/jedis/JedisCluster.java | 52 ++++++++ .../redis/clients/jedis/JedisCommands.java | 24 ++++ .../redis/clients/jedis/MultiKeyCommands.java | 8 ++ .../java/redis/clients/jedis/ScanParams.java | 1 + .../java/redis/clients/jedis/ScanResult.java | 29 +++- .../redis/clients/jedis/ShardedJedis.java | 33 +++++ .../commands/AllKindOfValuesCommandsTest.java | 11 +- .../tests/commands/HashesCommandsTest.java | 15 ++- .../jedis/tests/commands/SetCommandsTest.java | 11 +- .../tests/commands/SortedSetCommandsTest.java | 11 +- 14 files changed, 419 insertions(+), 26 deletions(-) diff --git a/src/main/java/redis/clients/jedis/BinaryClient.java b/src/main/java/redis/clients/jedis/BinaryClient.java index 26cd8f2..a8c12d8 100644 --- a/src/main/java/redis/clients/jedis/BinaryClient.java +++ b/src/main/java/redis/clients/jedis/BinaryClient.java @@ -1150,6 +1150,12 @@ public class BinaryClient extends Connection { sendCommand(HINCRBYFLOAT, key, field, toByteArray(increment)); } + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ public void scan(int cursor, final ScanParams params) { final List args = new ArrayList(); args.add(toByteArray(cursor)); @@ -1157,6 +1163,12 @@ public class BinaryClient extends Connection { sendCommand(SCAN, args.toArray(new byte[args.size()][])); } + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ public void hscan(final byte[] key, int cursor, final ScanParams params) { final List args = new ArrayList(); args.add(key); @@ -1164,7 +1176,13 @@ public class BinaryClient extends Connection { args.addAll(params.getParams()); sendCommand(HSCAN, args.toArray(new byte[args.size()][])); } - + + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ public void sscan(final byte[] key, int cursor, final ScanParams params) { final List args = new ArrayList(); args.add(key); @@ -1172,7 +1190,13 @@ public class BinaryClient extends Connection { args.addAll(params.getParams()); sendCommand(SSCAN, args.toArray(new byte[args.size()][])); } - + + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ public void zscan(final byte[] key, int cursor, final ScanParams params) { final List args = new ArrayList(); args.add(key); @@ -1180,6 +1204,37 @@ public class BinaryClient extends Connection { args.addAll(params.getParams()); sendCommand(ZSCAN, args.toArray(new byte[args.size()][])); } + + public void scan(final byte[] cursor, final ScanParams params) { + final List args = new ArrayList(); + args.add(cursor); + args.addAll(params.getParams()); + sendCommand(SCAN, args.toArray(new byte[args.size()][])); + } + + public void hscan(final byte[] key, final byte[] cursor, final ScanParams params) { + final List args = new ArrayList(); + args.add(key); + args.add(cursor); + args.addAll(params.getParams()); + sendCommand(HSCAN, args.toArray(new byte[args.size()][])); + } + + public void sscan(final byte[] key, final byte[] cursor, final ScanParams params) { + final List args = new ArrayList(); + args.add(key); + args.add(cursor); + args.addAll(params.getParams()); + sendCommand(SSCAN, args.toArray(new byte[args.size()][])); + } + + public void zscan(final byte[] key, final byte[] cursor, final ScanParams params) { + final List args = new ArrayList(); + args.add(key); + args.add(cursor); + args.addAll(params.getParams()); + sendCommand(ZSCAN, args.toArray(new byte[args.size()][])); + } public void waitReplicas(int replicas, long timeout) { sendCommand(WAIT, toByteArray(replicas), toByteArray(timeout)); diff --git a/src/main/java/redis/clients/jedis/Client.java b/src/main/java/redis/clients/jedis/Client.java index 96d0560..64f6f5c 100644 --- a/src/main/java/redis/clients/jedis/Client.java +++ b/src/main/java/redis/clients/jedis/Client.java @@ -833,17 +833,51 @@ public class Client extends BinaryClient implements Commands { increment); } + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ public void hscan(final String key, int cursor, final ScanParams params) { hscan(SafeEncoder.encode(key), cursor, params); } + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ public void sscan(final String key, int cursor, final ScanParams params) { sscan(SafeEncoder.encode(key), cursor, params); } + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ public void zscan(final String key, int cursor, final ScanParams params) { zscan(SafeEncoder.encode(key), cursor, params); } + + public void scan(final String cursor, final ScanParams params) { + scan(SafeEncoder.encode(cursor), params); + } + + public void hscan(final String key, final String cursor, final ScanParams params) { + hscan(SafeEncoder.encode(key), SafeEncoder.encode(cursor), params); + } + + public void sscan(final String key, final String cursor, final ScanParams params) { + sscan(SafeEncoder.encode(key), SafeEncoder.encode(cursor), params); + } + + public void zscan(final String key, final String cursor, final ScanParams params) { + zscan(SafeEncoder.encode(key), SafeEncoder.encode(cursor), params); + } public void cluster(final String subcommand, final int... args) { final byte[][] arg = new byte[args.length + 1][]; diff --git a/src/main/java/redis/clients/jedis/Commands.java b/src/main/java/redis/clients/jedis/Commands.java index 2d7ea92..a104ca9 100644 --- a/src/main/java/redis/clients/jedis/Commands.java +++ b/src/main/java/redis/clients/jedis/Commands.java @@ -297,13 +297,45 @@ public interface Commands { public void bitop(BitOP op, final String destKey, String... srcKeys); + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ public void scan(int cursor, final ScanParams params); + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ public void hscan(final String key, int cursor, final ScanParams params); + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ public void sscan(final String key, int cursor, final ScanParams params); + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ public void zscan(final String key, int 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 sscan(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); } diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index d5f7283..545fece 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -3096,10 +3096,22 @@ public class Jedis extends BinaryJedis implements JedisCommands, return (relpy != null ? new Double(relpy) : null); } + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ public ScanResult scan(int cursor) { return scan(cursor, new ScanParams()); } + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ public ScanResult scan(int cursor, final ScanParams params) { checkIsInMulti(); client.scan(cursor, params); @@ -3113,11 +3125,23 @@ public class Jedis extends BinaryJedis implements JedisCommands, return new ScanResult(newcursor, results); } + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ public ScanResult> hscan(final String key, int cursor) { return hscan(key, cursor, new ScanParams()); } + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ public ScanResult> hscan(final String key, int cursor, final ScanParams params) { checkIsInMulti(); @@ -3135,10 +3159,22 @@ public class Jedis extends BinaryJedis implements JedisCommands, return new ScanResult>(newcursor, results); } + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ public ScanResult sscan(final String key, int cursor) { return sscan(key, cursor, new ScanParams()); } + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ public ScanResult sscan(final String key, int cursor, final ScanParams params) { checkIsInMulti(); @@ -3153,10 +3189,22 @@ public class Jedis extends BinaryJedis implements JedisCommands, return new ScanResult(newcursor, results); } + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ public ScanResult zscan(final String key, int cursor) { return zscan(key, cursor, new ScanParams()); } + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ public ScanResult zscan(final String key, int cursor, final ScanParams params) { checkIsInMulti(); @@ -3172,6 +3220,83 @@ public class Jedis extends BinaryJedis implements JedisCommands, } return new ScanResult(newcursor, results); } + + public ScanResult scan(final String cursor) { + return scan(cursor, new ScanParams()); + } + + public ScanResult scan(final String cursor, final ScanParams params) { + checkIsInMulti(); + client.scan(cursor, params); + List result = client.getObjectMultiBulkReply(); + String newcursor = new String((byte[]) result.get(0)); + List results = new ArrayList(); + List rawResults = (List) result.get(1); + for (byte[] bs : rawResults) { + results.add(SafeEncoder.encode(bs)); + } + return new ScanResult(newcursor, results); + } + + public ScanResult> hscan(final String key, + final String cursor) { + return hscan(key, cursor, new ScanParams()); + } + + public ScanResult> hscan(final String key, + final String cursor, final ScanParams params) { + checkIsInMulti(); + client.hscan(key, cursor, params); + List result = client.getObjectMultiBulkReply(); + String newcursor = new String((byte[]) result.get(0)); + List> results = new ArrayList>(); + List rawResults = (List) result.get(1); + Iterator iterator = rawResults.iterator(); + while (iterator.hasNext()) { + results.add(new AbstractMap.SimpleEntry(SafeEncoder + .encode(iterator.next()), SafeEncoder.encode(iterator + .next()))); + } + return new ScanResult>(newcursor, results); + } + + public ScanResult sscan(final String key, final String cursor) { + return sscan(key, cursor, new ScanParams()); + } + + public ScanResult sscan(final String key, final String cursor, + final ScanParams params) { + checkIsInMulti(); + client.sscan(key, cursor, params); + List result = client.getObjectMultiBulkReply(); + String newcursor = new String((byte[]) result.get(0)); + List results = new ArrayList(); + List rawResults = (List) result.get(1); + for (byte[] bs : rawResults) { + results.add(SafeEncoder.encode(bs)); + } + return new ScanResult(newcursor, results); + } + + public ScanResult zscan(final String key, final String cursor) { + return zscan(key, cursor, new ScanParams()); + } + + public ScanResult zscan(final String key, final String cursor, + final ScanParams params) { + checkIsInMulti(); + client.zscan(key, cursor, params); + List result = client.getObjectMultiBulkReply(); + String newcursor = new String((byte[]) result.get(0)); + List results = new ArrayList(); + List rawResults = (List) result.get(1); + Iterator iterator = rawResults.iterator(); + while (iterator.hasNext()) { + results.add(new Tuple(SafeEncoder.encode(iterator.next()), Double + .valueOf(SafeEncoder.encode(iterator.next())))); + } + return new ScanResult(newcursor, results); + } public String clusterNodes() { checkIsInMulti(); diff --git a/src/main/java/redis/clients/jedis/JedisCluster.java b/src/main/java/redis/clients/jedis/JedisCluster.java index ffa1115..bec2574 100644 --- a/src/main/java/redis/clients/jedis/JedisCluster.java +++ b/src/main/java/redis/clients/jedis/JedisCluster.java @@ -1396,6 +1396,12 @@ public class JedisCluster implements JedisCommands, BasicCommands { return null; } + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ @Override public ScanResult> hscan(final String key, final int cursor) { @@ -1408,6 +1414,12 @@ public class JedisCluster implements JedisCommands, BasicCommands { }.run(null); } + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ @Override public ScanResult sscan(final String key, final int cursor) { return new JedisClusterCommand>(connectionHandler, @@ -1419,6 +1431,12 @@ public class JedisCluster implements JedisCommands, BasicCommands { }.run(null); } + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ @Override public ScanResult zscan(final String key, final int cursor) { return new JedisClusterCommand>(connectionHandler, @@ -1429,4 +1447,38 @@ public class JedisCluster implements JedisCommands, BasicCommands { } }.run(null); } + + @Override + public ScanResult> hscan(final String key, + final String cursor) { + return new JedisClusterCommand>>( + connectionHandler, timeout, maxRedirections) { + @Override + public ScanResult> execute() { + return connectionHandler.getConnection().hscan(key, cursor); + } + }.run(null); + } + + @Override + public ScanResult sscan(final String key, final String cursor) { + return new JedisClusterCommand>(connectionHandler, + timeout, maxRedirections) { + @Override + public ScanResult execute() { + return connectionHandler.getConnection().sscan(key, cursor); + } + }.run(null); + } + + @Override + public ScanResult zscan(final String key, final String cursor) { + return new JedisClusterCommand>(connectionHandler, + timeout, maxRedirections) { + @Override + public ScanResult execute() { + return connectionHandler.getConnection().zscan(key, cursor); + } + }.run(null); + } } diff --git a/src/main/java/redis/clients/jedis/JedisCommands.java b/src/main/java/redis/clients/jedis/JedisCommands.java index 3077e68..5952bdb 100644 --- a/src/main/java/redis/clients/jedis/JedisCommands.java +++ b/src/main/java/redis/clients/jedis/JedisCommands.java @@ -211,9 +211,33 @@ public interface JedisCommands { Long bitcount(final String key, long start, long end); + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ ScanResult> hscan(final String key, int cursor); + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ ScanResult sscan(final String key, int cursor); + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ ScanResult zscan(final String key, int cursor); + + ScanResult> hscan(final String key, final String cursor); + + ScanResult sscan(final String key, final String cursor); + + ScanResult zscan(final String key, final String cursor); } diff --git a/src/main/java/redis/clients/jedis/MultiKeyCommands.java b/src/main/java/redis/clients/jedis/MultiKeyCommands.java index 3565c6d..f03f82c 100644 --- a/src/main/java/redis/clients/jedis/MultiKeyCommands.java +++ b/src/main/java/redis/clients/jedis/MultiKeyCommands.java @@ -70,5 +70,13 @@ public interface MultiKeyCommands { Long bitop(BitOP op, final String destKey, String... srcKeys); + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ ScanResult scan(int cursor); + + ScanResult scan(final String cursor); } diff --git a/src/main/java/redis/clients/jedis/ScanParams.java b/src/main/java/redis/clients/jedis/ScanParams.java index 874d636..980bb13 100644 --- a/src/main/java/redis/clients/jedis/ScanParams.java +++ b/src/main/java/redis/clients/jedis/ScanParams.java @@ -12,6 +12,7 @@ import redis.clients.util.SafeEncoder; public class ScanParams { private List params = new ArrayList(); + public final static String SCAN_POINTER_START = String.valueOf(0); public void match(final String pattern) { params.add(MATCH.raw); diff --git a/src/main/java/redis/clients/jedis/ScanResult.java b/src/main/java/redis/clients/jedis/ScanResult.java index d8ba7c6..9afe27d 100644 --- a/src/main/java/redis/clients/jedis/ScanResult.java +++ b/src/main/java/redis/clients/jedis/ScanResult.java @@ -3,18 +3,43 @@ package redis.clients.jedis; import java.util.List; public class ScanResult { - private int cursor; + private String cursor; private List results; + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ public ScanResult(int cursor, List results) { + this.cursor = String.valueOf(cursor); + this.results = results; + } + + public ScanResult(String cursor, List results) { this.cursor = cursor; this.results = results; } + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + * @return int(currently), but will be changed to String, so be careful to prepare! + */ public int getCursor() { - return cursor; + return Integer.parseInt(cursor); } + /** + * FIXME: This method should be changed to getCursor() on next major release + */ + public String getStringCursor() { + return cursor; + } + public List getResult() { return results; } diff --git a/src/main/java/redis/clients/jedis/ShardedJedis.java b/src/main/java/redis/clients/jedis/ShardedJedis.java index 02c0e4c..7235cfe 100644 --- a/src/main/java/redis/clients/jedis/ShardedJedis.java +++ b/src/main/java/redis/clients/jedis/ShardedJedis.java @@ -523,18 +523,51 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands { return j.bitcount(key, start, end); } + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ public ScanResult> hscan(String key, int cursor) { Jedis j = getShard(key); return j.hscan(key, cursor); } + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ public ScanResult sscan(String key, int cursor) { Jedis j = getShard(key); return j.sscan(key, cursor); } + @Deprecated + /** + * This method is deprecated due to bug (scan cursor should be unsigned long) + * And will be removed on next major release + * @see https://github.com/xetorthio/jedis/issues/531 + */ public ScanResult zscan(String key, int cursor) { Jedis j = getShard(key); return j.zscan(key, cursor); } + + public ScanResult> hscan(String key, final String cursor) { + Jedis j = getShard(key); + return j.hscan(key, cursor); + } + + public ScanResult sscan(String key, final String cursor) { + Jedis j = getShard(key); + return j.sscan(key, cursor); + } + + public ScanResult zscan(String key, final String cursor) { + Jedis j = getShard(key); + return j.zscan(key, cursor); + } } diff --git a/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java index 8fe2675..057537c 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java @@ -10,6 +10,7 @@ import redis.clients.jedis.ScanParams; import redis.clients.jedis.ScanResult; import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.util.SafeEncoder; +import static redis.clients.jedis.ScanParams.SCAN_POINTER_START; public class AllKindOfValuesCommandsTest extends JedisCommandTestBase { final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; @@ -510,9 +511,9 @@ public class AllKindOfValuesCommandsTest extends JedisCommandTestBase { jedis.set("b", "b"); jedis.set("a", "a"); - ScanResult result = jedis.scan(0); + ScanResult result = jedis.scan(SCAN_POINTER_START); - assertEquals(0, result.getCursor()); + assertEquals(SCAN_POINTER_START, result.getStringCursor()); assertFalse(result.getResult().isEmpty()); } @@ -524,9 +525,9 @@ public class AllKindOfValuesCommandsTest extends JedisCommandTestBase { jedis.set("b", "b"); jedis.set("a", "a"); jedis.set("aa", "aa"); - ScanResult result = jedis.scan(0, params); + ScanResult result = jedis.scan(SCAN_POINTER_START, params); - assertEquals(0, result.getCursor()); + assertEquals(SCAN_POINTER_START, result.getStringCursor()); assertFalse(result.getResult().isEmpty()); } @@ -539,7 +540,7 @@ public class AllKindOfValuesCommandsTest extends JedisCommandTestBase { jedis.set("a" + i, "a" + i); } - ScanResult result = jedis.scan(0, params); + ScanResult result = jedis.scan(SCAN_POINTER_START, params); assertFalse(result.getResult().isEmpty()); } diff --git a/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java index 1210259..5f9ac4e 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java @@ -12,6 +12,7 @@ import org.junit.Test; import redis.clients.jedis.ScanParams; import redis.clients.jedis.ScanResult; +import static redis.clients.jedis.ScanParams.SCAN_POINTER_START; public class HashesCommandsTest extends JedisCommandTestBase { final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; @@ -295,9 +296,9 @@ public class HashesCommandsTest extends JedisCommandTestBase { jedis.hset("foo", "b", "b"); jedis.hset("foo", "a", "a"); - ScanResult> result = jedis.hscan("foo", 0); + ScanResult> result = jedis.hscan("foo", SCAN_POINTER_START); - assertEquals(0, result.getCursor()); + assertEquals(SCAN_POINTER_START, result.getStringCursor()); assertFalse(result.getResult().isEmpty()); } @@ -309,10 +310,10 @@ public class HashesCommandsTest extends JedisCommandTestBase { jedis.hset("foo", "b", "b"); jedis.hset("foo", "a", "a"); jedis.hset("foo", "aa", "aa"); - ScanResult> result = jedis.hscan("foo", 0, - params); + ScanResult> result = jedis.hscan("foo", + SCAN_POINTER_START, params); - assertEquals(0, result.getCursor()); + assertEquals(SCAN_POINTER_START, result.getStringCursor()); assertFalse(result.getResult().isEmpty()); } @@ -325,8 +326,8 @@ public class HashesCommandsTest extends JedisCommandTestBase { jedis.hset("foo", "a" + i, "a" + i); } - ScanResult> result = jedis.hscan("foo", 0, - params); + ScanResult> result = jedis.hscan("foo", + SCAN_POINTER_START, params); assertFalse(result.getResult().isEmpty()); } diff --git a/src/test/java/redis/clients/jedis/tests/commands/SetCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/SetCommandsTest.java index 80e59ad..2149feb 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/SetCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/SetCommandsTest.java @@ -8,6 +8,7 @@ import org.junit.Test; import redis.clients.jedis.ScanParams; import redis.clients.jedis.ScanResult; +import static redis.clients.jedis.ScanParams.SCAN_POINTER_START; public class SetCommandsTest extends JedisCommandTestBase { final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; @@ -457,9 +458,9 @@ public class SetCommandsTest extends JedisCommandTestBase { public void sscan() { jedis.sadd("foo", "a", "b"); - ScanResult result = jedis.sscan("foo", 0); + ScanResult result = jedis.sscan("foo", SCAN_POINTER_START); - assertEquals(0, result.getCursor()); + assertEquals(SCAN_POINTER_START, result.getStringCursor()); assertFalse(result.getResult().isEmpty()); } @@ -469,9 +470,9 @@ public class SetCommandsTest extends JedisCommandTestBase { params.match("a*"); jedis.sadd("foo", "b", "a", "aa"); - ScanResult result = jedis.sscan("foo", 0, params); + ScanResult result = jedis.sscan("foo", SCAN_POINTER_START, params); - assertEquals(0, result.getCursor()); + assertEquals(SCAN_POINTER_START, result.getStringCursor()); assertFalse(result.getResult().isEmpty()); } @@ -482,7 +483,7 @@ public class SetCommandsTest extends JedisCommandTestBase { jedis.sadd("foo", "a1", "a2", "a3", "a4", "a5"); - ScanResult result = jedis.sscan("foo", 0, params); + ScanResult result = jedis.sscan("foo", SCAN_POINTER_START, params); assertFalse(result.getResult().isEmpty()); } diff --git a/src/test/java/redis/clients/jedis/tests/commands/SortedSetCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/SortedSetCommandsTest.java index b4fd3b6..90b4c20 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/SortedSetCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/SortedSetCommandsTest.java @@ -10,6 +10,7 @@ import redis.clients.jedis.ScanResult; import redis.clients.jedis.Tuple; import redis.clients.jedis.ZParams; import redis.clients.util.SafeEncoder; +import static redis.clients.jedis.ScanParams.SCAN_POINTER_START; public class SortedSetCommandsTest extends JedisCommandTestBase { final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; @@ -894,9 +895,9 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { jedis.zadd("foo", 1, "a"); jedis.zadd("foo", 2, "b"); - ScanResult result = jedis.zscan("foo", 0); + ScanResult result = jedis.zscan("foo", SCAN_POINTER_START); - assertEquals(0, result.getCursor()); + assertEquals(SCAN_POINTER_START, result.getStringCursor()); assertFalse(result.getResult().isEmpty()); } @@ -908,9 +909,9 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { jedis.zadd("foo", 2, "b"); jedis.zadd("foo", 1, "a"); jedis.zadd("foo", 11, "aa"); - ScanResult result = jedis.zscan("foo", 0, params); + ScanResult result = jedis.zscan("foo", SCAN_POINTER_START, params); - assertEquals(0, result.getCursor()); + assertEquals(SCAN_POINTER_START, result.getStringCursor()); assertFalse(result.getResult().isEmpty()); } @@ -925,7 +926,7 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { jedis.zadd("foo", 4, "a4"); jedis.zadd("foo", 5, "a5"); - ScanResult result = jedis.zscan("foo", 0, params); + ScanResult result = jedis.zscan("foo", SCAN_POINTER_START, params); assertFalse(result.getResult().isEmpty()); } From 1ed231cf159d375cb60bea21420f359e3ff41f5e Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Mon, 10 Feb 2014 07:55:27 +0900 Subject: [PATCH 037/120] Mark @Duplicated to TransactionBlock and PipelineBlock related classes / methods --- .../java/redis/clients/jedis/BinaryJedis.java | 19 +++-- .../clients/jedis/BinaryShardedJedis.java | 6 ++ .../redis/clients/jedis/PipelineBlock.java | 6 ++ .../redis/clients/jedis/TransactionBlock.java | 6 ++ .../clients/jedis/tests/PipeliningTest.java | 14 +--- .../commands/TransactionCommandsTest.java | 83 ------------------- 6 files changed, 31 insertions(+), 103 deletions(-) diff --git a/src/main/java/redis/clients/jedis/BinaryJedis.java b/src/main/java/redis/clients/jedis/BinaryJedis.java index 991d046..173efbe 100644 --- a/src/main/java/redis/clients/jedis/BinaryJedis.java +++ b/src/main/java/redis/clients/jedis/BinaryJedis.java @@ -1696,6 +1696,13 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, return new Transaction(client); } + @Deprecated + /** + * This method is deprecated due to its error prone + * and will be removed on next major release + * You can use multi() instead + * @see https://github.com/xetorthio/jedis/pull/498 + */ public List multi(final TransactionBlock jedisTransaction) { List results = null; jedisTransaction.setClient(client); @@ -2119,14 +2126,12 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, return client.getStatusCodeReply(); } + @Deprecated /** - * Starts a pipeline, which is a very efficient way to send lots of command - * and read all the responses when you finish sending them. Try to avoid - * this version and use pipelined() when possible as it will give better - * performance. - * - * @param jedisPipeline - * @return The results of the command in the same order you've run them. + * This method is deprecated due to its error prone with multi + * and will be removed on next major release + * You can use pipelined() instead + * @see https://github.com/xetorthio/jedis/pull/498 */ public List pipelined(final PipelineBlock jedisPipeline) { jedisPipeline.setClient(client); diff --git a/src/main/java/redis/clients/jedis/BinaryShardedJedis.java b/src/main/java/redis/clients/jedis/BinaryShardedJedis.java index 382d48b..5895f20 100644 --- a/src/main/java/redis/clients/jedis/BinaryShardedJedis.java +++ b/src/main/java/redis/clients/jedis/BinaryShardedJedis.java @@ -482,6 +482,12 @@ public class BinaryShardedJedis extends Sharded } @Deprecated + /** + * This method is deprecated due to its error prone with multi + * and will be removed on next major release + * You can use pipelined() instead + * @see https://github.com/xetorthio/jedis/pull/498 + */ public List pipelined(ShardedJedisPipeline shardedJedisPipeline) { shardedJedisPipeline.setShardedJedis(this); shardedJedisPipeline.execute(); diff --git a/src/main/java/redis/clients/jedis/PipelineBlock.java b/src/main/java/redis/clients/jedis/PipelineBlock.java index 9cf2f7e..50181ba 100644 --- a/src/main/java/redis/clients/jedis/PipelineBlock.java +++ b/src/main/java/redis/clients/jedis/PipelineBlock.java @@ -1,5 +1,11 @@ package redis.clients.jedis; +@Deprecated +/** + * This method is deprecated due to its error prone with multi + * and will be removed on next major release + * @see https://github.com/xetorthio/jedis/pull/498 + */ public abstract class PipelineBlock extends Pipeline { public abstract void execute(); } diff --git a/src/main/java/redis/clients/jedis/TransactionBlock.java b/src/main/java/redis/clients/jedis/TransactionBlock.java index 87df232..86f7c44 100644 --- a/src/main/java/redis/clients/jedis/TransactionBlock.java +++ b/src/main/java/redis/clients/jedis/TransactionBlock.java @@ -2,6 +2,12 @@ package redis.clients.jedis; import redis.clients.jedis.exceptions.JedisException; +@Deprecated +/** + * This class is deprecated due to its error prone + * and will be removed on next major release + * @see https://github.com/xetorthio/jedis/pull/498 + */ public abstract class TransactionBlock extends Transaction { public TransactionBlock(Client client) { super(client); diff --git a/src/test/java/redis/clients/jedis/tests/PipeliningTest.java b/src/test/java/redis/clients/jedis/tests/PipeliningTest.java index 2b3eabe..aed67dc 100755 --- a/src/test/java/redis/clients/jedis/tests/PipeliningTest.java +++ b/src/test/java/redis/clients/jedis/tests/PipeliningTest.java @@ -15,7 +15,6 @@ import org.junit.Test; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; import redis.clients.jedis.Pipeline; -import redis.clients.jedis.PipelineBlock; import redis.clients.jedis.Response; import redis.clients.jedis.Tuple; import redis.clients.jedis.exceptions.JedisDataException; @@ -35,21 +34,10 @@ public class PipeliningTest extends Assert { @Test public void pipeline() throws UnsupportedEncodingException { - List results = jedis.pipelined(new PipelineBlock() { - public void execute() { - set("foo", "bar"); - get("foo"); - } - }); - - assertEquals(2, results.size()); - assertEquals("OK", results.get(0)); - assertEquals("bar", results.get(1)); - Pipeline p = jedis.pipelined(); p.set("foo", "bar"); p.get("foo"); - results = p.syncAndReturnAll(); + List results = p.syncAndReturnAll(); assertEquals(2, results.size()); assertEquals("OK", results.get(0)); diff --git a/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java index cc36a7f..ae98a8a 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java @@ -16,9 +16,7 @@ import redis.clients.jedis.Pipeline; import redis.clients.jedis.Protocol.Keyword; import redis.clients.jedis.Response; import redis.clients.jedis.Transaction; -import redis.clients.jedis.TransactionBlock; import redis.clients.jedis.exceptions.JedisDataException; -import redis.clients.jedis.exceptions.JedisException; public class TransactionCommandsTest extends JedisCommandTestBase { final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; @@ -73,87 +71,6 @@ public class TransactionCommandsTest extends JedisCommandTestBase { } - @Test - public void multiBlock() { - List response = jedis.multi(new TransactionBlock() { - @Override - public void execute() { - sadd("foo", "a"); - sadd("foo", "b"); - scard("foo"); - } - }); - - List expected = new ArrayList(); - expected.add(1L); - expected.add(1L); - expected.add(2L); - assertEquals(expected, response); - - // Binary - response = jedis.multi(new TransactionBlock() { - @Override - public void execute() { - sadd(bfoo, ba); - sadd(bfoo, bb); - scard(bfoo); - } - }); - - expected = new ArrayList(); - expected.add(1L); - expected.add(1L); - expected.add(2L); - assertEquals(expected, response); - - } - - @Test - public void multiBlockWithErrorRedisDiscardsTransaction() throws Exception { - // Transaction with error - Redis discards transaction automatically - // (Syntax Error, etc.) - TransactionBlock tb = new TransactionBlock() { - - @Override - public void execute() throws JedisException { - del("hello"); - hmset("hello", new HashMap()); - } - }; - - try { - jedis.multi(tb); - } catch (JedisDataException e) { - assertTrue(e.getMessage().contains("EXECABORT")); - } catch (Exception e) { - throw e; - } - } - - @Test - public void multiBlockWithErrorRedisForceToExecuteAllCommands() - throws Exception { - // Transaction with error - Redis doesn't roll back (Type Error, - // Deletion of non-exist key, etc.) - jedis.del("hello2"); - TransactionBlock tb2 = new TransactionBlock() { - - @Override - public void execute() throws JedisException { - del("hello2"); - set("hello2", "hello"); - sadd("hello2", "hello2"); - } - }; - - List responses = jedis.multi(tb2); - assertEquals("OK", responses.get(1)); - assertEquals(JedisDataException.class, responses.get(2).getClass()); - - Exception exc = (JedisDataException) responses.get(2); - assertTrue(exc.getMessage().contains("WRONGTYPE")); - } - @Test public void watch() throws UnknownHostException, IOException { jedis.watch("mykey", "somekey"); From e59e4a0d2a9758e34589babf3533c890dac3f6cb Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Tue, 11 Feb 2014 02:51:58 -0300 Subject: [PATCH 038/120] Fix test to make jedis work with latest git master version of redis --- Makefile | 6 ++--- .../tests/commands/ClusterCommandsTest.java | 26 ++++++++----------- 2 files changed, 14 insertions(+), 18 deletions(-) diff --git a/Makefile b/Makefile index a5328e2..ddc298a 100644 --- a/Makefile +++ b/Makefile @@ -180,9 +180,9 @@ stop: kill `cat /tmp/sentinel1.pid` kill `cat /tmp/sentinel2.pid` kill `cat /tmp/sentinel3.pid` - kill `cat /tmp/redis_cluster_node1.pid` || true - kill `cat /tmp/redis_cluster_node2.pid` || true - kill `cat /tmp/redis_cluster_node3.pid` || true + #kill `cat /tmp/redis_cluster_node1.pid` || true + #kill `cat /tmp/redis_cluster_node2.pid` || true + #kill `cat /tmp/redis_cluster_node3.pid` || true rm -f /tmp/redis_cluster_node1.conf rm -f /tmp/redis_cluster_node2.conf rm -f /tmp/redis_cluster_node3.conf diff --git a/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java index d2bc584..59b288d 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java @@ -9,7 +9,6 @@ import org.junit.Test; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; -import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.tests.HostAndPortUtil; import redis.clients.jedis.tests.JedisTestBase; @@ -47,13 +46,9 @@ public class ClusterCommandsTest extends JedisTestBase { node1.clusterDelSlots(1, 2, 3, 4, 5, 500); node1.clusterSetSlotNode(5000, node1Id); node1.clusterDelSlots(5000, 10000); - node1.clusterDelSlots(6000); node2.clusterDelSlots(6000, 1, 2, 3, 4, 5, 500, 5000); - try { - node2.clusterDelSlots(10000); - } catch (JedisDataException jde) { - // Do nothing, slot may or may not be assigned depending on gossip - } + node1.clusterAddSlots(6000); + node1.clusterDelSlots(6000); } private static void waitForEqualClusterSize() throws InterruptedException { @@ -74,6 +69,15 @@ public class ClusterCommandsTest extends JedisTestBase { } return 0; } + + @Test + public void clusterSetSlotImporting() { + node2.clusterAddSlots(6000); + String[] nodes = node1.clusterNodes().split("\n"); + String nodeId = nodes[0].split(" ")[0]; + String status = node1.clusterSetSlotImporting(6000, nodeId); + assertEquals("OK", status); + } @Test public void clusterNodes() { @@ -130,12 +134,4 @@ public class ClusterCommandsTest extends JedisTestBase { assertEquals("OK", status); } - @Test - public void clusterSetSlotImporting() { - node2.clusterAddSlots(6000); - String[] nodes = node1.clusterNodes().split("\n"); - String nodeId = nodes[0].split(" ")[0]; - String status = node1.clusterSetSlotImporting(6000, nodeId); - assertEquals("OK", status); - } } \ No newline at end of file From d8ec0f8a5c50eb21e93211dd7616bfc6ec87636d Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Tue, 11 Feb 2014 11:21:18 -0500 Subject: [PATCH 039/120] version bump --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index c2c7766..1e5cd73 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ jar redis.clients jedis - 2.3.2-SNAPSHOT + 2.4.0-SNAPSHOT Jedis Jedis is a blazingly small and sane Redis java client. https://github.com/xetorthio/jedis From e271acb79cb6f9bc562f71d21a4e1c9b87d01083 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Tue, 11 Feb 2014 12:04:47 -0500 Subject: [PATCH 040/120] Fix redis leak when testing --- Makefile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index ddc298a..a5328e2 100644 --- a/Makefile +++ b/Makefile @@ -180,9 +180,9 @@ stop: kill `cat /tmp/sentinel1.pid` kill `cat /tmp/sentinel2.pid` kill `cat /tmp/sentinel3.pid` - #kill `cat /tmp/redis_cluster_node1.pid` || true - #kill `cat /tmp/redis_cluster_node2.pid` || true - #kill `cat /tmp/redis_cluster_node3.pid` || true + kill `cat /tmp/redis_cluster_node1.pid` || true + kill `cat /tmp/redis_cluster_node2.pid` || true + kill `cat /tmp/redis_cluster_node3.pid` || true rm -f /tmp/redis_cluster_node1.conf rm -f /tmp/redis_cluster_node2.conf rm -f /tmp/redis_cluster_node3.conf From fcef705a6ca347593deb2f605625a2960c29a7da Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Tue, 11 Feb 2014 12:31:32 -0500 Subject: [PATCH 041/120] Add unit tests to Closeable --- .../java/redis/clients/jedis/tests/ConnectionTest.java | 7 +++++++ src/test/java/redis/clients/jedis/tests/JedisTest.java | 9 +++++++++ 2 files changed, 16 insertions(+) diff --git a/src/test/java/redis/clients/jedis/tests/ConnectionTest.java b/src/test/java/redis/clients/jedis/tests/ConnectionTest.java index 9cbaa12..d6175a5 100644 --- a/src/test/java/redis/clients/jedis/tests/ConnectionTest.java +++ b/src/test/java/redis/clients/jedis/tests/ConnectionTest.java @@ -41,4 +41,11 @@ public class ConnectionTest extends Assert { client.setTimeoutInfinite(); } + @Test + public void checkCloseable() { + client.setHost("localhost"); + client.setPort(6379); + client.connect(); + client.close(); + } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/JedisTest.java b/src/test/java/redis/clients/jedis/tests/JedisTest.java index b123b05..3f5cdf1 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisTest.java @@ -8,6 +8,7 @@ import java.util.Map; import org.junit.Test; +import redis.clients.jedis.BinaryJedis; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisShardInfo; import redis.clients.jedis.Protocol; @@ -91,4 +92,12 @@ public class JedisTest extends JedisCommandTestBase { assertEquals("PONG", jedis.ping()); assertEquals("bar", jedis.get("foo")); } + + @Test + public void checkCloseable() { + jedis.close(); + BinaryJedis bj = new BinaryJedis("localhost"); + bj.connect(); + bj.close(); + } } \ No newline at end of file From adc9cb215ae466d4252e322b6a83359d9a962477 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Tue, 11 Feb 2014 14:39:19 -0300 Subject: [PATCH 042/120] Fix ClusterCommandTest AfterClass handling as it may leave the cluster inconsistent --- .../clients/jedis/tests/commands/ClusterCommandsTest.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java index 59b288d..fb6264f 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java @@ -9,6 +9,7 @@ import org.junit.Test; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; +import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.tests.HostAndPortUtil; import redis.clients.jedis.tests.JedisTestBase; @@ -49,6 +50,11 @@ public class ClusterCommandsTest extends JedisTestBase { node2.clusterDelSlots(6000, 1, 2, 3, 4, 5, 500, 5000); node1.clusterAddSlots(6000); node1.clusterDelSlots(6000); + try { + node2.clusterDelSlots(10000); + } catch (JedisDataException jde) { + // Do nothing, slot may or may not be assigned depending on gossip + } } private static void waitForEqualClusterSize() throws InterruptedException { From ba9989e64c7d9610f4fc1a53c0a67d996a0bd85b Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Wed, 12 Feb 2014 00:39:12 -0300 Subject: [PATCH 043/120] Add support for redis cluster hashtags --- .../java/redis/clients/util/JedisClusterCRC16.java | 14 +++++++++++++- .../clients/jedis/tests/JedisClusterTest.java | 12 +++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/main/java/redis/clients/util/JedisClusterCRC16.java b/src/main/java/redis/clients/util/JedisClusterCRC16.java index c0d4afb..3c5c9b5 100644 --- a/src/main/java/redis/clients/util/JedisClusterCRC16.java +++ b/src/main/java/redis/clients/util/JedisClusterCRC16.java @@ -3,8 +3,20 @@ package redis.clients.util; public class JedisClusterCRC16 { public final static int polynomial = 0x1021; // Represents x^16+x^12+x^5+1 static int crc; + public static int getSlot(String key) { + int s = key.indexOf("{"); + if (s > -1) { + int e = key.indexOf("}", s+1); + if (e > -1 && e != s+1) { + key = key.substring(s+1, e); + } + } + return getCRC16(key) % 16384; + } + + private static int getCRC16(String key) { crc = 0x0000; for (byte b : key.getBytes()) { for (int i = 0; i < 8; i++) { @@ -18,6 +30,6 @@ public class JedisClusterCRC16 { } } - return crc &= 0xffff % 16384; + return crc &= 0xffff ; } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java index 356e642..de659e2 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java @@ -170,6 +170,16 @@ public class JedisClusterTest extends Assert { node2.clusterSetSlotMigrating(slot51, getNodeId(node3.clusterNodes())); jc.set("51", "foo"); } + + @Test + public void testRedisHashtag() { + assertEquals(JedisClusterCRC16.getSlot("{bar"), JedisClusterCRC16.getSlot("foo{{bar}}zap")); + assertEquals(JedisClusterCRC16.getSlot("{user1000}.following"), JedisClusterCRC16.getSlot("{user1000}.followers")); + assertNotEquals(JedisClusterCRC16.getSlot("foo{}{bar}"), JedisClusterCRC16.getSlot("bar")); + assertEquals(JedisClusterCRC16.getSlot("foo{bar}{zap}"), JedisClusterCRC16.getSlot("bar")); + + + } private String getNodeId(String infoOutput) { for (String infoLine : infoOutput.split("\n")) { @@ -191,5 +201,5 @@ public class JedisClusterTest extends Assert { Thread.sleep(50); } } - + } From 76814b56a1df1cc4b7d26c9f9486191a6ebd7562 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Wed, 12 Feb 2014 00:41:51 -0300 Subject: [PATCH 044/120] Remove unnecessary lines --- src/test/java/redis/clients/jedis/tests/JedisClusterTest.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java index de659e2..ff8a38f 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java @@ -177,8 +177,6 @@ public class JedisClusterTest extends Assert { assertEquals(JedisClusterCRC16.getSlot("{user1000}.following"), JedisClusterCRC16.getSlot("{user1000}.followers")); assertNotEquals(JedisClusterCRC16.getSlot("foo{}{bar}"), JedisClusterCRC16.getSlot("bar")); assertEquals(JedisClusterCRC16.getSlot("foo{bar}{zap}"), JedisClusterCRC16.getSlot("bar")); - - } private String getNodeId(String infoOutput) { From 9530eedf4d0a48cd5ce886f4339a56925c6bdfeb Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Wed, 12 Feb 2014 10:24:06 -0500 Subject: [PATCH 045/120] [maven-release-plugin] prepare release jedis-2.4.0 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 52f50af..5263b50 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ jar redis.clients jedis - 2.4.0-SNAPSHOT + 2.4.0 Jedis Jedis is a blazingly small and sane Redis java client. https://github.com/xetorthio/jedis @@ -41,7 +41,7 @@ scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git - jedis-2.2.0 + jedis-2.4.0 From 8d79bdef264fe88af870cf37f6468aec8ab4e120 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Wed, 12 Feb 2014 10:24:08 -0500 Subject: [PATCH 046/120] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 5263b50..064af01 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ jar redis.clients jedis - 2.4.0 + 2.4.1-SNAPSHOT Jedis Jedis is a blazingly small and sane Redis java client. https://github.com/xetorthio/jedis @@ -41,7 +41,7 @@ scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git - jedis-2.4.0 + jedis-2.2.0 From 7dc03cea1deac6082a38809828244676bb5c3961 Mon Sep 17 00:00:00 2001 From: Darren Shepherd Date: Tue, 28 Jan 2014 15:32:45 -0700 Subject: [PATCH 047/120] Add support for Travis CI --- .travis.yml | 7 +++++++ Makefile | 6 ++++++ 2 files changed, 13 insertions(+) create mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..aa9797b --- /dev/null +++ b/.travis.yml @@ -0,0 +1,7 @@ +language: java +jdk: + - openjdk6 + - openjdk7 + - oraclejdk7 +install: make travis-install +script: make test diff --git a/Makefile b/Makefile index 46e2c0e..ed635ce 100644 --- a/Makefile +++ b/Makefile @@ -1,3 +1,5 @@ +PATH := ./redis-git/src:${PATH} + define REDIS1_CONF daemonize yes port 6379 @@ -254,4 +256,8 @@ release: mvn release:perform make stop +travis-install: + [ ! -e redis-git ] && git clone https://github.com/antirez/redis.git redis-git || true + make -C redis-git -j4 + .PHONY: test From 072232038f8466680b68f732461e0f84a35edb05 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Thu, 13 Feb 2014 15:41:29 -0200 Subject: [PATCH 048/120] Add travis build status --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index ac3c67d..bbefbe1 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +[![Build Status](https://travis-ci.org/xetorthio/jedis.png?branch=master)](https://travis-ci.org/xetorthio/jedis) + # Jedis Jedis is a blazingly small and sane [Redis](http://github.com/antirez/redis "Redis") java client. From 1f7d1fda0001e35a945299dcdf574ccf60fcba28 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Thu, 13 Feb 2014 13:41:31 -0500 Subject: [PATCH 049/120] Makes sentinel tests more reliable by reducing the time it takes to mark master as odown. --- Makefile | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Makefile b/Makefile index ed635ce..6a4a77d 100644 --- a/Makefile +++ b/Makefile @@ -96,8 +96,8 @@ port 26379 daemonize yes sentinel monitor mymaster 127.0.0.1 6379 1 sentinel auth-pass mymaster foobared -sentinel down-after-milliseconds mymaster 3000 -sentinel failover-timeout mymaster 900000 +sentinel down-after-milliseconds mymaster 2000 +sentinel failover-timeout mymaster 180000 sentinel parallel-syncs mymaster 1 pidfile /tmp/sentinel1.pid logfile /tmp/sentinel1.log @@ -108,9 +108,9 @@ port 26380 daemonize yes sentinel monitor mymaster 127.0.0.1 6381 2 sentinel auth-pass mymaster foobared -sentinel down-after-milliseconds mymaster 3000 +sentinel down-after-milliseconds mymaster 2000 sentinel parallel-syncs mymaster 1 -sentinel failover-timeout mymaster 900000 +sentinel failover-timeout mymaster 180000 pidfile /tmp/sentinel2.pid logfile /tmp/sentinel2.log endef @@ -120,9 +120,9 @@ port 26381 daemonize yes sentinel monitor mymaster 127.0.0.1 6381 2 sentinel auth-pass mymaster foobared -sentinel down-after-milliseconds mymaster 3000 +sentinel down-after-milliseconds mymaster 2000 sentinel parallel-syncs mymaster 1 -sentinel failover-timeout mymaster 900000 +sentinel failover-timeout mymaster 180000 pidfile /tmp/sentinel3.pid logfile /tmp/sentinel3.log endef @@ -132,8 +132,8 @@ port 26382 daemonize yes sentinel monitor mymasterfailover 127.0.0.1 6385 1 sentinel auth-pass mymasterfailover foobared -sentinel down-after-milliseconds mymasterfailover 3000 -sentinel failover-timeout mymasterfailover 900000 +sentinel down-after-milliseconds mymasterfailover 2000 +sentinel failover-timeout mymasterfailover 180000 sentinel parallel-syncs mymasterfailover 1 pidfile /tmp/sentinel4.pid logfile /tmp/sentinel4.log From 1d0290d000cb0fcb2ef1ac9e01cd7588da53d589 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Thu, 13 Feb 2014 22:15:28 -0300 Subject: [PATCH 050/120] Improve JedsClusterTest setup speed --- .../clients/jedis/tests/JedisClusterTest.java | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java index ff8a38f..2913403 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java @@ -11,7 +11,6 @@ import org.junit.Test; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisCluster; -import redis.clients.jedis.Pipeline; import redis.clients.jedis.exceptions.JedisAskDataException; import redis.clients.jedis.exceptions.JedisClusterException; import redis.clients.jedis.exceptions.JedisClusterMaxRedirectionsException; @@ -26,7 +25,7 @@ public class JedisClusterTest extends Assert { private HostAndPort nodeInfo1 = HostAndPortUtil.getClusterServers().get(0); private HostAndPort nodeInfo2 = HostAndPortUtil.getClusterServers().get(1); private HostAndPort nodeInfo3 = HostAndPortUtil.getClusterServers().get(2); - + @Before public void setUp() throws InterruptedException { node1 = new Jedis(nodeInfo1.getHost(), nodeInfo1.getPort()); @@ -49,22 +48,23 @@ public class JedisClusterTest extends Assert { // split available slots across the three nodes int slotsPerNode = JedisCluster.HASHSLOTS / 3; - Pipeline pipeline1 = node1.pipelined(); - Pipeline pipeline2 = node2.pipelined(); - Pipeline pipeline3 = node3.pipelined(); - for (int i = 0; i < JedisCluster.HASHSLOTS; i++) { + int[] node1Slots = new int[slotsPerNode]; + int[] node2Slots = new int[slotsPerNode+1]; + int[] node3Slots = new int[slotsPerNode]; + for (int i = 0, slot1 = 0, slot2 = 0, slot3 = 0 ; i < JedisCluster.HASHSLOTS; i++) { if (i < slotsPerNode) { - pipeline1.clusterAddSlots(i); + node1Slots[slot1++] = i; } else if (i > slotsPerNode * 2) { - pipeline3.clusterAddSlots(i); + node3Slots[slot3++] = i; } else { - pipeline2.clusterAddSlots(i); + node2Slots[slot2++] = i; } } - pipeline1.sync(); - pipeline2.sync(); - pipeline3.sync(); - + + node1.clusterAddSlots(node1Slots); + node2.clusterAddSlots(node2Slots); + node3.clusterAddSlots(node3Slots); + waitForClusterReady(); } From b2fa6b6c405db7cb0a27167524e21f541fa79b47 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Fri, 14 Feb 2014 05:31:16 -0300 Subject: [PATCH 051/120] Improve Jedis Cluster tests and cleanup son they run much faster and reliable --- Makefile | 3 +++ .../clients/jedis/tests/JedisClusterTest.java | 17 +++++++++++--- .../tests/commands/ClusterCommandsTest.java | 23 ++++++++----------- 3 files changed, 26 insertions(+), 17 deletions(-) diff --git a/Makefile b/Makefile index 6a4a77d..3485047 100644 --- a/Makefile +++ b/Makefile @@ -143,6 +143,7 @@ endef define REDIS_CLUSTER_NODE1_CONF daemonize yes port 7379 +cluster-node-timeout 50 pidfile /tmp/redis_cluster_node1.pid logfile /tmp/redis_cluster_node1.log save "" @@ -154,6 +155,7 @@ endef define REDIS_CLUSTER_NODE2_CONF daemonize yes port 7380 +cluster-node-timeout 50 pidfile /tmp/redis_cluster_node2.pid logfile /tmp/redis_cluster_node2.log save "" @@ -165,6 +167,7 @@ endef define REDIS_CLUSTER_NODE3_CONF daemonize yes port 7381 +cluster-node-timeout 50 pidfile /tmp/redis_cluster_node3.pid logfile /tmp/redis_cluster_node3.log save "" diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java index 2913403..c138e8d 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java @@ -4,6 +4,7 @@ import java.util.HashSet; import java.util.Set; import org.junit.After; +import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -19,8 +20,8 @@ import redis.clients.util.JedisClusterCRC16; public class JedisClusterTest extends Assert { private Jedis node1; - private Jedis node2; - private Jedis node3; + private static Jedis node2; + private static Jedis node3; private HostAndPort nodeInfo1 = HostAndPortUtil.getClusterServers().get(0); private HostAndPort nodeInfo2 = HostAndPortUtil.getClusterServers().get(1); @@ -67,6 +68,16 @@ public class JedisClusterTest extends Assert { waitForClusterReady(); } + + @AfterClass + public static void cleanUp() { + int slotTest = JedisClusterCRC16.getSlot("test"); + int slot51 = JedisClusterCRC16.getSlot("51"); + String node3Id = getNodeId(node3.clusterNodes()); + node2.clusterSetSlotNode(slotTest, node3Id); + node2.clusterSetSlotNode(slot51, node3Id); + node2.clusterDelSlots(slotTest, slot51); + } @After public void tearDown() { @@ -179,7 +190,7 @@ public class JedisClusterTest extends Assert { assertEquals(JedisClusterCRC16.getSlot("foo{bar}{zap}"), JedisClusterCRC16.getSlot("bar")); } - private String getNodeId(String infoOutput) { + private static String getNodeId(String infoOutput) { for (String infoLine : infoOutput.split("\n")) { if (infoLine.contains("myself")) { return infoLine.split(" ")[0]; diff --git a/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java index fb6264f..03ebc89 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java @@ -40,29 +40,24 @@ public class ClusterCommandsTest extends JedisTestBase { @AfterClass public static void removeSlots() throws InterruptedException { - // This is to wait for gossip to replicate data. - waitForEqualClusterSize(); String[] nodes = node1.clusterNodes().split("\n"); String node1Id = nodes[0].split(" ")[0]; node1.clusterDelSlots(1, 2, 3, 4, 5, 500); node1.clusterSetSlotNode(5000, node1Id); node1.clusterDelSlots(5000, 10000); - node2.clusterDelSlots(6000, 1, 2, 3, 4, 5, 500, 5000); node1.clusterAddSlots(6000); node1.clusterDelSlots(6000); - try { - node2.clusterDelSlots(10000); - } catch (JedisDataException jde) { - // Do nothing, slot may or may not be assigned depending on gossip - } + waitForGossip(); + node2.clusterDelSlots(6000); + node1.clusterDelSlots(6000); } - private static void waitForEqualClusterSize() throws InterruptedException { - boolean notEqualSize = true; - while (notEqualSize) { - notEqualSize = getClusterAttribute(node1.clusterInfo(), - "cluster_known_nodes") == getClusterAttribute( - node2.clusterInfo(), "cluster_size") ? false : true; + private static void waitForGossip() { + boolean notReady = true; + while (notReady) { + if (node1.clusterNodes().contains("6000")) { + notReady = false; + } } } From d2e073b2f236724a5f051ae8b1ad430518bfce1b Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Sat, 15 Feb 2014 10:30:01 +0900 Subject: [PATCH 052/120] Use "sentinel failover" to force failover * Use "sentinel failover" to force failover ** faster than kill redis instances * set failover timeout to 1 min ** It makes sense with failover within localhost * reduce instances : 1 Redis Server and 1 Sentinel ** port is not changed -> I'll changed later at end of refactoring --- Makefile | 48 ++++--------------- .../jedis/tests/JedisSentinelPoolTest.java | 25 ++++------ 2 files changed, 17 insertions(+), 56 deletions(-) diff --git a/Makefile b/Makefile index 3485047..3e64c21 100644 --- a/Makefile +++ b/Makefile @@ -25,6 +25,7 @@ define REDIS3_CONF daemonize yes port 6381 requirepass foobared +masterauth foobared pidfile /tmp/redis3.pid logfile /tmp/redis3.log save "" @@ -43,18 +44,6 @@ appendonly no slaveof localhost 6381 endef -define REDIS5_CONF -daemonize yes -port 6383 -requirepass foobared -masterauth foobared -pidfile /tmp/redis5.pid -logfile /tmp/redis5.log -save "" -appendonly no -slaveof localhost 6381 -endef - define REDIS6_CONF daemonize yes port 6384 @@ -97,7 +86,7 @@ daemonize yes sentinel monitor mymaster 127.0.0.1 6379 1 sentinel auth-pass mymaster foobared sentinel down-after-milliseconds mymaster 2000 -sentinel failover-timeout mymaster 180000 +sentinel failover-timeout mymaster 60000 sentinel parallel-syncs mymaster 1 pidfile /tmp/sentinel1.pid logfile /tmp/sentinel1.log @@ -106,34 +95,22 @@ endef define REDIS_SENTINEL2 port 26380 daemonize yes -sentinel monitor mymaster 127.0.0.1 6381 2 +sentinel monitor mymaster 127.0.0.1 6381 1 sentinel auth-pass mymaster foobared sentinel down-after-milliseconds mymaster 2000 sentinel parallel-syncs mymaster 1 -sentinel failover-timeout mymaster 180000 +sentinel failover-timeout mymaster 60000 pidfile /tmp/sentinel2.pid logfile /tmp/sentinel2.log endef -define REDIS_SENTINEL3 -port 26381 -daemonize yes -sentinel monitor mymaster 127.0.0.1 6381 2 -sentinel auth-pass mymaster foobared -sentinel down-after-milliseconds mymaster 2000 -sentinel parallel-syncs mymaster 1 -sentinel failover-timeout mymaster 180000 -pidfile /tmp/sentinel3.pid -logfile /tmp/sentinel3.log -endef - define REDIS_SENTINEL4 port 26382 daemonize yes sentinel monitor mymasterfailover 127.0.0.1 6385 1 sentinel auth-pass mymasterfailover foobared sentinel down-after-milliseconds mymasterfailover 2000 -sentinel failover-timeout mymasterfailover 180000 +sentinel failover-timeout mymasterfailover 60000 sentinel parallel-syncs mymasterfailover 1 pidfile /tmp/sentinel4.pid logfile /tmp/sentinel4.log @@ -180,13 +157,11 @@ export REDIS1_CONF export REDIS2_CONF export REDIS3_CONF export REDIS4_CONF -export REDIS5_CONF export REDIS6_CONF export REDIS7_CONF export REDIS8_CONF export REDIS_SENTINEL1 export REDIS_SENTINEL2 -export REDIS_SENTINEL3 export REDIS_SENTINEL4 export REDIS_CLUSTER_NODE1_CONF export REDIS_CLUSTER_NODE2_CONF @@ -197,7 +172,6 @@ start: cleanup echo "$$REDIS2_CONF" | redis-server - echo "$$REDIS3_CONF" | redis-server - echo "$$REDIS4_CONF" | redis-server - - echo "$$REDIS5_CONF" | redis-server - echo "$$REDIS6_CONF" | redis-server - echo "$$REDIS7_CONF" | redis-server - echo "$$REDIS8_CONF" | redis-server - @@ -205,8 +179,6 @@ start: cleanup @sleep 0.5 echo "$$REDIS_SENTINEL2" > /tmp/sentinel2.conf && redis-server /tmp/sentinel2.conf --sentinel @sleep 0.5 - echo "$$REDIS_SENTINEL3" > /tmp/sentinel3.conf && redis-server /tmp/sentinel3.conf --sentinel - @sleep 0.5 echo "$$REDIS_SENTINEL4" > /tmp/sentinel4.conf && redis-server /tmp/sentinel4.conf --sentinel echo "$$REDIS_CLUSTER_NODE1_CONF" | redis-server - echo "$$REDIS_CLUSTER_NODE2_CONF" | redis-server - @@ -219,23 +191,19 @@ cleanup: stop: kill `cat /tmp/redis1.pid` kill `cat /tmp/redis2.pid` - # this get's segfaulted by the tests - kill `cat /tmp/redis3.pid` || true - kill `cat /tmp/redis4.pid` || true - kill `cat /tmp/redis5.pid` || true - kill `cat /tmp/redis6.pid` || true + kill `cat /tmp/redis3.pid` + kill `cat /tmp/redis4.pid` + kill `cat /tmp/redis6.pid` kill `cat /tmp/redis7.pid` kill `cat /tmp/redis8.pid` kill `cat /tmp/sentinel1.pid` kill `cat /tmp/sentinel2.pid` - kill `cat /tmp/sentinel3.pid` kill `cat /tmp/sentinel4.pid` kill `cat /tmp/redis_cluster_node1.pid` || true kill `cat /tmp/redis_cluster_node2.pid` || true kill `cat /tmp/redis_cluster_node3.pid` || true rm -f /tmp/sentinel1.conf rm -f /tmp/sentinel2.conf - rm -f /tmp/sentinel3.conf rm -f /tmp/sentinel4.conf rm -f /tmp/redis_cluster_node1.conf rm -f /tmp/redis_cluster_node2.conf diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java index f8a3ee2..62fffe6 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java @@ -14,6 +14,7 @@ import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPubSub; import redis.clients.jedis.JedisSentinelPool; import redis.clients.jedis.Transaction; +import redis.clients.jedis.exceptions.JedisDataException; public class JedisSentinelPoolTest extends JedisTestBase { private static final String MASTER_NAME = "mymaster"; @@ -26,8 +27,6 @@ public class JedisSentinelPoolTest extends JedisTestBase { .get(4); protected static HostAndPort sentinel1 = HostAndPortUtil .getSentinelServers().get(1); - protected static HostAndPort sentinel2 = HostAndPortUtil - .getSentinelServers().get(2); protected static Jedis sentinelJedis1; @@ -36,7 +35,6 @@ public class JedisSentinelPoolTest extends JedisTestBase { @Before public void setUp() throws Exception { sentinels.add(sentinel1.toString()); - sentinels.add(sentinel2.toString()); sentinelJedis1 = new Jedis(sentinel1.getHost(), sentinel1.getPort()); } @@ -46,30 +44,25 @@ public class JedisSentinelPoolTest extends JedisTestBase { JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels, new GenericObjectPoolConfig(), 1000, "foobared", 2); - // perform failover - doSegFaultMaster(pool); - - // perform failover once again - doSegFaultMaster(pool); - + forceFailover(pool); + forceFailover(pool); + // you can test failover as much as possible - // but you need to prepare additional slave per failover } - private void doSegFaultMaster(JedisSentinelPool pool) - throws InterruptedException { + private void forceFailover(JedisSentinelPool pool) throws InterruptedException { HostAndPort oldMaster = pool.getCurrentHostMaster(); // jedis connection should be master Jedis jedis = pool.getResource(); assertEquals("PONG", jedis.ping()); - try { - jedis.debug(DebugParams.SEGFAULT()); - } catch (Exception e) { - } + // It can throw JedisDataException while there's no slave to promote + // There's nothing we can do, so we just pass Exception to make test fail fast + sentinelJedis1.sentinelFailover(MASTER_NAME); waitForFailover(pool, oldMaster); + // JedisSentinelPool recognize master but may not changed internal pool yet Thread.sleep(100); jedis = pool.getResource(); From 0909811538d91b0fd6d88da08012f3026645d8f3 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Sat, 15 Feb 2014 11:00:46 +0900 Subject: [PATCH 053/120] Let JedisSentinelPoolTest recognizes "aborted failover" and fail fast * let unit test fail if -failover-abort-* message is produced while waiting to failover ** waiting more is meaningless, and there is nothing we can do ** we can request "sentinel failover" to failover again, but it may can fail again --- .../jedis/tests/JedisSentinelPoolTest.java | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java index 62fffe6..b153c27 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java @@ -14,6 +14,7 @@ import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPubSub; import redis.clients.jedis.JedisSentinelPool; import redis.clients.jedis.Transaction; +import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisDataException; public class JedisSentinelPoolTest extends JedisTestBase { @@ -86,8 +87,6 @@ public class JedisSentinelPoolTest extends JedisTestBase { @Override public void onMessage(String channel, String message) { - // TODO Auto-generated method stub - } @Override @@ -96,33 +95,27 @@ public class JedisSentinelPoolTest extends JedisTestBase { if (channel.equals("+switch-master")) { newmaster.set(message); punsubscribe(); + } else if (channel.startsWith("-failover-abort")) { + punsubscribe(); + fail("Unfortunately sentinel cannot failover... reason(channel) : " + + channel + " / message : " + message); } - // TODO Auto-generated method stub - } @Override public void onSubscribe(String channel, int subscribedChannels) { - // TODO Auto-generated method stub - } @Override public void onUnsubscribe(String channel, int subscribedChannels) { - // TODO Auto-generated method stub - } @Override public void onPUnsubscribe(String pattern, int subscribedChannels) { - // TODO Auto-generated method stub - } @Override public void onPSubscribe(String pattern, int subscribedChannels) { - // TODO Auto-generated method stub - } }, "*"); From a3862bc2dd96805b85d2a99ed03e5d76c615e1d9 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Sat, 15 Feb 2014 12:53:30 +0900 Subject: [PATCH 054/120] Clean up JedisSentinelTestUtil * remove all unused methods * move JedisSentinelPoolTest.waitForJedisSentinelPoolRecognizeNewMaster to JedisSentinelTestUtil ** both JedisSentinelTest and JedisSentinelPoolTest can use this implementation * introduce FailoverAbortedException ** throws when we subscribe sentinel channels and got message by "-failover-abort-*" channel * respect Source Format to Java Convention (by Eclipse -> Source -> Format) --- .../tests/utils/FailoverAbortedException.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 src/test/java/redis/clients/jedis/tests/utils/FailoverAbortedException.java diff --git a/src/test/java/redis/clients/jedis/tests/utils/FailoverAbortedException.java b/src/test/java/redis/clients/jedis/tests/utils/FailoverAbortedException.java new file mode 100644 index 0000000..e711087 --- /dev/null +++ b/src/test/java/redis/clients/jedis/tests/utils/FailoverAbortedException.java @@ -0,0 +1,17 @@ +package redis.clients.jedis.tests.utils; + +public class FailoverAbortedException extends RuntimeException { + private static final long serialVersionUID = 1925110762858409954L; + + public FailoverAbortedException(String message) { + super(message); + } + + public FailoverAbortedException(Throwable cause) { + super(cause); + } + + public FailoverAbortedException(String message, Throwable cause) { + super(message, cause); + } +} From d937b48f9093b9e0bfa85eadc595c4e542c95d17 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Sat, 15 Feb 2014 12:57:40 +0900 Subject: [PATCH 055/120] Revert "Clean up JedisSentinelTestUtil" This reverts commit a3862bc2dd96805b85d2a99ed03e5d76c615e1d9. --- .../tests/utils/FailoverAbortedException.java | 17 ----------------- 1 file changed, 17 deletions(-) delete mode 100644 src/test/java/redis/clients/jedis/tests/utils/FailoverAbortedException.java diff --git a/src/test/java/redis/clients/jedis/tests/utils/FailoverAbortedException.java b/src/test/java/redis/clients/jedis/tests/utils/FailoverAbortedException.java deleted file mode 100644 index e711087..0000000 --- a/src/test/java/redis/clients/jedis/tests/utils/FailoverAbortedException.java +++ /dev/null @@ -1,17 +0,0 @@ -package redis.clients.jedis.tests.utils; - -public class FailoverAbortedException extends RuntimeException { - private static final long serialVersionUID = 1925110762858409954L; - - public FailoverAbortedException(String message) { - super(message); - } - - public FailoverAbortedException(Throwable cause) { - super(cause); - } - - public FailoverAbortedException(String message, Throwable cause) { - super(message, cause); - } -} From 57b17dcc7114e3b6788a9332a0a1127cbcf793ba Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Sat, 15 Feb 2014 13:12:08 +0900 Subject: [PATCH 056/120] Clean up JedisSentinelTestUtil * remove all unused methods * move JedisSentinelPoolTest.waitForJedisSentinelPoolRecognizeNewMaster to JedisSentin ** both JedisSentinelTest and JedisSentinelPoolTest can use this implementation * introduce FailoverAbortedException ** throws when we subscribe sentinel channels and got message by "-failover-abort-*" c * respect Source Format to Java Convention (by Eclipse -> Source -> Format) --- .../jedis/tests/JedisSentinelPoolTest.java | 105 +++++------ .../jedis/tests/JedisSentinelTest.java | 166 ++++++++++-------- .../tests/utils/FailoverAbortedException.java | 17 ++ .../tests/utils/JedisSentinelTestUtil.java | 153 +++++----------- 4 files changed, 195 insertions(+), 246 deletions(-) create mode 100644 src/test/java/redis/clients/jedis/tests/utils/FailoverAbortedException.java diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java index b153c27..8db9bf0 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java @@ -2,20 +2,17 @@ package redis.clients.jedis.tests; import java.util.HashSet; import java.util.Set; -import java.util.concurrent.atomic.AtomicReference; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.junit.Before; import org.junit.Test; -import redis.clients.jedis.DebugParams; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisPubSub; import redis.clients.jedis.JedisSentinelPool; import redis.clients.jedis.Transaction; import redis.clients.jedis.exceptions.JedisConnectionException; -import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.tests.utils.JedisSentinelTestUtil; public class JedisSentinelPoolTest extends JedisTestBase { private static final String MASTER_NAME = "mymaster"; @@ -47,11 +44,12 @@ public class JedisSentinelPoolTest extends JedisTestBase { forceFailover(pool); forceFailover(pool); - + // you can test failover as much as possible } - private void forceFailover(JedisSentinelPool pool) throws InterruptedException { + private void forceFailover(JedisSentinelPool pool) + throws InterruptedException { HostAndPort oldMaster = pool.getCurrentHostMaster(); // jedis connection should be master @@ -59,13 +57,15 @@ public class JedisSentinelPoolTest extends JedisTestBase { assertEquals("PONG", jedis.ping()); // It can throw JedisDataException while there's no slave to promote - // There's nothing we can do, so we just pass Exception to make test fail fast + // There's nothing we can do, so we just pass Exception to make test + // fail fast sentinelJedis1.sentinelFailover(MASTER_NAME); - + waitForFailover(pool, oldMaster); - // JedisSentinelPool recognize master but may not changed internal pool yet + // JedisSentinelPool recognize master but may not changed internal pool + // yet Thread.sleep(100); - + jedis = pool.getResource(); assertEquals("PONG", jedis.ping()); assertEquals("foobared", jedis.configGet("requirepass").get(1)); @@ -74,54 +74,15 @@ public class JedisSentinelPoolTest extends JedisTestBase { private void waitForFailover(JedisSentinelPool pool, HostAndPort oldMaster) throws InterruptedException { - waitForJedisSentinelPoolRecognizeNewMaster(pool); + HostAndPort newMaster = JedisSentinelTestUtil + .waitForNewPromotedMaster(sentinelJedis1); + + waitForJedisSentinelPoolRecognizeNewMaster(pool, newMaster); } private void waitForJedisSentinelPoolRecognizeNewMaster( - JedisSentinelPool pool) throws InterruptedException { - - final AtomicReference newmaster = new AtomicReference( - ""); - - sentinelJedis1.psubscribe(new JedisPubSub() { - - @Override - public void onMessage(String channel, String message) { - } - - @Override - public void onPMessage(String pattern, String channel, - String message) { - if (channel.equals("+switch-master")) { - newmaster.set(message); - punsubscribe(); - } else if (channel.startsWith("-failover-abort")) { - punsubscribe(); - fail("Unfortunately sentinel cannot failover... reason(channel) : " + - channel + " / message : " + message); - } - } - - @Override - public void onSubscribe(String channel, int subscribedChannels) { - } - - @Override - public void onUnsubscribe(String channel, int subscribedChannels) { - } - - @Override - public void onPUnsubscribe(String pattern, int subscribedChannels) { - } - - @Override - public void onPSubscribe(String pattern, int subscribedChannels) { - } - }, "*"); - - String[] chunks = newmaster.get().split(" "); - HostAndPort newMaster = new HostAndPort(chunks[3], - Integer.parseInt(chunks[4])); + JedisSentinelPool pool, HostAndPort newMaster) + throws InterruptedException { while (true) { String host = pool.getCurrentHostMaster().getHost(); @@ -136,7 +97,7 @@ public class JedisSentinelPoolTest extends JedisTestBase { Thread.sleep(100); } } - + @Test public void returnResourceShouldResetState() { GenericObjectPoolConfig config = new GenericObjectPoolConfig(); @@ -146,15 +107,29 @@ public class JedisSentinelPoolTest extends JedisTestBase { config, 1000, "foobared", 2); Jedis jedis = pool.getResource(); - jedis.set("hello", "jedis"); - Transaction t = jedis.multi(); - t.set("hello", "world"); - pool.returnResource(jedis); + Jedis jedis2 = null; + + try { + jedis.set("hello", "jedis"); + Transaction t = jedis.multi(); + t.set("hello", "world"); + pool.returnResource(jedis); + + jedis2 = pool.getResource(); - Jedis jedis2 = pool.getResource(); - assertTrue(jedis == jedis2); - assertEquals("jedis", jedis2.get("hello")); - pool.returnResource(jedis2); - pool.destroy(); + assertTrue(jedis == jedis2); + assertEquals("jedis", jedis2.get("hello")); + } catch (JedisConnectionException e) { + if (jedis2 != null) { + pool.returnBrokenResource(jedis2); + jedis2 = null; + } + } finally { + if (jedis2 != null) + pool.returnResource(jedis2); + + pool.destroy(); + } } + } diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java b/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java index 4445072..7e9a97a 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java @@ -50,30 +50,35 @@ public class JedisSentinelTest extends JedisTestBase { @Test public void sentinel() { Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); - List> masters = j.sentinelMasters(); - boolean inMasters = false; - for (Map master : masters) - if (MASTER_NAME.equals(master.get("name"))) - inMasters = true; + try { + List> masters = j.sentinelMasters(); - assertTrue(inMasters); + boolean inMasters = false; + for (Map master : masters) + if (MASTER_NAME.equals(master.get("name"))) + inMasters = true; - List masterHostAndPort = j - .sentinelGetMasterAddrByName(MASTER_NAME); - HostAndPort masterFromSentinel = new HostAndPort( - masterHostAndPort.get(0), Integer.parseInt(masterHostAndPort - .get(1))); - assertEquals(master, masterFromSentinel); + assertTrue(inMasters); - List> slaves = j.sentinelSlaves(MASTER_NAME); - assertTrue(slaves.size() > 0); - assertEquals(master.getPort(), - Integer.parseInt(slaves.get(0).get("master-port"))); + List masterHostAndPort = j + .sentinelGetMasterAddrByName(MASTER_NAME); + HostAndPort masterFromSentinel = new HostAndPort( + masterHostAndPort.get(0), + Integer.parseInt(masterHostAndPort.get(1))); + assertEquals(master, masterFromSentinel); - // DO NOT RE-RUN TEST TOO FAST, RESET TAKES SOME TIME TO... RESET - assertEquals(Long.valueOf(1), j.sentinelReset(MASTER_NAME)); - assertEquals(Long.valueOf(0), j.sentinelReset("woof" + MASTER_NAME)); + List> slaves = j.sentinelSlaves(MASTER_NAME); + assertTrue(slaves.size() > 0); + assertEquals(master.getPort(), + Integer.parseInt(slaves.get(0).get("master-port"))); + + // DO NOT RE-RUN TEST TOO FAST, RESET TAKES SOME TIME TO... RESET + assertEquals(Long.valueOf(1), j.sentinelReset(MASTER_NAME)); + assertEquals(Long.valueOf(0), j.sentinelReset("woof" + MASTER_NAME)); + } finally { + j.close(); + } } @Test @@ -81,40 +86,49 @@ public class JedisSentinelTest extends JedisTestBase { Jedis j = new Jedis(sentinelForFailover.getHost(), sentinelForFailover.getPort()); - HostAndPort currentMaster = new HostAndPort( - masterForFailover.getHost(), masterForFailover.getPort()); + try { + HostAndPort currentMaster = new HostAndPort( + masterForFailover.getHost(), masterForFailover.getPort()); - List masterHostAndPort = j - .sentinelGetMasterAddrByName(FAILOVER_MASTER_NAME); - String result = j.sentinelFailover(FAILOVER_MASTER_NAME); - assertEquals("OK", result); + List masterHostAndPort = j + .sentinelGetMasterAddrByName(FAILOVER_MASTER_NAME); + String result = j.sentinelFailover(FAILOVER_MASTER_NAME); + assertEquals("OK", result); - JedisSentinelTestUtil.waitForNewPromotedMaster(sentinelForFailover, - FAILOVER_MASTER_NAME, currentMaster); + JedisSentinelTestUtil.waitForNewPromotedMaster(j); - masterHostAndPort = j.sentinelGetMasterAddrByName(FAILOVER_MASTER_NAME); - HostAndPort newMaster = new HostAndPort(masterHostAndPort.get(0), - Integer.parseInt(masterHostAndPort.get(1))); + masterHostAndPort = j + .sentinelGetMasterAddrByName(FAILOVER_MASTER_NAME); + HostAndPort newMaster = new HostAndPort(masterHostAndPort.get(0), + Integer.parseInt(masterHostAndPort.get(1))); + + assertNotEquals(newMaster, currentMaster); + } finally { + j.close(); + } - assertNotEquals(newMaster, currentMaster); } @Test public void sentinelMonitor() { Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); - // monitor new master - String result = j.sentinelMonitor(MONITOR_MASTER_NAME, MASTER_IP, - master.getPort(), 1); - assertEquals("OK", result); - - // already monitored try { - j.sentinelMonitor(MONITOR_MASTER_NAME, MASTER_IP, master.getPort(), - 1); - fail(); - } catch (JedisDataException e) { - // pass + // monitor new master + String result = j.sentinelMonitor(MONITOR_MASTER_NAME, MASTER_IP, + master.getPort(), 1); + assertEquals("OK", result); + + // already monitored + try { + j.sentinelMonitor(MONITOR_MASTER_NAME, MASTER_IP, + master.getPort(), 1); + fail(); + } catch (JedisDataException e) { + // pass + } + } finally { + j.close(); } } @@ -122,19 +136,23 @@ public class JedisSentinelTest extends JedisTestBase { public void sentinelRemove() { Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); - ensureMonitored(sentinel, REMOVE_MASTER_NAME, MASTER_IP, - master.getPort(), 1); - - String result = j.sentinelRemove(REMOVE_MASTER_NAME); - assertEquals("OK", result); - - // not exist try { - result = j.sentinelRemove(REMOVE_MASTER_NAME); - assertNotEquals("OK", result); - fail(); - } catch (JedisDataException e) { - // pass + ensureMonitored(sentinel, REMOVE_MASTER_NAME, MASTER_IP, + master.getPort(), 1); + + String result = j.sentinelRemove(REMOVE_MASTER_NAME); + assertEquals("OK", result); + + // not exist + try { + result = j.sentinelRemove(REMOVE_MASTER_NAME); + assertNotEquals("OK", result); + fail(); + } catch (JedisDataException e) { + // pass + } + } finally { + j.close(); } } @@ -142,24 +160,29 @@ public class JedisSentinelTest extends JedisTestBase { public void sentinelSet() { Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); - Map parameterMap = new HashMap(); - parameterMap.put("down-after-milliseconds", String.valueOf(1234)); - parameterMap.put("parallel-syncs", String.valueOf(3)); - parameterMap.put("quorum", String.valueOf(2)); - j.sentinelSet(MASTER_NAME, parameterMap); + try { + Map parameterMap = new HashMap(); + parameterMap.put("down-after-milliseconds", String.valueOf(1234)); + parameterMap.put("parallel-syncs", String.valueOf(3)); + parameterMap.put("quorum", String.valueOf(2)); + j.sentinelSet(MASTER_NAME, parameterMap); - List> masters = j.sentinelMasters(); - for (Map master : masters) { - if (master.get("name").equals(MASTER_NAME)) { - assertEquals(1234, - Integer.parseInt(master.get("down-after-milliseconds"))); - assertEquals(3, Integer.parseInt(master.get("parallel-syncs"))); - assertEquals(2, Integer.parseInt(master.get("quorum"))); + List> masters = j.sentinelMasters(); + for (Map master : masters) { + if (master.get("name").equals(MASTER_NAME)) { + assertEquals(1234, Integer.parseInt(master + .get("down-after-milliseconds"))); + assertEquals(3, + Integer.parseInt(master.get("parallel-syncs"))); + assertEquals(2, Integer.parseInt(master.get("quorum"))); + } } - } - parameterMap.put("quorum", String.valueOf(1)); - j.sentinelSet(MASTER_NAME, parameterMap); + parameterMap.put("quorum", String.valueOf(1)); + j.sentinelSet(MASTER_NAME, parameterMap); + } finally { + j.close(); + } } private void ensureMonitored(HostAndPort sentinel, String masterName, @@ -168,6 +191,8 @@ public class JedisSentinelTest extends JedisTestBase { try { j.sentinelMonitor(masterName, ip, port, quorum); } catch (JedisDataException e) { + } finally { + j.close(); } } @@ -176,6 +201,9 @@ public class JedisSentinelTest extends JedisTestBase { try { j.sentinelRemove(masterName); } catch (JedisDataException e) { + } finally { + j.close(); } } + } diff --git a/src/test/java/redis/clients/jedis/tests/utils/FailoverAbortedException.java b/src/test/java/redis/clients/jedis/tests/utils/FailoverAbortedException.java new file mode 100644 index 0000000..e711087 --- /dev/null +++ b/src/test/java/redis/clients/jedis/tests/utils/FailoverAbortedException.java @@ -0,0 +1,17 @@ +package redis.clients.jedis.tests.utils; + +public class FailoverAbortedException extends RuntimeException { + private static final long serialVersionUID = 1925110762858409954L; + + public FailoverAbortedException(String message) { + super(message); + } + + public FailoverAbortedException(Throwable cause) { + super(cause); + } + + public FailoverAbortedException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/test/java/redis/clients/jedis/tests/utils/JedisSentinelTestUtil.java b/src/test/java/redis/clients/jedis/tests/utils/JedisSentinelTestUtil.java index 9ac4a85..dcb9334 100644 --- a/src/test/java/redis/clients/jedis/tests/utils/JedisSentinelTestUtil.java +++ b/src/test/java/redis/clients/jedis/tests/utils/JedisSentinelTestUtil.java @@ -1,131 +1,60 @@ package redis.clients.jedis.tests.utils; -import java.util.List; -import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPubSub; +import redis.clients.jedis.tests.utils.FailoverAbortedException; public class JedisSentinelTestUtil { - - public static void waitForSentinelRecognizeRedisReplication( - HostAndPort sentinel, String masterName, HostAndPort master, - List slaves) throws InterruptedException { - Jedis sentinelJedis = new Jedis(sentinel.getHost(), sentinel.getPort()); - while (true) { - Thread.sleep(1000); - - if (!isMasterRecognized(sentinelJedis, masterName, master)) { - System.out.println("Master not recognized by Sentinel " - + sentinel.getHost() + ":" + sentinel.getPort() - + ", sleep..."); - continue; - } - - if (!isSlavesRecognized(sentinelJedis, masterName, slaves)) { - System.out.println("Slaves not recognized by Sentinel " - + sentinel.getHost() + ":" + sentinel.getPort() - + ", sleep..."); - continue; - } - - // all recognized - break; - } - - } - - public static HostAndPort waitForNewPromotedMaster(HostAndPort sentinel, - String masterName, HostAndPort oldMaster) + public static HostAndPort waitForNewPromotedMaster(Jedis sentinelJedis) throws InterruptedException { - Jedis sentinelJedis = new Jedis(sentinel.getHost(), sentinel.getPort()); + + final AtomicReference newmaster = new AtomicReference( + ""); - HostAndPort newMaster = null; - while (true) { - Thread.sleep(1000); + sentinelJedis.psubscribe(new JedisPubSub() { - List sentinelMasterInfos = sentinelJedis - .sentinelGetMasterAddrByName(masterName); - if (sentinelMasterInfos == null) { - System.out - .println("Cannot retrieve Sentinel's master address info, sleep..."); - continue; + @Override + public void onMessage(String channel, String message) { } - newMaster = new HostAndPort(sentinelMasterInfos.get(0), - Integer.parseInt(sentinelMasterInfos.get(1))); + @Override + public void onPMessage(String pattern, String channel, + String message) { + if (channel.equals("+switch-master")) { + newmaster.set(message); + punsubscribe(); + } else if (channel.startsWith("-failover-abort")) { + punsubscribe(); + throw new FailoverAbortedException("Unfortunately sentinel cannot failover... reason(channel) : " + + channel + " / message : " + message); + } + } - if (!newMaster.equals(oldMaster)) - break; + @Override + public void onSubscribe(String channel, int subscribedChannels) { + } - System.out - .println("Sentinel's master is not yet changed, sleep..."); - } + @Override + public void onUnsubscribe(String channel, int subscribedChannels) { + } + + @Override + public void onPUnsubscribe(String pattern, int subscribedChannels) { + } + + @Override + public void onPSubscribe(String pattern, int subscribedChannels) { + } + }, "*"); + + String[] chunks = newmaster.get().split(" "); + HostAndPort newMaster = new HostAndPort(chunks[3], + Integer.parseInt(chunks[4])); return newMaster; } - public static void waitForSentinelsRecognizeEachOthers() - throws InterruptedException { - // During failover, master has been changed - // It means that sentinels need to recognize other sentinels from new - // master's hello channel - // Without recognizing, Sentinels cannot run failover - - // Sentinels need to take some time to recognize each other... - // http://redis.io/topics/sentinel - // Sentinel Rule #8: Every Sentinel publishes a message to every - // monitored master - // Pub/Sub channel __sentinel__:hello, every five seconds, blabla... - - // FIXME There're no command for sentinel to list recognized sentinels - // so sleep wisely (channel's hello message interval + margin) - Thread.sleep(5000 + 500); - } - - private static boolean isMasterRecognized(Jedis sentinelJedis, - String masterName, HostAndPort master) { - List sentinelMasterInfos = sentinelJedis - .sentinelGetMasterAddrByName(masterName); - if (sentinelMasterInfos == null) - return false; - - HostAndPort sentinelMaster = new HostAndPort( - sentinelMasterInfos.get(0), - Integer.parseInt(sentinelMasterInfos.get(1))); - - return sentinelMaster.equals(master); - } - - private static boolean isSlavesRecognized(Jedis sentinelJedis, - String masterName, List slaves) { - List> slavesMap = sentinelJedis - .sentinelSlaves(masterName); - - if (slavesMap.size() != slaves.size()) - return false; - - int slavesRecognized = 0; - - for (HostAndPort slave : slaves) { - if (isSlaveFoundInSlavesMap(slavesMap, slave)) - slavesRecognized++; - } - - return slavesRecognized == slaves.size(); - } - - private static boolean isSlaveFoundInSlavesMap( - List> slavesMap, HostAndPort slave) { - for (Map slaveMap : slavesMap) { - HostAndPort sentinelSlave = new HostAndPort(slaveMap.get("ip"), - Integer.parseInt(slaveMap.get("port"))); - - if (sentinelSlave.equals(slave)) - return true; - } - - return false; - } - } From cee792dbfb92f6371de036e1afee56e651a9c25a Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Sat, 15 Feb 2014 13:13:32 +0900 Subject: [PATCH 057/120] Modify method sequence : public -> private --- .../jedis/tests/JedisSentinelPoolTest.java | 68 +++++++++---------- 1 file changed, 34 insertions(+), 34 deletions(-) diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java index 8db9bf0..4b0e06f 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java @@ -47,6 +47,40 @@ public class JedisSentinelPoolTest extends JedisTestBase { // you can test failover as much as possible } + + @Test + public void returnResourceShouldResetState() { + GenericObjectPoolConfig config = new GenericObjectPoolConfig(); + config.setMaxTotal(1); + config.setBlockWhenExhausted(false); + JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels, + config, 1000, "foobared", 2); + + Jedis jedis = pool.getResource(); + Jedis jedis2 = null; + + try { + jedis.set("hello", "jedis"); + Transaction t = jedis.multi(); + t.set("hello", "world"); + pool.returnResource(jedis); + + jedis2 = pool.getResource(); + + assertTrue(jedis == jedis2); + assertEquals("jedis", jedis2.get("hello")); + } catch (JedisConnectionException e) { + if (jedis2 != null) { + pool.returnBrokenResource(jedis2); + jedis2 = null; + } + } finally { + if (jedis2 != null) + pool.returnResource(jedis2); + + pool.destroy(); + } + } private void forceFailover(JedisSentinelPool pool) throws InterruptedException { @@ -98,38 +132,4 @@ public class JedisSentinelPoolTest extends JedisTestBase { } } - @Test - public void returnResourceShouldResetState() { - GenericObjectPoolConfig config = new GenericObjectPoolConfig(); - config.setMaxTotal(1); - config.setBlockWhenExhausted(false); - JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels, - config, 1000, "foobared", 2); - - Jedis jedis = pool.getResource(); - Jedis jedis2 = null; - - try { - jedis.set("hello", "jedis"); - Transaction t = jedis.multi(); - t.set("hello", "world"); - pool.returnResource(jedis); - - jedis2 = pool.getResource(); - - assertTrue(jedis == jedis2); - assertEquals("jedis", jedis2.get("hello")); - } catch (JedisConnectionException e) { - if (jedis2 != null) { - pool.returnBrokenResource(jedis2); - jedis2 = null; - } - } finally { - if (jedis2 != null) - pool.returnResource(jedis2); - - pool.destroy(); - } - } - } From ef95688701526b0b54a7d0d5dc8f1470ea5ed4bb Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Sat, 15 Feb 2014 13:21:07 +0900 Subject: [PATCH 058/120] set sentinel failover-timeout longer (120000 ms) * failover-timeout 60000 (ms) always success with local machine ** but sometimes failed with Travis CI --- Makefile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index 3e64c21..66d6e98 100644 --- a/Makefile +++ b/Makefile @@ -86,7 +86,7 @@ daemonize yes sentinel monitor mymaster 127.0.0.1 6379 1 sentinel auth-pass mymaster foobared sentinel down-after-milliseconds mymaster 2000 -sentinel failover-timeout mymaster 60000 +sentinel failover-timeout mymaster 120000 sentinel parallel-syncs mymaster 1 pidfile /tmp/sentinel1.pid logfile /tmp/sentinel1.log @@ -99,7 +99,7 @@ sentinel monitor mymaster 127.0.0.1 6381 1 sentinel auth-pass mymaster foobared sentinel down-after-milliseconds mymaster 2000 sentinel parallel-syncs mymaster 1 -sentinel failover-timeout mymaster 60000 +sentinel failover-timeout mymaster 120000 pidfile /tmp/sentinel2.pid logfile /tmp/sentinel2.log endef @@ -110,7 +110,7 @@ daemonize yes sentinel monitor mymasterfailover 127.0.0.1 6385 1 sentinel auth-pass mymasterfailover foobared sentinel down-after-milliseconds mymasterfailover 2000 -sentinel failover-timeout mymasterfailover 60000 +sentinel failover-timeout mymasterfailover 120000 sentinel parallel-syncs mymasterfailover 1 pidfile /tmp/sentinel4.pid logfile /tmp/sentinel4.log From 05d63bbda46e4834022b10c75c71602ca2ffb1a9 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Sat, 15 Feb 2014 20:22:50 +0900 Subject: [PATCH 059/120] Shift Redis/Sentinel instances to remove unused index * Redis instances : 6, 7, 8 -> 5, 6, 7 * Sentinel instances : 4 -> 3 --- Makefile | 50 +++++++++---------- pom.xml | 4 +- .../clients/jedis/tests/HostAndPortUtil.java | 1 - .../jedis/tests/JedisSentinelPoolTest.java | 2 - .../jedis/tests/JedisSentinelTest.java | 13 +++-- 5 files changed, 33 insertions(+), 37 deletions(-) diff --git a/Makefile b/Makefile index 66d6e98..1ac2bb9 100644 --- a/Makefile +++ b/Makefile @@ -44,6 +44,18 @@ appendonly no slaveof localhost 6381 endef +define REDIS5_CONF +daemonize yes +port 6383 +requirepass foobared +masterauth foobared +pidfile /tmp/redis5.pid +logfile /tmp/redis5.log +save "" +appendonly no +slaveof localhost 6379 +endef + define REDIS6_CONF daemonize yes port 6384 @@ -53,7 +65,6 @@ pidfile /tmp/redis6.pid logfile /tmp/redis6.log save "" appendonly no -slaveof localhost 6379 endef define REDIS7_CONF @@ -65,18 +76,7 @@ pidfile /tmp/redis7.pid logfile /tmp/redis7.log save "" appendonly no -endef - -define REDIS8_CONF -daemonize yes -port 6386 -requirepass foobared -masterauth foobared -pidfile /tmp/redis8.pid -logfile /tmp/redis8.log -save "" -appendonly no -slaveof localhost 6385 +slaveof localhost 6384 endef # SENTINELS @@ -104,16 +104,16 @@ pidfile /tmp/sentinel2.pid logfile /tmp/sentinel2.log endef -define REDIS_SENTINEL4 -port 26382 +define REDIS_SENTINEL3 +port 26381 daemonize yes -sentinel monitor mymasterfailover 127.0.0.1 6385 1 +sentinel monitor mymasterfailover 127.0.0.1 6384 1 sentinel auth-pass mymasterfailover foobared sentinel down-after-milliseconds mymasterfailover 2000 sentinel failover-timeout mymasterfailover 120000 sentinel parallel-syncs mymasterfailover 1 -pidfile /tmp/sentinel4.pid -logfile /tmp/sentinel4.log +pidfile /tmp/sentinel3.pid +logfile /tmp/sentinel3.log endef # CLUSTER REDIS NODES @@ -157,12 +157,12 @@ export REDIS1_CONF export REDIS2_CONF export REDIS3_CONF export REDIS4_CONF +export REDIS5_CONF export REDIS6_CONF export REDIS7_CONF -export REDIS8_CONF export REDIS_SENTINEL1 export REDIS_SENTINEL2 -export REDIS_SENTINEL4 +export REDIS_SENTINEL3 export REDIS_CLUSTER_NODE1_CONF export REDIS_CLUSTER_NODE2_CONF export REDIS_CLUSTER_NODE3_CONF @@ -172,14 +172,14 @@ start: cleanup echo "$$REDIS2_CONF" | redis-server - echo "$$REDIS3_CONF" | redis-server - echo "$$REDIS4_CONF" | redis-server - + echo "$$REDIS5_CONF" | redis-server - echo "$$REDIS6_CONF" | redis-server - echo "$$REDIS7_CONF" | redis-server - - echo "$$REDIS8_CONF" | redis-server - echo "$$REDIS_SENTINEL1" > /tmp/sentinel1.conf && redis-server /tmp/sentinel1.conf --sentinel @sleep 0.5 echo "$$REDIS_SENTINEL2" > /tmp/sentinel2.conf && redis-server /tmp/sentinel2.conf --sentinel @sleep 0.5 - echo "$$REDIS_SENTINEL4" > /tmp/sentinel4.conf && redis-server /tmp/sentinel4.conf --sentinel + echo "$$REDIS_SENTINEL3" > /tmp/sentinel3.conf && redis-server /tmp/sentinel3.conf --sentinel echo "$$REDIS_CLUSTER_NODE1_CONF" | redis-server - echo "$$REDIS_CLUSTER_NODE2_CONF" | redis-server - echo "$$REDIS_CLUSTER_NODE3_CONF" | redis-server - @@ -193,18 +193,18 @@ stop: kill `cat /tmp/redis2.pid` kill `cat /tmp/redis3.pid` kill `cat /tmp/redis4.pid` + kill `cat /tmp/redis5.pid` kill `cat /tmp/redis6.pid` kill `cat /tmp/redis7.pid` - kill `cat /tmp/redis8.pid` kill `cat /tmp/sentinel1.pid` kill `cat /tmp/sentinel2.pid` - kill `cat /tmp/sentinel4.pid` + kill `cat /tmp/sentinel3.pid` kill `cat /tmp/redis_cluster_node1.pid` || true kill `cat /tmp/redis_cluster_node2.pid` || true kill `cat /tmp/redis_cluster_node3.pid` || true rm -f /tmp/sentinel1.conf rm -f /tmp/sentinel2.conf - rm -f /tmp/sentinel4.conf + rm -f /tmp/sentinel3.conf rm -f /tmp/redis_cluster_node1.conf rm -f /tmp/redis_cluster_node2.conf rm -f /tmp/redis_cluster_node3.conf diff --git a/pom.xml b/pom.xml index 064af01..7008df1 100644 --- a/pom.xml +++ b/pom.xml @@ -45,8 +45,8 @@ - localhost:6379,localhost:6380,localhost:6381,localhost:6382,localhost:6383,localhost:6384,localhost:6385,localhost:6386 - localhost:26379,localhost:26380,localhost:26381,localhost:26382 + localhost:6379,localhost:6380,localhost:6381,localhost:6382,localhost:6383,localhost:6384,localhost:6385 + localhost:26379,localhost:26380,localhost:26381 localhost:7379,localhost:7380,localhost:7381 github diff --git a/src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java b/src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java index 491f0a3..cb7a58b 100644 --- a/src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java +++ b/src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java @@ -23,7 +23,6 @@ public class HostAndPortUtil { 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", 7380)); diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java index 4b0e06f..c8df9c5 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java @@ -21,8 +21,6 @@ public class JedisSentinelPoolTest extends JedisTestBase { .get(2); protected static HostAndPort slave1 = HostAndPortUtil.getRedisServers() .get(3); - protected static HostAndPort slave2 = HostAndPortUtil.getRedisServers() - .get(4); protected static HostAndPort sentinel1 = HostAndPortUtil .getSentinelServers().get(1); diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java b/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java index 7e9a97a..822c659 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java @@ -22,15 +22,15 @@ public class JedisSentinelTest extends JedisTestBase { protected static HostAndPort master = HostAndPortUtil.getRedisServers() .get(0); - protected static HostAndPort slave = HostAndPortUtil.getRedisServers().get( - 5); + protected static HostAndPort slave = HostAndPortUtil.getRedisServers() + .get(4); protected static HostAndPort sentinel = HostAndPortUtil .getSentinelServers().get(0); protected static HostAndPort sentinelForFailover = HostAndPortUtil - .getSentinelServers().get(3); + .getSentinelServers().get(2); protected static HostAndPort masterForFailover = HostAndPortUtil - .getRedisServers().get(6); + .getRedisServers().get(5); @Before public void setup() throws InterruptedException { @@ -87,11 +87,10 @@ public class JedisSentinelTest extends JedisTestBase { sentinelForFailover.getPort()); try { - HostAndPort currentMaster = new HostAndPort( - masterForFailover.getHost(), masterForFailover.getPort()); - List masterHostAndPort = j .sentinelGetMasterAddrByName(FAILOVER_MASTER_NAME); + HostAndPort currentMaster = new HostAndPort(masterHostAndPort.get(0), + Integer.parseInt(masterHostAndPort.get(1))); String result = j.sentinelFailover(FAILOVER_MASTER_NAME); assertEquals("OK", result); From 68ee4e49d061ad66352e146612c2ab9bdc0fd566 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Mon, 17 Feb 2014 13:37:06 +0900 Subject: [PATCH 060/120] Set dependency to Response when multi in pipeline and build dependency first if Response's dependency found and not built * there's some dependency with exec response and command responses within multi * if command responses's get() called before exec response's build(), it calls exec response's build() first * unit test included --- .../java/redis/clients/jedis/Pipeline.java | 7 ++++ .../java/redis/clients/jedis/Response.java | 34 ++++++++++++++----- .../clients/jedis/tests/PipeliningTest.java | 21 ++++++++++++ 3 files changed, 54 insertions(+), 8 deletions(-) diff --git a/src/main/java/redis/clients/jedis/Pipeline.java b/src/main/java/redis/clients/jedis/Pipeline.java index 97f856b..2687f84 100755 --- a/src/main/java/redis/clients/jedis/Pipeline.java +++ b/src/main/java/redis/clients/jedis/Pipeline.java @@ -31,6 +31,12 @@ public class Pipeline extends MultiKeyPipelineBase { return values; } + public void setResponseDependency(Response dependency) { + for (Response response : responses) { + response.setDependency(dependency); + } + } + public void addResponse(Response response) { responses.add(response); } @@ -106,6 +112,7 @@ public class Pipeline extends MultiKeyPipelineBase { public Response> exec() { client.exec(); Response> response = super.getResponse(currentMulti); + currentMulti.setResponseDependency(response); currentMulti = null; return response; } diff --git a/src/main/java/redis/clients/jedis/Response.java b/src/main/java/redis/clients/jedis/Response.java index b17f314..955277a 100644 --- a/src/main/java/redis/clients/jedis/Response.java +++ b/src/main/java/redis/clients/jedis/Response.java @@ -8,6 +8,8 @@ public class Response { private boolean set = false; private Builder builder; private Object data; + private Response dependency = null; + private boolean requestDependencyBuild = false; public Response(Builder b) { this.builder = b; @@ -19,23 +21,39 @@ public class Response { } public T get() { + // if response has dependency response and dependency is not built, + // build it first and no more!! + if (!requestDependencyBuild && dependency != null && dependency.set + && !dependency.built) { + requestDependencyBuild = true; + dependency.build(); + } if (!set) { throw new JedisDataException( "Please close pipeline or multi block before calling this method."); } if (!built) { - if (data != null) { - if (data instanceof JedisDataException) { - throw new JedisDataException((JedisDataException) data); - } - response = builder.build(data); - } - this.data = null; - built = true; + build(); } return response; } + public void setDependency(Response dependency) { + this.dependency = dependency; + this.requestDependencyBuild = false; + } + + private void build() { + if (data != null) { + if (data instanceof JedisDataException) { + throw new JedisDataException((JedisDataException) data); + } + response = builder.build(data); + } + data = null; + built = true; + } + public String toString() { return "Response " + builder.toString(); } diff --git a/src/test/java/redis/clients/jedis/tests/PipeliningTest.java b/src/test/java/redis/clients/jedis/tests/PipeliningTest.java index aed67dc..d3cddd0 100755 --- a/src/test/java/redis/clients/jedis/tests/PipeliningTest.java +++ b/src/test/java/redis/clients/jedis/tests/PipeliningTest.java @@ -251,6 +251,27 @@ public class PipeliningTest extends Assert { } + @Test + public void multiWithSync() { + jedis.set("foo", "314"); + jedis.set("bar", "foo"); + jedis.set("hello", "world"); + Pipeline p = jedis.pipelined(); + Response r1 = p.get("bar"); + p.multi(); + Response r2 = p.get("foo"); + p.exec(); + Response r3 = p.get("hello"); + p.sync(); + + // before multi + assertEquals("foo", r1.get()); + // It should be readable whether exec's response was built or not + assertEquals("314", r2.get()); + // after multi + assertEquals("world", r3.get()); + } + @Test public void testDiscardInPipeline() { Pipeline pipeline = jedis.pipelined(); From c4fb2b4adca709ad27e5e11fdc8488dd4dbd1658 Mon Sep 17 00:00:00 2001 From: Mayank Dang Date: Mon, 17 Feb 2014 16:52:19 +0530 Subject: [PATCH 061/120] Fix #550 : Removed redundant call to connectionPool.getResource() in method getConnectionFromSlot(int slot) in class JedisSlotBasedConnectionHandler --- .gitignore | 3 +++ .../redis/clients/jedis/JedisSlotBasedConnectionHandler.java | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 982e6b6..181df84 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,6 @@ target/ build/ bin/ tags +.idea +*.aof +*.rdb diff --git a/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java index 4aba893..36c04ed 100644 --- a/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java +++ b/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java @@ -40,7 +40,7 @@ public class JedisSlotBasedConnectionHandler extends connectionPool = getRandomConnection(); } currentConnection = connectionPool.getResource(); - return connectionPool.getResource(); + return currentConnection; } } From b7d551149a972f98fa51daad64a6bd9956d0d7c2 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Mon, 17 Feb 2014 18:01:19 -0500 Subject: [PATCH 062/120] It is better to point everything to localhost and we just make sure there is not redis running on port 1234 when renning the tests. --- .../java/redis/clients/jedis/tests/ShardedJedisPoolTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolTest.java b/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolTest.java index 35d7c54..ee7951b 100644 --- a/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolTest.java +++ b/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolTest.java @@ -155,7 +155,7 @@ public class ShardedJedisPoolTest extends Assert { // items on one shard // alter shard 1 and recreate pool pool.destroy(); - shards.set(1, new JedisShardInfo("nohost", 1234)); + shards.set(1, new JedisShardInfo("localhost", 1234)); pool = new ShardedJedisPool(redisConfig, shards); jedis = pool.getResource(); Long actual = Long.valueOf(0); From 89ccd8dfdd12c3884a4bc31b98c9f753d4e34a0f Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Mon, 17 Feb 2014 18:12:21 -0500 Subject: [PATCH 063/120] [maven-release-plugin] prepare release jedis-2.4.1 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 7008df1..71a27d6 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ jar redis.clients jedis - 2.4.1-SNAPSHOT + 2.4.1 Jedis Jedis is a blazingly small and sane Redis java client. https://github.com/xetorthio/jedis @@ -41,7 +41,7 @@ scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git - jedis-2.2.0 + jedis-2.4.1 From bfa4a80b0141fcb2370b6677d078c2241e68e15f Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Mon, 17 Feb 2014 18:12:23 -0500 Subject: [PATCH 064/120] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 71a27d6..a55806e 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ jar redis.clients jedis - 2.4.1 + 2.4.2-SNAPSHOT Jedis Jedis is a blazingly small and sane Redis java client. https://github.com/xetorthio/jedis @@ -41,7 +41,7 @@ scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git - jedis-2.4.1 + jedis-2.2.0 From e4de67048eac13e67f3fa683d7360a400d882f1f Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Tue, 18 Feb 2014 21:59:53 -0300 Subject: [PATCH 065/120] Make JedisCluster multihread by improving connection handling --- .../redis/clients/jedis/JedisCluster.java | 488 +++++++++--------- .../clients/jedis/JedisClusterCommand.java | 13 +- .../jedis/JedisClusterConnectionHandler.java | 7 + .../JedisSlotBasedConnectionHandler.java | 19 +- 4 files changed, 262 insertions(+), 265 deletions(-) diff --git a/src/main/java/redis/clients/jedis/JedisCluster.java b/src/main/java/redis/clients/jedis/JedisCluster.java index bec2574..1f645ea 100644 --- a/src/main/java/redis/clients/jedis/JedisCluster.java +++ b/src/main/java/redis/clients/jedis/JedisCluster.java @@ -38,8 +38,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().set(key, value); + public String execute(Jedis connection) { + return connection.set(key, value); } }.run(key); } @@ -49,8 +49,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().get(key); + public String execute(Jedis connection) { + return connection.get(key); } }.run(key); } @@ -60,8 +60,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Boolean execute() { - return connectionHandler.getConnection().exists(key); + public Boolean execute(Jedis connection) { + return connection.exists(key); } }.run(key); } @@ -71,8 +71,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().persist(key); + public Long execute(Jedis connection) { + return connection.persist(key); } }.run(key); } @@ -82,8 +82,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().type(key); + public String execute(Jedis connection) { + return connection.type(key); } }.run(key); } @@ -93,8 +93,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().expire(key, seconds); + public Long execute(Jedis connection) { + return connection.expire(key, seconds); } }.run(key); } @@ -104,8 +104,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection() + public Long execute(Jedis connection) { + return connection .expireAt(key, unixTime); } }.run(key); @@ -116,8 +116,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().ttl(key); + public Long execute(Jedis connection) { + return connection.ttl(key); } }.run(key); } @@ -128,8 +128,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Boolean execute() { - return connectionHandler.getConnection().setbit(key, offset, + public Boolean execute(Jedis connection) { + return connection.setbit(key, offset, value); } }.run(key); @@ -141,8 +141,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Boolean execute() { - return connectionHandler.getConnection().setbit(key, offset, + public Boolean execute(Jedis connection) { + return connection.setbit(key, offset, value); } }.run(key); @@ -153,8 +153,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Boolean execute() { - return connectionHandler.getConnection().getbit(key, offset); + public Boolean execute(Jedis connection) { + return connection.getbit(key, offset); } }.run(key); } @@ -164,8 +164,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().setrange(key, offset, + public Long execute(Jedis connection) { + return connection.setrange(key, offset, value); } }.run(key); @@ -177,8 +177,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().getrange(key, + public String execute(Jedis connection) { + return connection.getrange(key, startOffset, endOffset); } }.run(key); @@ -189,8 +189,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().getSet(key, value); + public String execute(Jedis connection) { + return connection.getSet(key, value); } }.run(key); } @@ -200,8 +200,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().setnx(key, value); + public Long execute(Jedis connection) { + return connection.setnx(key, value); } }.run(key); } @@ -211,8 +211,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().setex(key, seconds, + public String execute(Jedis connection) { + return connection.setex(key, seconds, value); } }.run(key); @@ -223,8 +223,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().decrBy(key, integer); + public Long execute(Jedis connection) { + return connection.decrBy(key, integer); } }.run(key); } @@ -234,8 +234,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().decr(key); + public Long execute(Jedis connection) { + return connection.decr(key); } }.run(key); } @@ -245,8 +245,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().incrBy(key, integer); + public Long execute(Jedis connection) { + return connection.incrBy(key, integer); } }.run(key); } @@ -256,8 +256,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().incr(key); + public Long execute(Jedis connection) { + return connection.incr(key); } }.run(key); } @@ -267,8 +267,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().append(key, value); + public Long execute(Jedis connection) { + return connection.append(key, value); } }.run(key); } @@ -278,8 +278,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection() + public String execute(Jedis connection) { + return connection .substr(key, start, end); } }.run(key); @@ -290,8 +290,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection() + public Long execute(Jedis connection) { + return connection .hset(key, field, value); } }.run(key); @@ -302,8 +302,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().hget(key, field); + public String execute(Jedis connection) { + return connection.hget(key, field); } }.run(key); } @@ -313,8 +313,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().hsetnx(key, field, + public Long execute(Jedis connection) { + return connection.hsetnx(key, field, value); } }.run(key); @@ -325,8 +325,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().hmset(key, hash); + public String execute(Jedis connection) { + return connection.hmset(key, hash); } }.run(key); } @@ -336,8 +336,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public List execute() { - return connectionHandler.getConnection().hmget(key, fields); + public List execute(Jedis connection) { + return connection.hmget(key, fields); } }.run(key); } @@ -347,8 +347,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().hincrBy(key, field, + public Long execute(Jedis connection) { + return connection.hincrBy(key, field, value); } }.run(key); @@ -359,8 +359,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Boolean execute() { - return connectionHandler.getConnection().hexists(key, field); + public Boolean execute(Jedis connection) { + return connection.hexists(key, field); } }.run(key); } @@ -370,8 +370,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().hdel(key, field); + public Long execute(Jedis connection) { + return connection.hdel(key, field); } }.run(key); } @@ -381,8 +381,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().hdel(key); + public Long execute(Jedis connection) { + return connection.hdel(key); } }.run(key); } @@ -392,8 +392,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public Set execute() { - return connectionHandler.getConnection().hkeys(key); + public Set execute(Jedis connection) { + return connection.hkeys(key); } }.run(key); } @@ -403,8 +403,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public List execute() { - return connectionHandler.getConnection().hvals(key); + public List execute(Jedis connection) { + return connection.hvals(key); } }.run(key); } @@ -414,8 +414,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public Map execute() { - return connectionHandler.getConnection().hgetAll(key); + public Map execute(Jedis connection) { + return connection.hgetAll(key); } }.run(key); } @@ -425,8 +425,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().rpush(key, string); + public Long execute(Jedis connection) { + return connection.rpush(key, string); } }.run(key); } @@ -436,8 +436,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().lpush(key, string); + public Long execute(Jedis connection) { + return connection.lpush(key, string); } }.run(key); } @@ -447,8 +447,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().llen(key); + public Long execute(Jedis connection) { + return connection.llen(key); } }.run(key); } @@ -459,8 +459,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public List execute() { - return connectionHandler.getConnection() + public List execute(Jedis connection) { + return connection .lrange(key, start, end); } }.run(key); @@ -471,8 +471,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().ltrim(key, start, end); + public String execute(Jedis connection) { + return connection.ltrim(key, start, end); } }.run(key); } @@ -482,8 +482,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().lindex(key, index); + public String execute(Jedis connection) { + return connection.lindex(key, index); } }.run(key); } @@ -493,8 +493,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection() + public String execute(Jedis connection) { + return connection .lset(key, index, value); } }.run(key); @@ -505,8 +505,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection() + public Long execute(Jedis connection) { + return connection .lrem(key, count, value); } }.run(key); @@ -517,8 +517,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().lpop(key); + public String execute(Jedis connection) { + return connection.lpop(key); } }.run(key); } @@ -528,8 +528,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().rpop(key); + public String execute(Jedis connection) { + return connection.rpop(key); } }.run(key); } @@ -539,8 +539,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().sadd(key, member); + public Long execute(Jedis connection) { + return connection.sadd(key, member); } }.run(key); } @@ -550,8 +550,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public Set execute() { - return connectionHandler.getConnection().smembers(key); + public Set execute(Jedis connection) { + return connection.smembers(key); } }.run(key); } @@ -561,8 +561,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().srem(key, member); + public Long execute(Jedis connection) { + return connection.srem(key, member); } }.run(key); } @@ -572,8 +572,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().spop(key); + public String execute(Jedis connection) { + return connection.spop(key); } }.run(key); } @@ -583,8 +583,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().scard(key); + public Long execute(Jedis connection) { + return connection.scard(key); } }.run(key); } @@ -594,8 +594,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Boolean execute() { - return connectionHandler.getConnection().sismember(key, member); + public Boolean execute(Jedis connection) { + return connection.sismember(key, member); } }.run(key); } @@ -605,8 +605,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().srandmember(key); + public String execute(Jedis connection) { + return connection.srandmember(key); } }.run(key); } @@ -616,8 +616,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().strlen(key); + public Long execute(Jedis connection) { + return connection.strlen(key); } }.run(key); } @@ -627,8 +627,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().zadd(key, score, + public Long execute(Jedis connection) { + return connection.zadd(key, score, member); } }.run(key); @@ -639,8 +639,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection() + public Long execute(Jedis connection) { + return connection .zadd(key, scoreMembers); } }.run(key); @@ -651,8 +651,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public Set execute() { - return connectionHandler.getConnection() + public Set execute(Jedis connection) { + return connection .zrange(key, start, end); } }.run(key); @@ -663,8 +663,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().zrem(key, member); + public Long execute(Jedis connection) { + return connection.zrem(key, member); } }.run(key); } @@ -675,8 +675,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Double execute() { - return connectionHandler.getConnection().zincrby(key, score, + public Double execute(Jedis connection) { + return connection.zincrby(key, score, member); } }.run(key); @@ -687,8 +687,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().zrank(key, member); + public Long execute(Jedis connection) { + return connection.zrank(key, member); } }.run(key); } @@ -698,8 +698,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().zrevrank(key, member); + public Long execute(Jedis connection) { + return connection.zrevrank(key, member); } }.run(key); } @@ -710,8 +710,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public Set execute() { - return connectionHandler.getConnection().zrevrange(key, start, + public Set execute(Jedis connection) { + return connection.zrevrange(key, start, end); } }.run(key); @@ -723,8 +723,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public Set execute() { - return connectionHandler.getConnection().zrangeWithScores(key, + public Set execute(Jedis connection) { + return connection.zrangeWithScores(key, start, end); } }.run(key); @@ -736,8 +736,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public Set execute() { - return connectionHandler.getConnection().zrevrangeWithScores( + public Set execute(Jedis connection) { + return connection.zrevrangeWithScores( key, start, end); } }.run(key); @@ -748,8 +748,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().zcard(key); + public Long execute(Jedis connection) { + return connection.zcard(key); } }.run(key); } @@ -759,8 +759,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Double execute() { - return connectionHandler.getConnection().zscore(key, member); + public Double execute(Jedis connection) { + return connection.zscore(key, member); } }.run(key); } @@ -770,8 +770,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public List execute() { - return connectionHandler.getConnection().sort(key); + public List execute(Jedis connection) { + return connection.sort(key); } }.run(key); } @@ -782,8 +782,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public List execute() { - return connectionHandler.getConnection().sort(key, + public List execute(Jedis connection) { + return connection.sort(key, sortingParameters); } }.run(key); @@ -794,8 +794,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().zcount(key, min, max); + public Long execute(Jedis connection) { + return connection.zcount(key, min, max); } }.run(key); } @@ -805,8 +805,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().zcount(key, min, max); + public Long execute(Jedis connection) { + return connection.zcount(key, min, max); } }.run(key); } @@ -817,8 +817,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public Set execute() { - return connectionHandler.getConnection().zrangeByScore(key, + public Set execute(Jedis connection) { + return connection.zrangeByScore(key, min, max); } }.run(key); @@ -830,8 +830,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public Set execute() { - return connectionHandler.getConnection().zrangeByScore(key, + public Set execute(Jedis connection) { + return connection.zrangeByScore(key, min, max); } }.run(key); @@ -843,8 +843,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public Set execute() { - return connectionHandler.getConnection().zrevrangeByScore(key, + public Set execute(Jedis connection) { + return connection.zrevrangeByScore(key, min, max); } }.run(key); @@ -856,8 +856,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public Set execute() { - return connectionHandler.getConnection().zrangeByScore(key, + public Set execute(Jedis connection) { + return connection.zrangeByScore(key, min, max, offset, count); } }.run(key); @@ -869,8 +869,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public Set execute() { - return connectionHandler.getConnection().zrevrangeByScore(key, + public Set execute(Jedis connection) { + return connection.zrevrangeByScore(key, min, max); } }.run(key); @@ -882,8 +882,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public Set execute() { - return connectionHandler.getConnection().zrangeByScore(key, + public Set execute(Jedis connection) { + return connection.zrangeByScore(key, min, max, offset, count); } }.run(key); @@ -895,8 +895,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public Set execute() { - return connectionHandler.getConnection().zrevrangeByScore(key, + public Set execute(Jedis connection) { + return connection.zrevrangeByScore(key, min, max, offset, count); } }.run(key); @@ -908,8 +908,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public Set execute() { - return connectionHandler.getConnection() + public Set execute(Jedis connection) { + return connection .zrangeByScoreWithScores(key, min, max); } }.run(key); @@ -921,8 +921,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public Set execute() { - return connectionHandler.getConnection() + public Set execute(Jedis connection) { + return connection .zrevrangeByScoreWithScores(key, min, max); } }.run(key); @@ -935,8 +935,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public Set execute() { - return connectionHandler.getConnection() + public Set execute(Jedis connection) { + return connection .zrangeByScoreWithScores(key, min, max, offset, count); } }.run(key); @@ -948,8 +948,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public Set execute() { - return connectionHandler.getConnection().zrevrangeByScore(key, + public Set execute(Jedis connection) { + return connection.zrevrangeByScore(key, min, max, offset, count); } }.run(key); @@ -961,8 +961,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public Set execute() { - return connectionHandler.getConnection() + public Set execute(Jedis connection) { + return connection .zrangeByScoreWithScores(key, min, max); } }.run(key); @@ -974,8 +974,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public Set execute() { - return connectionHandler.getConnection() + public Set execute(Jedis connection) { + return connection .zrevrangeByScoreWithScores(key, min, max); } }.run(key); @@ -988,8 +988,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public Set execute() { - return connectionHandler.getConnection() + public Set execute(Jedis connection) { + return connection .zrangeByScoreWithScores(key, min, max, offset, count); } }.run(key); @@ -1002,8 +1002,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public Set execute() { - return connectionHandler.getConnection() + public Set execute(Jedis connection) { + return connection .zrevrangeByScoreWithScores(key, max, min, offset, count); } @@ -1017,8 +1017,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public Set execute() { - return connectionHandler.getConnection() + public Set execute(Jedis connection) { + return connection .zrevrangeByScoreWithScores(key, max, min, offset, count); } @@ -1031,8 +1031,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().zremrangeByRank(key, + public Long execute(Jedis connection) { + return connection.zremrangeByRank(key, start, end); } }.run(key); @@ -1044,8 +1044,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().zremrangeByScore(key, + public Long execute(Jedis connection) { + return connection.zremrangeByScore(key, start, end); } }.run(key); @@ -1057,8 +1057,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().zremrangeByScore(key, + public Long execute(Jedis connection) { + return connection.zremrangeByScore(key, start, end); } }.run(key); @@ -1070,8 +1070,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().linsert(key, where, + public Long execute(Jedis connection) { + return connection.linsert(key, where, pivot, value); } }.run(key); @@ -1082,8 +1082,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().lpushx(key, string); + public Long execute(Jedis connection) { + return connection.lpushx(key, string); } }.run(key); } @@ -1093,8 +1093,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().rpushx(key, string); + public Long execute(Jedis connection) { + return connection.rpushx(key, string); } }.run(key); } @@ -1104,8 +1104,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public List execute() { - return connectionHandler.getConnection().blpop(arg); + public List execute(Jedis connection) { + return connection.blpop(arg); } }.run(null); } @@ -1115,8 +1115,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public List execute() { - return connectionHandler.getConnection().brpop(arg); + public List execute(Jedis connection) { + return connection.brpop(arg); } }.run(null); } @@ -1126,8 +1126,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().del(key); + public Long execute(Jedis connection) { + return connection.del(key); } }.run(null); } @@ -1137,8 +1137,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().echo(string); + public String execute(Jedis connection) { + return connection.echo(string); } }.run(null); } @@ -1148,8 +1148,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().move(key, dbIndex); + public Long execute(Jedis connection) { + return connection.move(key, dbIndex); } }.run(key); } @@ -1159,8 +1159,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().bitcount(key); + public Long execute(Jedis connection) { + return connection.bitcount(key); } }.run(key); } @@ -1170,8 +1170,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().bitcount(key, start, + public Long execute(Jedis connection) { + return connection.bitcount(key, start, end); } }.run(key); @@ -1182,8 +1182,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().ping(); + public String execute(Jedis connection) { + return connection.ping(); } }.run(null); } @@ -1193,8 +1193,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().quit(); + public String execute(Jedis connection) { + return connection.quit(); } }.run(null); } @@ -1204,8 +1204,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().flushDB(); + public String execute(Jedis connection) { + return connection.flushDB(); } }.run(null); } @@ -1215,8 +1215,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().dbSize(); + public Long execute(Jedis connection) { + return connection.dbSize(); } }.run(null); } @@ -1226,8 +1226,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().select(index); + public String execute(Jedis connection) { + return connection.select(index); } }.run(null); } @@ -1237,8 +1237,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().flushAll(); + public String execute(Jedis connection) { + return connection.flushAll(); } }.run(null); } @@ -1248,8 +1248,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().auth(password); + public String execute(Jedis connection) { + return connection.auth(password); } }.run(null); } @@ -1259,8 +1259,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().save(); + public String execute(Jedis connection) { + return connection.save(); } }.run(null); } @@ -1270,8 +1270,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().bgsave(); + public String execute(Jedis connection) { + return connection.bgsave(); } }.run(null); } @@ -1281,8 +1281,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().bgrewriteaof(); + public String execute(Jedis connection) { + return connection.bgrewriteaof(); } }.run(null); } @@ -1292,8 +1292,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().lastsave(); + public Long execute(Jedis connection) { + return connection.lastsave(); } }.run(null); } @@ -1303,8 +1303,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().shutdown(); + public String execute(Jedis connection) { + return connection.shutdown(); } }.run(null); } @@ -1314,8 +1314,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().info(); + public String execute(Jedis connection) { + return connection.info(); } }.run(null); } @@ -1325,8 +1325,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().info(section); + public String execute(Jedis connection) { + return connection.info(section); } }.run(null); } @@ -1336,8 +1336,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().slaveof(host, port); + public String execute(Jedis connection) { + return connection.slaveof(host, port); } }.run(null); } @@ -1347,8 +1347,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().slaveofNoOne(); + public String execute(Jedis connection) { + return connection.slaveofNoOne(); } }.run(null); } @@ -1358,8 +1358,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public Long execute() { - return connectionHandler.getConnection().getDB(); + public Long execute(Jedis connection) { + return connection.getDB(); } }.run(null); } @@ -1369,8 +1369,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().debug(params); + public String execute(Jedis connection) { + return connection.debug(params); } }.run(null); } @@ -1380,8 +1380,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override - public String execute() { - return connectionHandler.getConnection().configResetStat(); + public String execute(Jedis connection) { + return connection.configResetStat(); } }.run(null); } @@ -1408,8 +1408,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>>( connectionHandler, timeout, maxRedirections) { @Override - public ScanResult> execute() { - return connectionHandler.getConnection().hscan(key, cursor); + public ScanResult> execute(Jedis connection) { + return connection.hscan(key, cursor); } }.run(null); } @@ -1425,8 +1425,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public ScanResult execute() { - return connectionHandler.getConnection().sscan(key, cursor); + public ScanResult execute(Jedis connection) { + return connection.sscan(key, cursor); } }.run(null); } @@ -1442,8 +1442,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public ScanResult execute() { - return connectionHandler.getConnection().zscan(key, cursor); + public ScanResult execute(Jedis connection) { + return connection.zscan(key, cursor); } }.run(null); } @@ -1454,8 +1454,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>>( connectionHandler, timeout, maxRedirections) { @Override - public ScanResult> execute() { - return connectionHandler.getConnection().hscan(key, cursor); + public ScanResult> execute(Jedis connection) { + return connection.hscan(key, cursor); } }.run(null); } @@ -1465,8 +1465,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public ScanResult execute() { - return connectionHandler.getConnection().sscan(key, cursor); + public ScanResult execute(Jedis connection) { + return connection.sscan(key, cursor); } }.run(null); } @@ -1476,8 +1476,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override - public ScanResult execute() { - return connectionHandler.getConnection().zscan(key, cursor); + public ScanResult execute(Jedis connection) { + return connection.zscan(key, cursor); } }.run(null); } diff --git a/src/main/java/redis/clients/jedis/JedisClusterCommand.java b/src/main/java/redis/clients/jedis/JedisClusterCommand.java index 41087a7..6e110bc 100644 --- a/src/main/java/redis/clients/jedis/JedisClusterCommand.java +++ b/src/main/java/redis/clients/jedis/JedisClusterCommand.java @@ -23,9 +23,10 @@ public abstract class JedisClusterCommand { this.redirections = maxRedirections; } - public abstract T execute(); + public abstract T execute(Jedis connection); public T run(String key) { + Jedis connection = null; try { if (key == null) { @@ -35,16 +36,20 @@ public abstract class JedisClusterCommand { throw new JedisClusterMaxRedirectionsException( "Too many Cluster redirections?"); } - connectionHandler.getConnectionFromSlot(JedisClusterCRC16 + connection = connectionHandler.getConnectionFromSlot(JedisClusterCRC16 .getSlot(key)); if (asking) { // TODO: Pipeline asking with the original command to make it // faster.... - connectionHandler.getConnection().asking(); + connection.asking(); } - return execute(); + return execute(connection); } catch (JedisRedirectionException jre) { return handleRedirection(jre, key); + } finally { + if (connection != null) { + connectionHandler.returnConnection(connection); + } } } diff --git a/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java index d30b5f7..28e22f9 100644 --- a/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java +++ b/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java @@ -11,6 +11,13 @@ public abstract class JedisClusterConnectionHandler { protected Map slots = new HashMap(); abstract Jedis getConnection(); + + protected void returnConnection(Jedis connection) { + nodes.get( + connection.getClient().getHost() + + connection.getClient().getPort()).returnResource( + connection); + } abstract Jedis getConnectionFromSlot(int slot); diff --git a/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java index 4aba893..76b52d0 100644 --- a/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java +++ b/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java @@ -5,25 +5,12 @@ import java.util.Set; public class JedisSlotBasedConnectionHandler extends JedisClusterConnectionHandler { - private Jedis currentConnection; - public JedisSlotBasedConnectionHandler(Set nodes) { super(nodes); } public Jedis getConnection() { - return currentConnection != null ? currentConnection - : getRandomConnection().getResource(); - } - - private void returnCurrentConnection() { - if (currentConnection != null) { - nodes.get( - currentConnection.getClient().getHost() - + currentConnection.getClient().getPort()) - .returnResource(currentConnection); - } - + return getRandomConnection().getResource(); } @Override @@ -34,13 +21,11 @@ public class JedisSlotBasedConnectionHandler extends @Override public Jedis getConnectionFromSlot(int slot) { - returnCurrentConnection(); JedisPool connectionPool = slots.get(slot); if (connectionPool == null) { connectionPool = getRandomConnection(); } - currentConnection = connectionPool.getResource(); - return connectionPool.getResource(); + return connectionPool.getResource(); } } From 3f8507a1171cb3b048c1fa72be3eb1c3bec15a36 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Thu, 20 Feb 2014 14:39:51 -0300 Subject: [PATCH 066/120] Remove unnecessary connection allocation --- .../redis/clients/jedis/JedisSlotBasedConnectionHandler.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java index 76b52d0..18aa424 100644 --- a/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java +++ b/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java @@ -16,7 +16,6 @@ public class JedisSlotBasedConnectionHandler extends @Override public void assignSlotToNode(int slot, HostAndPort targetNode) { super.assignSlotToNode(slot, targetNode); - getConnectionFromSlot(slot); } @Override @@ -25,7 +24,7 @@ public class JedisSlotBasedConnectionHandler extends if (connectionPool == null) { connectionPool = getRandomConnection(); } - return connectionPool.getResource(); + return connectionPool.getResource(); } } From 756113821f2599e72bfece457094bc51a1fcc7c2 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Thu, 20 Feb 2014 14:58:04 -0300 Subject: [PATCH 067/120] Make JedisClusterCRC16 multi-thread --- src/main/java/redis/clients/util/JedisClusterCRC16.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/redis/clients/util/JedisClusterCRC16.java b/src/main/java/redis/clients/util/JedisClusterCRC16.java index 3c5c9b5..270dbf0 100644 --- a/src/main/java/redis/clients/util/JedisClusterCRC16.java +++ b/src/main/java/redis/clients/util/JedisClusterCRC16.java @@ -2,7 +2,6 @@ package redis.clients.util; public class JedisClusterCRC16 { public final static int polynomial = 0x1021; // Represents x^16+x^12+x^5+1 - static int crc; public static int getSlot(String key) { @@ -17,7 +16,7 @@ public class JedisClusterCRC16 { } private static int getCRC16(String key) { - crc = 0x0000; + int crc = 0x0000; for (byte b : key.getBytes()) { for (int i = 0; i < 8; i++) { boolean bit = ((b >> (7 - i) & 1) == 1); From 670e019a8958acfecf9a2f7932cdf1ef58bcb0ed Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Sun, 23 Feb 2014 23:50:40 +0900 Subject: [PATCH 068/120] Implements Closeable to Pooled Jedis & ShardedJedis * Implement Closeable from Jedis, ShardedJedis with Pooled ** resources from JedisPool, JedisSentinelPool, ShardedJedis, ShardedJedisPool * Connection class : check whether Jedis Connection is broken ** when it's time to throw JedisConnectionException, mark Connection to broken --- .../java/redis/clients/jedis/BinaryJedis.java | 14 +-- .../java/redis/clients/jedis/Connection.java | 95 ++++++++++++------- src/main/java/redis/clients/jedis/Jedis.java | 39 ++++++-- .../java/redis/clients/jedis/JedisPool.java | 7 ++ .../clients/jedis/JedisSentinelPool.java | 27 ++++-- .../redis/clients/jedis/ShardedJedis.java | 50 +++++++++- .../redis/clients/jedis/ShardedJedisPool.java | 19 ++++ .../clients/jedis/tests/JedisPoolTest.java | 46 +++++++-- .../jedis/tests/JedisSentinelPoolTest.java | 23 +++++ .../jedis/tests/ShardedJedisPoolTest.java | 66 +++++++++++++ .../clients/jedis/tests/ShardedJedisTest.java | 21 ++++ 11 files changed, 338 insertions(+), 69 deletions(-) diff --git a/src/main/java/redis/clients/jedis/BinaryJedis.java b/src/main/java/redis/clients/jedis/BinaryJedis.java index eba466f..9095712 100644 --- a/src/main/java/redis/clients/jedis/BinaryJedis.java +++ b/src/main/java/redis/clients/jedis/BinaryJedis.java @@ -1707,9 +1707,9 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, public List multi(final TransactionBlock jedisTransaction) { List results = null; jedisTransaction.setClient(client); - client.multi(); - jedisTransaction.execute(); - results = jedisTransaction.exec(); + client.multi(); + jedisTransaction.execute(); + results = jedisTransaction.exec(); return results; } @@ -1729,8 +1729,10 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, } public void resetState() { - client.resetState(); - client.getAll(); + if (client.isConnected()) { + client.resetState(); + client.getAll(); + } } public String watch(final byte[]... keys) { @@ -1744,7 +1746,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, } @Override - public void close() { + public void close() { client.close(); } diff --git a/src/main/java/redis/clients/jedis/Connection.java b/src/main/java/redis/clients/jedis/Connection.java index e913d68..c50c706 100644 --- a/src/main/java/redis/clients/jedis/Connection.java +++ b/src/main/java/redis/clients/jedis/Connection.java @@ -11,7 +11,6 @@ import java.util.List; import redis.clients.jedis.Protocol.Command; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisDataException; -import redis.clients.jedis.exceptions.JedisException; import redis.clients.util.RedisInputStream; import redis.clients.util.RedisOutputStream; import redis.clients.util.SafeEncoder; @@ -25,6 +24,8 @@ public class Connection implements Closeable { private int pipelinedCommands = 0; private int timeout = Protocol.DEFAULT_TIMEOUT; + private boolean broken = false; + public Socket getSocket() { return socket; } @@ -45,7 +46,8 @@ public class Connection implements Closeable { socket.setKeepAlive(true); socket.setSoTimeout(0); } catch (SocketException ex) { - throw new JedisException(ex); + broken = true; + throw new JedisConnectionException(ex); } } @@ -54,7 +56,8 @@ public class Connection implements Closeable { socket.setSoTimeout(timeout); socket.setKeepAlive(false); } catch (SocketException ex) { - throw new JedisException(ex); + broken = true; + throw new JedisConnectionException(ex); } } @@ -63,14 +66,6 @@ public class Connection implements Closeable { this.host = host; } - protected void flush() { - try { - outputStream.flush(); - } catch (IOException e) { - throw new JedisConnectionException(e); - } - } - protected Connection sendCommand(final Command cmd, final String... args) { final byte[][] bargs = new byte[args.length][]; for (int i = 0; i < args.length; i++) { @@ -80,17 +75,29 @@ public class Connection implements Closeable { } protected Connection sendCommand(final Command cmd, final byte[]... args) { - connect(); - Protocol.sendCommand(outputStream, cmd, args); - pipelinedCommands++; - return this; + try { + connect(); + Protocol.sendCommand(outputStream, cmd, args); + pipelinedCommands++; + return this; + } catch (JedisConnectionException ex) { + // Any other exceptions related to connection? + broken = true; + throw ex; + } } protected Connection sendCommand(final Command cmd) { - connect(); - Protocol.sendCommand(outputStream, cmd, new byte[0][]); - pipelinedCommands++; - return this; + try { + connect(); + Protocol.sendCommand(outputStream, cmd, new byte[0][]); + pipelinedCommands++; + return this; + } catch (JedisConnectionException ex) { + // Any other exceptions related to connection? + broken = true; + throw ex; + } } public Connection(final String host, final int port) { @@ -139,6 +146,7 @@ public class Connection implements Closeable { outputStream = new RedisOutputStream(socket.getOutputStream()); inputStream = new RedisInputStream(socket.getInputStream()); } catch (IOException ex) { + broken = true; throw new JedisConnectionException(ex); } } @@ -147,7 +155,7 @@ public class Connection implements Closeable { @Override public void close() { disconnect(); - } + } public void disconnect() { if (isConnected()) { @@ -158,6 +166,7 @@ public class Connection implements Closeable { socket.close(); } } catch (IOException ex) { + broken = true; throw new JedisConnectionException(ex); } } @@ -172,7 +181,7 @@ public class Connection implements Closeable { protected String getStatusCodeReply() { flush(); pipelinedCommands--; - final byte[] resp = (byte[]) Protocol.read(inputStream); + final byte[] resp = (byte[]) readProtocolWithCheckingBroken(); if (null == resp) { return null; } else { @@ -192,13 +201,13 @@ public class Connection implements Closeable { public byte[] getBinaryBulkReply() { flush(); pipelinedCommands--; - return (byte[]) Protocol.read(inputStream); + return (byte[]) readProtocolWithCheckingBroken(); } public Long getIntegerReply() { flush(); pipelinedCommands--; - return (Long) Protocol.read(inputStream); + return (Long) readProtocolWithCheckingBroken(); } public List getMultiBulkReply() { @@ -209,29 +218,29 @@ public class Connection implements Closeable { public List getBinaryMultiBulkReply() { flush(); pipelinedCommands--; - return (List) Protocol.read(inputStream); + return (List) readProtocolWithCheckingBroken(); } public void resetPipelinedCount() { - pipelinedCommands = 0; + pipelinedCommands = 0; } @SuppressWarnings("unchecked") public List getRawObjectMultiBulkReply() { - return (List) Protocol.read(inputStream); + return (List) readProtocolWithCheckingBroken(); } public List getObjectMultiBulkReply() { - flush(); - pipelinedCommands--; - return getRawObjectMultiBulkReply(); + flush(); + pipelinedCommands--; + return getRawObjectMultiBulkReply(); } @SuppressWarnings("unchecked") public List getIntegerMultiBulkReply() { flush(); pipelinedCommands--; - return (List) Protocol.read(inputStream); + return (List) readProtocolWithCheckingBroken(); } public List getAll() { @@ -243,7 +252,7 @@ public class Connection implements Closeable { flush(); while (pipelinedCommands > except) { try { - all.add(Protocol.read(inputStream)); + all.add(readProtocolWithCheckingBroken()); } catch (JedisDataException e) { all.add(e); } @@ -255,6 +264,28 @@ public class Connection implements Closeable { public Object getOne() { flush(); pipelinedCommands--; - return Protocol.read(inputStream); + return readProtocolWithCheckingBroken(); + } + + public boolean isBroken() { + return broken; + } + + protected void flush() { + try { + outputStream.flush(); + } catch (IOException ex) { + broken = true; + throw new JedisConnectionException(ex); + } + } + + protected Object readProtocolWithCheckingBroken() { + try { + return Protocol.read(inputStream); + } catch (JedisConnectionException exc) { + broken = true; + throw exc; + } } } diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index 4961f42..a8aa286 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -12,12 +12,16 @@ import java.util.Map.Entry; import java.util.Set; import redis.clients.jedis.BinaryClient.LIST_POSITION; +import redis.clients.util.Pool; import redis.clients.util.SafeEncoder; import redis.clients.util.Slowlog; public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommands, AdvancedJedisCommands, ScriptingCommands, BasicCommands, ClusterCommands { + + protected Pool dataSource = null; + public Jedis(final String host) { super(host); } @@ -3256,11 +3260,11 @@ public class Jedis extends BinaryJedis implements JedisCommands, } return new ScanResult(newcursor, results); } - + public ScanResult scan(final String cursor) { return scan(cursor, new ScanParams()); } - + public ScanResult scan(final String cursor, final ScanParams params) { checkIsInMulti(); client.scan(cursor, params); @@ -3273,12 +3277,12 @@ public class Jedis extends BinaryJedis implements JedisCommands, } return new ScanResult(newcursor, results); } - + public ScanResult> hscan(final String key, final String cursor) { return hscan(key, cursor, new ScanParams()); } - + public ScanResult> hscan(final String key, final String cursor, final ScanParams params) { checkIsInMulti(); @@ -3291,15 +3295,15 @@ public class Jedis extends BinaryJedis implements JedisCommands, while (iterator.hasNext()) { results.add(new AbstractMap.SimpleEntry(SafeEncoder .encode(iterator.next()), SafeEncoder.encode(iterator - .next()))); + .next()))); } return new ScanResult>(newcursor, results); } - + public ScanResult sscan(final String key, final String cursor) { return sscan(key, cursor, new ScanParams()); } - + public ScanResult sscan(final String key, final String cursor, final ScanParams params) { checkIsInMulti(); @@ -3313,11 +3317,11 @@ public class Jedis extends BinaryJedis implements JedisCommands, } return new ScanResult(newcursor, results); } - + public ScanResult zscan(final String key, final String cursor) { return zscan(key, cursor, new ScanParams()); } - + public ScanResult zscan(final String key, final String cursor, final ScanParams params) { checkIsInMulti(); @@ -3412,4 +3416,21 @@ public class Jedis extends BinaryJedis implements JedisCommands, return BuilderFactory.STRING_MAP .build(client.getBinaryMultiBulkReply()); } + + @Override + public void close() { + if (dataSource != null) { + if (client.isBroken()) { + this.dataSource.returnBrokenResource(this); + } else { + this.dataSource.returnResource(this); + } + } else { + client.close(); + } + } + + public void setDataSource(Pool jedisPool) { + this.dataSource = jedisPool; + } } diff --git a/src/main/java/redis/clients/jedis/JedisPool.java b/src/main/java/redis/clients/jedis/JedisPool.java index 6b2c80c..3aaa6ff 100644 --- a/src/main/java/redis/clients/jedis/JedisPool.java +++ b/src/main/java/redis/clients/jedis/JedisPool.java @@ -79,6 +79,13 @@ public class JedisPool extends Pool { database, clientName)); } + @Override + public Jedis getResource() { + Jedis jedis = super.getResource(); + jedis.setDataSource(this); + return jedis; + } + public void returnBrokenResource(final Jedis resource) { returnBrokenResourceObject(resource); } diff --git a/src/main/java/redis/clients/jedis/JedisSentinelPool.java b/src/main/java/redis/clients/jedis/JedisSentinelPool.java index 4fe5433..be8bad1 100644 --- a/src/main/java/redis/clients/jedis/JedisSentinelPool.java +++ b/src/main/java/redis/clients/jedis/JedisSentinelPool.java @@ -74,15 +74,6 @@ public class JedisSentinelPool extends Pool { initPool(master); } - public void returnBrokenResource(final Jedis resource) { - returnBrokenResourceObject(resource); - } - - public void returnResource(final Jedis resource) { - resource.resetState(); - returnResourceObject(resource); - } - private volatile HostAndPort currentHostMaster; public void destroy() { @@ -171,6 +162,24 @@ public class JedisSentinelPool extends Pool { return new HostAndPort(host, port); } + @Override + public Jedis getResource() { + Jedis jedis = super.getResource(); + jedis.setDataSource(this); + return jedis; + } + + @Override + public void returnBrokenResource(final Jedis resource) { + returnBrokenResourceObject(resource); + } + + @Override + public void returnResource(final Jedis resource) { + resource.resetState(); + returnResourceObject(resource); + } + protected class JedisPubSubAdapter extends JedisPubSub { @Override public void onMessage(String channel, String message) { diff --git a/src/main/java/redis/clients/jedis/ShardedJedis.java b/src/main/java/redis/clients/jedis/ShardedJedis.java index 7235cfe..0ebc9f0 100644 --- a/src/main/java/redis/clients/jedis/ShardedJedis.java +++ b/src/main/java/redis/clients/jedis/ShardedJedis.java @@ -1,5 +1,6 @@ package redis.clients.jedis; +import java.io.Closeable; import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -8,8 +9,13 @@ import java.util.regex.Pattern; import redis.clients.jedis.BinaryClient.LIST_POSITION; import redis.clients.util.Hashing; +import redis.clients.util.Pool; + +public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, + Closeable { + + protected Pool dataSource = null; -public class ShardedJedis extends BinaryShardedJedis implements JedisCommands { public ShardedJedis(List shards) { super(shards); } @@ -555,19 +561,53 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands { Jedis j = getShard(key); return j.zscan(key, cursor); } - - public ScanResult> hscan(String key, final String cursor) { + + public ScanResult> hscan(String key, + final String cursor) { Jedis j = getShard(key); return j.hscan(key, cursor); } - + public ScanResult sscan(String key, final String cursor) { Jedis j = getShard(key); return j.sscan(key, cursor); } - + public ScanResult zscan(String key, final String cursor) { Jedis j = getShard(key); return j.zscan(key, cursor); } + + @Override + public void close() { + if (dataSource != null) { + boolean broken = false; + + for (Jedis jedis : getAllShards()) { + if (jedis.getClient().isBroken()) { + broken = true; + } + } + + if (broken) { + dataSource.returnBrokenResource(this); + } else { + this.resetState(); + dataSource.returnResource(this); + } + + } else { + disconnect(); + } + } + + public void setDataSource(Pool shardedJedisPool) { + this.dataSource = shardedJedisPool; + } + + public void resetState() { + for (Jedis jedis : getAllShards()) { + jedis.resetState(); + } + } } diff --git a/src/main/java/redis/clients/jedis/ShardedJedisPool.java b/src/main/java/redis/clients/jedis/ShardedJedisPool.java index dd56ac1..5cdfd06 100644 --- a/src/main/java/redis/clients/jedis/ShardedJedisPool.java +++ b/src/main/java/redis/clients/jedis/ShardedJedisPool.java @@ -31,6 +31,25 @@ public class ShardedJedisPool extends Pool { List shards, Hashing algo, Pattern keyTagPattern) { super(poolConfig, new ShardedJedisFactory(shards, algo, keyTagPattern)); } + + @Override + public ShardedJedis getResource() { + ShardedJedis jedis = super.getResource(); + jedis.setDataSource(this); + return jedis; + } + + @Override + public void returnBrokenResource(final ShardedJedis resource) { + returnBrokenResourceObject(resource); + } + + @Override + public void returnResource(final ShardedJedis resource) { + resource.resetState(); + returnResourceObject(resource); + } + /** * PoolableObjectFactory custom impl. diff --git a/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java b/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java index a501024..7e011c0 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java @@ -187,15 +187,45 @@ public class JedisPoolTest extends Assert { 2000, "foobared"); Jedis jedis = pool.getResource(); - jedis.set("hello", "jedis"); - Transaction t = jedis.multi(); - t.set("hello", "world"); - pool.returnResource(jedis); + try { + jedis.set("hello", "jedis"); + Transaction t = jedis.multi(); + t.set("hello", "world"); + } finally { + jedis.close(); + } Jedis jedis2 = pool.getResource(); - assertTrue(jedis == jedis2); - assertEquals("jedis", jedis2.get("hello")); - pool.returnResource(jedis2); + try { + assertTrue(jedis == jedis2); + assertEquals("jedis", jedis2.get("hello")); + } finally { + jedis2.close(); + } + pool.destroy(); } -} + + @Test + public void checkResourceIsCloseable() { + GenericObjectPoolConfig config = new GenericObjectPoolConfig(); + config.setMaxTotal(1); + config.setBlockWhenExhausted(false); + JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(), + 2000, "foobared"); + + Jedis jedis = pool.getResource(); + try { + jedis.set("hello", "jedis"); + } finally { + jedis.close(); + } + + Jedis jedis2 = pool.getResource(); + try { + assertEquals(jedis, jedis2); + } finally { + jedis2.close(); + } + } +} \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java index c8df9c5..46c37a8 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java @@ -79,6 +79,29 @@ public class JedisSentinelPoolTest extends JedisTestBase { pool.destroy(); } } + + @Test + public void checkResourceIsCloseable() { + GenericObjectPoolConfig config = new GenericObjectPoolConfig(); + config.setMaxTotal(1); + config.setBlockWhenExhausted(false); + JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels, + config, 1000, "foobared", 2); + + Jedis jedis = pool.getResource(); + try { + jedis.set("hello", "jedis"); + } finally { + jedis.close(); + } + + Jedis jedis2 = pool.getResource(); + try { + assertEquals(jedis, jedis2); + } finally { + jedis2.close(); + } + } private void forceFailover(JedisSentinelPool pool) throws InterruptedException { diff --git a/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolTest.java b/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolTest.java index ee7951b..b1350e9 100644 --- a/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolTest.java +++ b/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolTest.java @@ -14,6 +14,7 @@ import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisShardInfo; import redis.clients.jedis.ShardedJedis; +import redis.clients.jedis.ShardedJedisPipeline; import redis.clients.jedis.ShardedJedisPool; import redis.clients.jedis.exceptions.JedisConnectionException; @@ -233,4 +234,69 @@ public class ShardedJedisPoolTest extends Assert { assertEquals("PONG", jedis.ping()); assertEquals("bar", jedis.get("foo")); } + + @Test + public void returnResourceShouldResetState() throws URISyntaxException { + GenericObjectPoolConfig config = new GenericObjectPoolConfig(); + config.setMaxTotal(1); + config.setBlockWhenExhausted(false); + + List shards = new ArrayList(); + shards.add(new JedisShardInfo(new URI( + "redis://:foobared@localhost:6380"))); + shards.add(new JedisShardInfo(new URI( + "redis://:foobared@localhost:6379"))); + + ShardedJedisPool pool = new ShardedJedisPool(config, shards); + + ShardedJedis jedis = pool.getResource(); + jedis.set("pipelined", String.valueOf(0)); + jedis.set("pipelined2", String.valueOf(0)); + + ShardedJedisPipeline pipeline = jedis.pipelined(); + + pipeline.incr("pipelined"); + pipeline.incr("pipelined2"); + + jedis.resetState(); + + pipeline = jedis.pipelined(); + pipeline.incr("pipelined"); + pipeline.incr("pipelined2"); + List results = pipeline.syncAndReturnAll(); + + assertEquals(2, results.size()); + pool.returnResource(jedis); + pool.destroy(); + } + + @Test + public void checkResourceIsCloseable() throws URISyntaxException { + GenericObjectPoolConfig config = new GenericObjectPoolConfig(); + config.setMaxTotal(1); + config.setBlockWhenExhausted(false); + + List shards = new ArrayList(); + shards.add(new JedisShardInfo(new URI( + "redis://:foobared@localhost:6380"))); + shards.add(new JedisShardInfo(new URI( + "redis://:foobared@localhost:6379"))); + + ShardedJedisPool pool = new ShardedJedisPool(config, shards); + + ShardedJedis jedis = pool.getResource(); + try { + jedis.set("hello", "jedis"); + } finally { + jedis.close(); + } + + ShardedJedis jedis2 = pool.getResource(); + try { + assertEquals(jedis, jedis2); + } finally { + jedis2.close(); + } + } + } diff --git a/src/test/java/redis/clients/jedis/tests/ShardedJedisTest.java b/src/test/java/redis/clients/jedis/tests/ShardedJedisTest.java index 5a71391..2413952 100644 --- a/src/test/java/redis/clients/jedis/tests/ShardedJedisTest.java +++ b/src/test/java/redis/clients/jedis/tests/ShardedJedisTest.java @@ -302,4 +302,25 @@ public class ShardedJedisTest extends Assert { assertEquals(jedisShardInfo.getName(), jedisShardInfo2.getName()); } } + + @Test + public void checkCloseable() { + List shards = new ArrayList(); + shards.add(new JedisShardInfo(redis1.getHost(), redis1.getPort())); + shards.add(new JedisShardInfo(redis2.getHost(), redis2.getPort())); + shards.get(0).setPassword("foobared"); + shards.get(1).setPassword("foobared"); + + ShardedJedis jedisShard = new ShardedJedis(shards); + try { + jedisShard.set("shard_closeable", "true"); + } finally { + jedisShard.close(); + } + + for (Jedis jedis : jedisShard.getAllShards()) { + assertTrue(!jedis.isConnected()); + } + } + } \ No newline at end of file From 882d662470351d08d106006821c837d76b5ddaac Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Tue, 25 Feb 2014 18:29:09 +0900 Subject: [PATCH 069/120] Make Jedis Cluster more likely to antirez's redis-rb-cluster JedisClusterCommand * improvements on connection error handling ** if based on slot connection throws connection related exception, retry to random node ** if we retry with random node, but all nodes are unreachable, throw JedisConnectionException without retry ** try to release connection whether connection is broken or not * bug fix : if asking flag is on, and success this time, set asking flag to off JedisClusterConnectionHandler * have flexibility on initializing slots cache ** allow some nodes connection failure - skip ** if current node is success initializing slots cache, skip other nodes ** if current node failed to initialize slots cache, discard all discovered nodes and slots * set nodes if node does not exist in nodes ** it restricts JedisPool to replace - prevent IllegalStateException : Returned object not currently part of this pool JedisSlotBasedConnectionGuaranteedConnectionHandler * getConnection (random connection) ** check all connections by random sequence ** always return valid connection (able to ping-pong) ** throw exception if all connections are invalid * some refactoring --- .../redis/clients/jedis/JedisCluster.java | 2 +- .../clients/jedis/JedisClusterCommand.java | 87 ++++++++++++++----- .../jedis/JedisClusterConnectionHandler.java | 80 +++++++++++++---- ...ConnectionGuaranteedConnectionHandler.java | 68 +++++++++++++++ 4 files changed, 196 insertions(+), 41 deletions(-) create mode 100644 src/main/java/redis/clients/jedis/JedisSlotBasedConnectionGuaranteedConnectionHandler.java diff --git a/src/main/java/redis/clients/jedis/JedisCluster.java b/src/main/java/redis/clients/jedis/JedisCluster.java index 1f645ea..afa0109 100644 --- a/src/main/java/redis/clients/jedis/JedisCluster.java +++ b/src/main/java/redis/clients/jedis/JedisCluster.java @@ -27,7 +27,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { public JedisCluster(Set jedisClusterNode, int timeout, int maxRedirections) { - this.connectionHandler = new JedisSlotBasedConnectionHandler( + this.connectionHandler = new JedisSlotBasedConnectionGuaranteedConnectionHandler( jedisClusterNode); this.timeout = timeout; this.maxRedirections = maxRedirections; diff --git a/src/main/java/redis/clients/jedis/JedisClusterCommand.java b/src/main/java/redis/clients/jedis/JedisClusterCommand.java index 6e110bc..c1be912 100644 --- a/src/main/java/redis/clients/jedis/JedisClusterCommand.java +++ b/src/main/java/redis/clients/jedis/JedisClusterCommand.java @@ -3,19 +3,18 @@ package redis.clients.jedis; import redis.clients.jedis.exceptions.JedisAskDataException; import redis.clients.jedis.exceptions.JedisClusterException; import redis.clients.jedis.exceptions.JedisClusterMaxRedirectionsException; +import redis.clients.jedis.exceptions.JedisConnectionException; +import redis.clients.jedis.exceptions.JedisException; +import redis.clients.jedis.exceptions.JedisMovedDataException; import redis.clients.jedis.exceptions.JedisRedirectionException; import redis.clients.util.JedisClusterCRC16; public abstract class JedisClusterCommand { - private boolean asking = false; - private JedisClusterConnectionHandler connectionHandler; private int commandTimeout; private int redirections; - // private boolean asking = false; - public JedisClusterCommand(JedisClusterConnectionHandler connectionHandler, int timeout, int maxRedirections) { this.connectionHandler = connectionHandler; @@ -26,40 +25,80 @@ public abstract class JedisClusterCommand { public abstract T execute(Jedis connection); public T run(String key) { + if (key == null) { + throw new JedisClusterException( + "No way to dispatch this command to Redis Cluster."); + } + + return runWithRetries(key, this.redirections, false, false); + } + + private T runWithRetries(String key, int redirections, + boolean tryRandomNode, boolean asking) { + if (redirections <= 0) { + throw new JedisClusterMaxRedirectionsException( + "Too many Cluster redirections?"); + } + Jedis connection = null; try { - - if (key == null) { - throw new JedisClusterException( - "No way to dispatch this command to Redis Cluster."); - } else if (redirections == 0) { - throw new JedisClusterMaxRedirectionsException( - "Too many Cluster redirections?"); + if (tryRandomNode) { + connection = connectionHandler.getConnection(); + } else { + connection = connectionHandler + .getConnectionFromSlot(JedisClusterCRC16.getSlot(key)); } - connection = connectionHandler.getConnectionFromSlot(JedisClusterCRC16 - .getSlot(key)); + if (asking) { // TODO: Pipeline asking with the original command to make it // faster.... connection.asking(); + + // if asking success, reset asking flag + asking = false; } + return execute(connection); + } catch (JedisConnectionException jce) { + if (tryRandomNode) { + // maybe all connection is down + throw jce; + } + + releaseConnection(connection, true); + connection = null; + + // retry with random connection + return runWithRetries(key, redirections--, true, asking); } catch (JedisRedirectionException jre) { - return handleRedirection(jre, key); + if (jre instanceof JedisAskDataException) { + asking = true; + } else if (jre instanceof JedisMovedDataException) { + // TODO : In antirez's redis-rb-cluster implementation, + // it rebuilds cluster's slot and node cache + } + + this.connectionHandler.assignSlotToNode(jre.getSlot(), + jre.getTargetNode()); + + releaseConnection(connection, false); + connection = null; + + return runWithRetries(key, redirections - 1, false, asking); } finally { - if (connection != null) { + releaseConnection(connection, false); + } + + } + + private void releaseConnection(Jedis connection, boolean broken) { + if (connection != null) { + if (broken) { + connectionHandler.returnBrokenConnection(connection); + } else { connectionHandler.returnConnection(connection); } } } - private T handleRedirection(JedisRedirectionException jre, String key) { - if (jre instanceof JedisAskDataException) { - asking = true; - } - redirections--; - this.connectionHandler.assignSlotToNode(jre.getSlot(), - jre.getTargetNode()); - return run(key); - } } \ No newline at end of file diff --git a/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java index 28e22f9..94f4c75 100644 --- a/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java +++ b/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java @@ -5,17 +5,22 @@ import java.util.Map; import java.util.Random; import java.util.Set; +import redis.clients.jedis.exceptions.JedisConnectionException; + public abstract class JedisClusterConnectionHandler { protected Map nodes = new HashMap(); protected Map slots = new HashMap(); abstract Jedis getConnection(); - + protected void returnConnection(Jedis connection) { - nodes.get( - connection.getClient().getHost() - + connection.getClient().getPort()).returnResource( + nodes.get(getNodeKey(connection.getClient())) + .returnResource(connection); + } + + public void returnBrokenConnection(Jedis connection) { + nodes.get(getNodeKey(connection.getClient())).returnBrokenResource( connection); } @@ -29,29 +34,57 @@ public abstract class JedisClusterConnectionHandler { return nodes; } - private void initializeSlotsCache(Set nodes) { - for (HostAndPort hostAndPort : nodes) { + private void initializeSlotsCache(Set startNodes) { + for (HostAndPort hostAndPort : startNodes) { JedisPool jp = new JedisPool(hostAndPort.getHost(), hostAndPort.getPort()); - this.nodes.put(hostAndPort.getHost() + hostAndPort.getPort(), jp); - Jedis jedis = jp.getResource(); + + this.nodes.clear(); + this.slots.clear(); + + Jedis jedis = null; try { + jedis = jp.getResource(); discoverClusterNodesAndSlots(jedis); + break; + } catch (JedisConnectionException e) { + if (jedis != null) { + jp.returnBrokenResource(jedis); + jedis = null; + } + + // try next nodes } finally { - jp.returnResource(jedis); + if (jedis != null) { + jp.returnResource(jedis); + } } } - } + for (HostAndPort node : startNodes) { + setNodeIfNotExist(node); + } + } + private void discoverClusterNodesAndSlots(Jedis jedis) { String localNodes = jedis.clusterNodes(); for (String nodeInfo : localNodes.split("\n")) { HostAndPort node = getHostAndPortFromNodeLine(nodeInfo, jedis); - JedisPool nodePool = new JedisPool(node.getHost(), node.getPort()); - this.nodes.put(node.getHost() + node.getPort(), nodePool); + setNodeIfNotExist(node); + + JedisPool nodePool = nodes.get(getNodeKey(node)); populateNodeSlots(nodeInfo, nodePool); } } + + private void setNodeIfNotExist(HostAndPort node) { + String nodeKey = getNodeKey(node); + if (nodes.containsKey(nodeKey)) + return; + + JedisPool nodePool = new JedisPool(node.getHost(), node.getPort()); + nodes.put(nodeKey, nodePool); + } private void populateNodeSlots(String nodeInfo, JedisPool nodePool) { String[] nodeInfoArray = nodeInfo.split(" "); @@ -74,7 +107,8 @@ public abstract class JedisClusterConnectionHandler { } } - private HostAndPort getHostAndPortFromNodeLine(String nodeInfo, Jedis currentConnection) { + private HostAndPort getHostAndPortFromNodeLine(String nodeInfo, + Jedis currentConnection) { String stringHostAndPort = nodeInfo.split(" ", 3)[1]; if (":0".equals(stringHostAndPort)) { return new HostAndPort(currentConnection.getClient().getHost(), @@ -86,9 +120,16 @@ public abstract class JedisClusterConnectionHandler { } public void assignSlotToNode(int slot, HostAndPort targetNode) { - JedisPool targetPool = nodes.get(targetNode.getHost() - + targetNode.getPort()); - slots.put(slot, targetPool); + JedisPool targetPool = nodes.get(getNodeKey(targetNode)); + + if (targetPool != null) { + slots.put(slot, targetPool); + } else { + setNodeIfNotExist(targetNode); + + targetPool = nodes.get(getNodeKey(targetNode)); + slots.put(slot, targetPool); + } } protected JedisPool getRandomConnection() { @@ -96,4 +137,11 @@ public abstract class JedisClusterConnectionHandler { return (JedisPool) (nodeArray[new Random().nextInt(nodeArray.length)]); } + protected String getNodeKey(HostAndPort hnp) { + return hnp.getHost() + ":" + hnp.getPort(); + } + + protected String getNodeKey(Client client) { + return client.getHost() + ":" + client.getPort(); + } } diff --git a/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionGuaranteedConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionGuaranteedConnectionHandler.java new file mode 100644 index 0000000..0fe2cec --- /dev/null +++ b/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionGuaranteedConnectionHandler.java @@ -0,0 +1,68 @@ +package redis.clients.jedis; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import redis.clients.jedis.exceptions.JedisConnectionException; + +public class JedisSlotBasedConnectionGuaranteedConnectionHandler extends + JedisSlotBasedConnectionHandler { + + public JedisSlotBasedConnectionGuaranteedConnectionHandler( + Set nodes) { + super(nodes); + } + + public Jedis getConnection() { + // In antirez's redis-rb-cluster implementation, + // getRandomConnection always return valid connection (able to ping-pong) + // or exception if all connections are invalid + + List pools = getShuffledNodesPool(); + + for (JedisPool pool : pools) { + Jedis jedis = null; + try { + jedis = pool.getResource(); + + if (jedis == null) { + continue; + } + + String result = jedis.ping(); + + if (result.equalsIgnoreCase("pong")) + return jedis; + + pool.returnBrokenResource(jedis); + } catch (JedisConnectionException ex) { + if (jedis != null) { + pool.returnBrokenResource(jedis); + } + } + } + + throw new JedisConnectionException("no reachable node in cluster"); + } + + @Override + public Jedis getConnectionFromSlot(int slot) { + JedisPool connectionPool = slots.get(slot); + if (connectionPool != null) { + // It can't guaranteed to get valid connection because of node assignment + return connectionPool.getResource(); + } else { + return getConnection(); + } + } + + private List getShuffledNodesPool() { + List pools = new ArrayList(); + pools.addAll(nodes.values()); + Collections.shuffle(pools); + return pools; + } + +} From fcea0fe0feca0d2b4160a377ecf79c90c9dcda7d Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Wed, 26 Feb 2014 07:54:08 +0900 Subject: [PATCH 070/120] CLUSTERDOWN : JedisClusterException --- src/main/java/redis/clients/jedis/Protocol.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/redis/clients/jedis/Protocol.java b/src/main/java/redis/clients/jedis/Protocol.java index a753f96..681bc56 100644 --- a/src/main/java/redis/clients/jedis/Protocol.java +++ b/src/main/java/redis/clients/jedis/Protocol.java @@ -5,6 +5,7 @@ import java.util.ArrayList; import java.util.List; import redis.clients.jedis.exceptions.JedisAskDataException; +import redis.clients.jedis.exceptions.JedisClusterException; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.exceptions.JedisMovedDataException; @@ -16,6 +17,7 @@ public final class Protocol { private static final String ASK_RESPONSE = "ASK"; private static final String MOVED_RESPONSE = "MOVED"; + private static final String CLUSTERDOWN_RESPONSE = "CLUSTERDOWN"; public static final int DEFAULT_PORT = 6379; public static final int DEFAULT_SENTINEL_PORT = 26379; public static final int DEFAULT_TIMEOUT = 2000; @@ -96,6 +98,8 @@ public final class Protocol { throw new JedisAskDataException(message, new HostAndPort( askInfo[1], Integer.valueOf(askInfo[2])), Integer.valueOf(askInfo[0])); + } else if (message.startsWith(CLUSTERDOWN_RESPONSE)) { + throw new JedisClusterException(message); } throw new JedisDataException(message); } From ddb1870a5f6781f909d9cd803bc0ac17e8846457 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Thu, 27 Feb 2014 10:48:46 -0300 Subject: [PATCH 071/120] Fix bug in JedisCluster del command. Fix #568 --- src/main/java/redis/clients/jedis/JedisCluster.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/redis/clients/jedis/JedisCluster.java b/src/main/java/redis/clients/jedis/JedisCluster.java index 1f645ea..121bde8 100644 --- a/src/main/java/redis/clients/jedis/JedisCluster.java +++ b/src/main/java/redis/clients/jedis/JedisCluster.java @@ -1129,7 +1129,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { public Long execute(Jedis connection) { return connection.del(key); } - }.run(null); + }.run(key); } @Override From 46eef9530b4a6f493ed1ab1e677213467461bfbe Mon Sep 17 00:00:00 2001 From: Henning Schmiedehausen Date: Thu, 27 Feb 2014 10:58:46 -0800 Subject: [PATCH 072/120] add a number of null check to return methods. This allows calling these methods on error cleanup paths without having to surround them with if checks all the time. --- src/main/java/redis/clients/jedis/JedisPool.java | 10 +++++++--- src/main/java/redis/clients/util/Pool.java | 10 +++++++--- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/main/java/redis/clients/jedis/JedisPool.java b/src/main/java/redis/clients/jedis/JedisPool.java index 6b2c80c..8e34d19 100644 --- a/src/main/java/redis/clients/jedis/JedisPool.java +++ b/src/main/java/redis/clients/jedis/JedisPool.java @@ -80,11 +80,15 @@ public class JedisPool extends Pool { } public void returnBrokenResource(final Jedis resource) { - returnBrokenResourceObject(resource); + if (resource != null) { + returnBrokenResourceObject(resource); + } } public void returnResource(final Jedis resource) { - resource.resetState(); - returnResourceObject(resource); + if (resource != null) { + resource.resetState(); + returnResourceObject(resource); + } } } diff --git a/src/main/java/redis/clients/util/Pool.java b/src/main/java/redis/clients/util/Pool.java index 09d8ebb..2b0d91f 100644 --- a/src/main/java/redis/clients/util/Pool.java +++ b/src/main/java/redis/clients/util/Pool.java @@ -54,11 +54,15 @@ public abstract class Pool { } public void returnBrokenResource(final T resource) { - returnBrokenResourceObject(resource); + if (resource != null) { + returnBrokenResourceObject(resource); + } } public void returnResource(final T resource) { - returnResourceObject(resource); + if (resource != null) { + returnResourceObject(resource); + } } public void destroy() { @@ -81,4 +85,4 @@ public abstract class Pool { throw new JedisException("Could not destroy the pool", e); } } -} \ No newline at end of file +} From b2eb5d6d1c1e15c32bb702bf60b638044f79e510 Mon Sep 17 00:00:00 2001 From: Roland von Herget Date: Fri, 28 Feb 2014 14:36:53 +0100 Subject: [PATCH 073/120] add a returnBrokenResource method, this way we can throw away broken ShardedJedis objects (e.g. due to timeouts on one shard) --- src/main/java/redis/clients/jedis/ShardedJedisPool.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/redis/clients/jedis/ShardedJedisPool.java b/src/main/java/redis/clients/jedis/ShardedJedisPool.java index dd56ac1..7816c1e 100644 --- a/src/main/java/redis/clients/jedis/ShardedJedisPool.java +++ b/src/main/java/redis/clients/jedis/ShardedJedisPool.java @@ -32,6 +32,10 @@ public class ShardedJedisPool extends Pool { super(poolConfig, new ShardedJedisFactory(shards, algo, keyTagPattern)); } + public void returnBrokenResource(final ShardedJedis resource) { + returnBrokenResourceObject(resource); + } + /** * PoolableObjectFactory custom impl. */ From 4e78b811be01b3b859433fa173c2e7ba305518bc Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Mon, 3 Mar 2014 18:54:24 -0300 Subject: [PATCH 074/120] Merge JedisSlotBasedConnectionGuaranteedConnectionHandler to JedisSlotBasedConnectionHandler --- .../redis/clients/jedis/JedisCluster.java | 2 +- ...ConnectionGuaranteedConnectionHandler.java | 68 ------------------- .../JedisSlotBasedConnectionHandler.java | 50 ++++++++++++-- 3 files changed, 47 insertions(+), 73 deletions(-) delete mode 100644 src/main/java/redis/clients/jedis/JedisSlotBasedConnectionGuaranteedConnectionHandler.java diff --git a/src/main/java/redis/clients/jedis/JedisCluster.java b/src/main/java/redis/clients/jedis/JedisCluster.java index c1a34ce..121bde8 100644 --- a/src/main/java/redis/clients/jedis/JedisCluster.java +++ b/src/main/java/redis/clients/jedis/JedisCluster.java @@ -27,7 +27,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { public JedisCluster(Set jedisClusterNode, int timeout, int maxRedirections) { - this.connectionHandler = new JedisSlotBasedConnectionGuaranteedConnectionHandler( + this.connectionHandler = new JedisSlotBasedConnectionHandler( jedisClusterNode); this.timeout = timeout; this.maxRedirections = maxRedirections; diff --git a/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionGuaranteedConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionGuaranteedConnectionHandler.java deleted file mode 100644 index 0fe2cec..0000000 --- a/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionGuaranteedConnectionHandler.java +++ /dev/null @@ -1,68 +0,0 @@ -package redis.clients.jedis; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Set; - -import redis.clients.jedis.exceptions.JedisConnectionException; - -public class JedisSlotBasedConnectionGuaranteedConnectionHandler extends - JedisSlotBasedConnectionHandler { - - public JedisSlotBasedConnectionGuaranteedConnectionHandler( - Set nodes) { - super(nodes); - } - - public Jedis getConnection() { - // In antirez's redis-rb-cluster implementation, - // getRandomConnection always return valid connection (able to ping-pong) - // or exception if all connections are invalid - - List pools = getShuffledNodesPool(); - - for (JedisPool pool : pools) { - Jedis jedis = null; - try { - jedis = pool.getResource(); - - if (jedis == null) { - continue; - } - - String result = jedis.ping(); - - if (result.equalsIgnoreCase("pong")) - return jedis; - - pool.returnBrokenResource(jedis); - } catch (JedisConnectionException ex) { - if (jedis != null) { - pool.returnBrokenResource(jedis); - } - } - } - - throw new JedisConnectionException("no reachable node in cluster"); - } - - @Override - public Jedis getConnectionFromSlot(int slot) { - JedisPool connectionPool = slots.get(slot); - if (connectionPool != null) { - // It can't guaranteed to get valid connection because of node assignment - return connectionPool.getResource(); - } else { - return getConnection(); - } - } - - private List getShuffledNodesPool() { - List pools = new ArrayList(); - pools.addAll(nodes.values()); - Collections.shuffle(pools); - return pools; - } - -} diff --git a/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java index 18aa424..4cd4fc7 100644 --- a/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java +++ b/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java @@ -1,7 +1,12 @@ package redis.clients.jedis; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import java.util.Set; +import redis.clients.jedis.exceptions.JedisConnectionException; + public class JedisSlotBasedConnectionHandler extends JedisClusterConnectionHandler { @@ -10,7 +15,35 @@ public class JedisSlotBasedConnectionHandler extends } public Jedis getConnection() { - return getRandomConnection().getResource(); + // In antirez's redis-rb-cluster implementation, + // getRandomConnection always return valid connection (able to ping-pong) + // or exception if all connections are invalid + + List pools = getShuffledNodesPool(); + + for (JedisPool pool : pools) { + Jedis jedis = null; + try { + jedis = pool.getResource(); + + if (jedis == null) { + continue; + } + + String result = jedis.ping(); + + if (result.equalsIgnoreCase("pong")) + return jedis; + + pool.returnBrokenResource(jedis); + } catch (JedisConnectionException ex) { + if (jedis != null) { + pool.returnBrokenResource(jedis); + } + } + } + + throw new JedisConnectionException("no reachable node in cluster"); } @Override @@ -21,10 +54,19 @@ public class JedisSlotBasedConnectionHandler extends @Override public Jedis getConnectionFromSlot(int slot) { JedisPool connectionPool = slots.get(slot); - if (connectionPool == null) { - connectionPool = getRandomConnection(); + if (connectionPool != null) { + // It can't guaranteed to get valid connection because of node assignment + return connectionPool.getResource(); + } else { + return getConnection(); } - return connectionPool.getResource(); + } + + private List getShuffledNodesPool() { + List pools = new ArrayList(); + pools.addAll(nodes.values()); + Collections.shuffle(pools); + return pools; } } From 0cd32a61037eaaef58b7f6a64b38b0f408b5505b Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Tue, 4 Mar 2014 23:54:44 +0900 Subject: [PATCH 075/120] Expose *SCAN commands to BinaryJedis * method signatures are a bit similar to Jedis's *SCAN ** but it takes parameters to byte[] instead of String * ScanParams : allow match pattern with byte[] * ScanResult : add method to get cursor with byte[] type * *SCAN for BinaryJedis unit tests included --- .../java/redis/clients/jedis/BinaryJedis.java | 68 +++++++++++++++++++ .../java/redis/clients/jedis/ScanParams.java | 6 ++ .../java/redis/clients/jedis/ScanResult.java | 11 +++ .../commands/AllKindOfValuesCommandsTest.java | 34 +++++++++- .../tests/commands/HashesCommandsTest.java | 43 +++++++++++- .../jedis/tests/commands/SetCommandsTest.java | 33 +++++++++ .../tests/commands/SortedSetCommandsTest.java | 40 +++++++++++ 7 files changed, 233 insertions(+), 2 deletions(-) diff --git a/src/main/java/redis/clients/jedis/BinaryJedis.java b/src/main/java/redis/clients/jedis/BinaryJedis.java index eba466f..a2cf153 100644 --- a/src/main/java/redis/clients/jedis/BinaryJedis.java +++ b/src/main/java/redis/clients/jedis/BinaryJedis.java @@ -4,6 +4,7 @@ import static redis.clients.jedis.Protocol.toByteArray; import java.io.Closeable; import java.net.URI; +import java.util.AbstractMap; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; @@ -3417,4 +3418,71 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, return client.getIntegerReply(); } + public ScanResult scan(final byte[] cursor) { + return scan(cursor, new ScanParams()); + } + + public ScanResult scan(final byte[] cursor, final ScanParams params) { + checkIsInMulti(); + client.scan(cursor, params); + List result = client.getObjectMultiBulkReply(); + byte[] newcursor = (byte[]) result.get(0); + List rawResults = (List) result.get(1); + return new ScanResult(newcursor, rawResults); + } + + public ScanResult> hscan(final byte[] key, + final byte[] cursor) { + return hscan(key, cursor, new ScanParams()); + } + + public ScanResult> hscan(final byte[] key, + final byte[] cursor, final ScanParams params) { + checkIsInMulti(); + client.hscan(key, cursor, params); + List result = client.getObjectMultiBulkReply(); + byte[] newcursor = (byte[]) result.get(0); + List> results = new ArrayList>(); + List rawResults = (List) result.get(1); + Iterator iterator = rawResults.iterator(); + while (iterator.hasNext()) { + results.add(new AbstractMap.SimpleEntry(iterator.next(), + iterator.next())); + } + return new ScanResult>(newcursor, results); + } + + public ScanResult sscan(final byte[] key, final byte[] cursor) { + return sscan(key, cursor, new ScanParams()); + } + + public ScanResult sscan(final byte[] key, final byte[] cursor, + final ScanParams params) { + checkIsInMulti(); + client.sscan(key, cursor, params); + List result = client.getObjectMultiBulkReply(); + byte[] newcursor = (byte[]) result.get(0); + List rawResults = (List) result.get(1); + return new ScanResult(newcursor, rawResults); + } + + public ScanResult zscan(final byte[] key, final byte[] cursor) { + return zscan(key, cursor, new ScanParams()); + } + + public ScanResult zscan(final byte[] key, final byte[] cursor, + final ScanParams params) { + checkIsInMulti(); + client.zscan(key, cursor, params); + List result = client.getObjectMultiBulkReply(); + byte[] newcursor = (byte[]) result.get(0); + List results = new ArrayList(); + List rawResults = (List) result.get(1); + Iterator iterator = rawResults.iterator(); + while (iterator.hasNext()) { + results.add(new Tuple(iterator.next(), Double + .valueOf(SafeEncoder.encode(iterator.next())))); + } + return new ScanResult(newcursor, results); + } } diff --git a/src/main/java/redis/clients/jedis/ScanParams.java b/src/main/java/redis/clients/jedis/ScanParams.java index 980bb13..49317b8 100644 --- a/src/main/java/redis/clients/jedis/ScanParams.java +++ b/src/main/java/redis/clients/jedis/ScanParams.java @@ -13,7 +13,13 @@ import redis.clients.util.SafeEncoder; public class ScanParams { private List params = new ArrayList(); public final static String SCAN_POINTER_START = String.valueOf(0); + public final static byte[] SCAN_POINTER_START_BINARY = SafeEncoder.encode(SCAN_POINTER_START); + public void match(final byte[] pattern) { + params.add(MATCH.raw); + params.add(pattern); + } + public void match(final String pattern) { params.add(MATCH.raw); params.add(SafeEncoder.encode(pattern)); diff --git a/src/main/java/redis/clients/jedis/ScanResult.java b/src/main/java/redis/clients/jedis/ScanResult.java index 9afe27d..bf1bbd4 100644 --- a/src/main/java/redis/clients/jedis/ScanResult.java +++ b/src/main/java/redis/clients/jedis/ScanResult.java @@ -2,6 +2,8 @@ package redis.clients.jedis; import java.util.List; +import redis.clients.util.SafeEncoder; + public class ScanResult { private String cursor; private List results; @@ -17,6 +19,11 @@ public class ScanResult { this.results = results; } + public ScanResult(byte[] cursor, List results) { + this.cursor = SafeEncoder.encode(cursor); + this.results = results; + } + public ScanResult(String cursor, List results) { this.cursor = cursor; this.results = results; @@ -40,6 +47,10 @@ public class ScanResult { return cursor; } + public byte[] getBinaryCursor() { + return SafeEncoder.encode(cursor); + } + public List getResult() { return results; } diff --git a/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java index 057537c..c0a9670 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java @@ -11,6 +11,7 @@ import redis.clients.jedis.ScanResult; import redis.clients.jedis.exceptions.JedisDataException; 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 { final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; @@ -515,8 +516,14 @@ public class AllKindOfValuesCommandsTest extends JedisCommandTestBase { assertEquals(SCAN_POINTER_START, result.getStringCursor()); assertFalse(result.getResult().isEmpty()); + + // binary + ScanResult bResult = jedis.scan(SCAN_POINTER_START_BINARY); + + assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getBinaryCursor()); + assertFalse(bResult.getResult().isEmpty()); } - + @Test public void scanMatch() { ScanParams params = new ScanParams(); @@ -529,6 +536,19 @@ public class AllKindOfValuesCommandsTest extends JedisCommandTestBase { assertEquals(SCAN_POINTER_START, result.getStringCursor()); assertFalse(result.getResult().isEmpty()); + + // binary + params = new ScanParams(); + params.match(bfoostar); + + jedis.set(bfoo1, bbar); + jedis.set(bfoo2, bbar); + jedis.set(bfoo3, bbar); + + ScanResult bResult = jedis.scan(SCAN_POINTER_START_BINARY, params); + + assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getBinaryCursor()); + assertFalse(bResult.getResult().isEmpty()); } @Test @@ -543,5 +563,17 @@ public class AllKindOfValuesCommandsTest extends JedisCommandTestBase { ScanResult result = jedis.scan(SCAN_POINTER_START, params); assertFalse(result.getResult().isEmpty()); + + // binary + params = new ScanParams(); + params.count(2); + + jedis.set(bfoo1, bbar); + jedis.set(bfoo2, bbar); + jedis.set(bfoo3, bbar); + + ScanResult bResult = jedis.scan(SCAN_POINTER_START_BINARY, params); + + assertFalse(bResult.getResult().isEmpty()); } } diff --git a/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java index 5f9ac4e..8883f1f 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java @@ -13,12 +13,18 @@ import org.junit.Test; import redis.clients.jedis.ScanParams; 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 { final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; final byte[] bcar = { 0x09, 0x0A, 0x0B, 0x0C }; - + + final byte[] bbar1 = { 0x05, 0x06, 0x07, 0x08, 0x0A }; + final byte[] bbar2 = { 0x05, 0x06, 0x07, 0x08, 0x0B }; + final byte[] bbar3 = { 0x05, 0x06, 0x07, 0x08, 0x0C }; + final byte[] bbarstar = { 0x05, 0x06, 0x07, 0x08, '*' }; + @Test public void hset() { long status = jedis.hset("foo", "bar", "car"); @@ -300,6 +306,14 @@ public class HashesCommandsTest extends JedisCommandTestBase { assertEquals(SCAN_POINTER_START, result.getStringCursor()); assertFalse(result.getResult().isEmpty()); + + // binary + jedis.hset(bfoo, bbar, bcar); + + ScanResult> bResult = jedis.hscan(bfoo, SCAN_POINTER_START_BINARY); + + assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getBinaryCursor()); + assertFalse(bResult.getResult().isEmpty()); } @Test @@ -315,6 +329,20 @@ public class HashesCommandsTest extends JedisCommandTestBase { assertEquals(SCAN_POINTER_START, result.getStringCursor()); assertFalse(result.getResult().isEmpty()); + + // binary + params = new ScanParams(); + params.match(bbarstar); + + jedis.hset(bfoo, bbar, bcar); + jedis.hset(bfoo, bbar1, bcar); + jedis.hset(bfoo, bbar2, bcar); + jedis.hset(bfoo, bbar3, bcar); + + ScanResult> bResult = jedis.hscan(bfoo, SCAN_POINTER_START_BINARY, params); + + assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getBinaryCursor()); + assertFalse(bResult.getResult().isEmpty()); } @Test @@ -330,5 +358,18 @@ public class HashesCommandsTest extends JedisCommandTestBase { SCAN_POINTER_START, params); assertFalse(result.getResult().isEmpty()); + + // binary + params = new ScanParams(); + params.count(2); + + jedis.hset(bfoo, bbar, bcar); + jedis.hset(bfoo, bbar1, bcar); + jedis.hset(bfoo, bbar2, bcar); + jedis.hset(bfoo, bbar3, bcar); + + ScanResult> bResult = jedis.hscan(bfoo, SCAN_POINTER_START_BINARY, params); + + assertFalse(bResult.getResult().isEmpty()); } } diff --git a/src/test/java/redis/clients/jedis/tests/commands/SetCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/SetCommandsTest.java index 2149feb..abdfc2b 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/SetCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/SetCommandsTest.java @@ -9,6 +9,7 @@ import org.junit.Test; import redis.clients.jedis.ScanParams; 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 { final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; @@ -19,6 +20,11 @@ public class SetCommandsTest extends JedisCommandTestBase { final byte[] bc = { 0x0C }; final byte[] bd = { 0x0D }; final byte[] bx = { 0x42 }; + + final byte[] bbar1 = { 0x05, 0x06, 0x07, 0x08, 0x0A }; + final byte[] bbar2 = { 0x05, 0x06, 0x07, 0x08, 0x0B }; + final byte[] bbar3 = { 0x05, 0x06, 0x07, 0x08, 0x0C }; + final byte[] bbarstar = { 0x05, 0x06, 0x07, 0x08, '*' }; @Test public void sadd() { @@ -462,6 +468,14 @@ public class SetCommandsTest extends JedisCommandTestBase { assertEquals(SCAN_POINTER_START, result.getStringCursor()); assertFalse(result.getResult().isEmpty()); + + // binary + jedis.sadd(bfoo, ba, bb); + + ScanResult bResult = jedis.sscan(bfoo, SCAN_POINTER_START_BINARY); + + assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getBinaryCursor()); + assertFalse(bResult.getResult().isEmpty()); } @Test @@ -474,6 +488,16 @@ public class SetCommandsTest extends JedisCommandTestBase { assertEquals(SCAN_POINTER_START, result.getStringCursor()); assertFalse(result.getResult().isEmpty()); + + // binary + params = new ScanParams(); + params.match(bbarstar); + + jedis.sadd(bfoo, bbar1, bbar2, bbar3); + ScanResult bResult = jedis.sscan(bfoo, SCAN_POINTER_START_BINARY, params); + + assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getBinaryCursor()); + assertFalse(bResult.getResult().isEmpty()); } @Test @@ -486,5 +510,14 @@ public class SetCommandsTest extends JedisCommandTestBase { ScanResult result = jedis.sscan("foo", SCAN_POINTER_START, params); assertFalse(result.getResult().isEmpty()); + + // binary + params = new ScanParams(); + params.count(2); + + jedis.sadd(bfoo, bbar1, bbar2, bbar3); + ScanResult bResult = jedis.sscan(bfoo, SCAN_POINTER_START_BINARY, params); + + assertFalse(bResult.getResult().isEmpty()); } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/commands/SortedSetCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/SortedSetCommandsTest.java index 90b4c20..6b73cb7 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/SortedSetCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/SortedSetCommandsTest.java @@ -11,6 +11,7 @@ import redis.clients.jedis.Tuple; import redis.clients.jedis.ZParams; 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 { final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; @@ -19,6 +20,11 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { final byte[] ba = { 0x0A }; final byte[] bb = { 0x0B }; final byte[] bc = { 0x0C }; + + final byte[] bbar1 = { 0x05, 0x06, 0x07, 0x08, 0x0A }; + final byte[] bbar2 = { 0x05, 0x06, 0x07, 0x08, 0x0B }; + final byte[] bbar3 = { 0x05, 0x06, 0x07, 0x08, 0x0C }; + final byte[] bbarstar = { 0x05, 0x06, 0x07, 0x08, '*' }; @Test public void zadd() { @@ -899,6 +905,15 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { assertEquals(SCAN_POINTER_START, result.getStringCursor()); assertFalse(result.getResult().isEmpty()); + + // binary + jedis.zadd(bfoo, 1, ba); + jedis.zadd(bfoo, 1, bb); + + ScanResult bResult = jedis.zscan(bfoo, SCAN_POINTER_START_BINARY); + + assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getBinaryCursor()); + assertFalse(bResult.getResult().isEmpty()); } @Test @@ -913,6 +928,19 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { assertEquals(SCAN_POINTER_START, result.getStringCursor()); assertFalse(result.getResult().isEmpty()); + + // binary + params = new ScanParams(); + params.match(bbarstar); + + jedis.zadd(bfoo, 2, bbar1); + jedis.zadd(bfoo, 1, bbar2); + jedis.zadd(bfoo, 11, bbar3); + ScanResult bResult = jedis.zscan(bfoo, SCAN_POINTER_START_BINARY, params); + + assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getBinaryCursor()); + assertFalse(bResult.getResult().isEmpty()); + } @Test @@ -929,5 +957,17 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { ScanResult result = jedis.zscan("foo", SCAN_POINTER_START, params); assertFalse(result.getResult().isEmpty()); + + // binary + params = new ScanParams(); + params.count(2); + + jedis.zadd(bfoo, 2, bbar1); + jedis.zadd(bfoo, 1, bbar2); + jedis.zadd(bfoo, 11, bbar3); + + ScanResult bResult = jedis.zscan(bfoo, SCAN_POINTER_START_BINARY, params); + + assertFalse(bResult.getResult().isEmpty()); } } \ No newline at end of file From d9813a09dca3343c00991e7160801dc0f27b595a Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Wed, 5 Mar 2014 08:30:09 +0900 Subject: [PATCH 076/120] Change ScanResult's cursor type to byte[] * It's less probabilities to conversion with byte[] <-> ? --- .../java/redis/clients/jedis/ScanResult.java | 22 +++++++++---------- 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/src/main/java/redis/clients/jedis/ScanResult.java b/src/main/java/redis/clients/jedis/ScanResult.java index bf1bbd4..d864ee5 100644 --- a/src/main/java/redis/clients/jedis/ScanResult.java +++ b/src/main/java/redis/clients/jedis/ScanResult.java @@ -5,7 +5,7 @@ import java.util.List; import redis.clients.util.SafeEncoder; public class ScanResult { - private String cursor; + private byte[] cursor; private List results; @Deprecated @@ -15,20 +15,18 @@ public class ScanResult { * @see https://github.com/xetorthio/jedis/issues/531 */ public ScanResult(int cursor, List results) { - this.cursor = String.valueOf(cursor); - this.results = results; + this(Protocol.toByteArray(cursor), results); + } + + public ScanResult(String cursor, List results) { + this(SafeEncoder.encode(cursor), results); } public ScanResult(byte[] cursor, List results) { - this.cursor = SafeEncoder.encode(cursor); - this.results = results; - } - - public ScanResult(String cursor, List results) { this.cursor = cursor; this.results = results; } - + @Deprecated /** * This method is deprecated due to bug (scan cursor should be unsigned long) @@ -37,18 +35,18 @@ public class ScanResult { * @return int(currently), but will be changed to String, so be careful to prepare! */ public int getCursor() { - return Integer.parseInt(cursor); + return Integer.parseInt(getStringCursor()); } /** * FIXME: This method should be changed to getCursor() on next major release */ public String getStringCursor() { - return cursor; + return SafeEncoder.encode(cursor); } public byte[] getBinaryCursor() { - return SafeEncoder.encode(cursor); + return cursor; } public List getResult() { From e1f50b5fae9288a8327e8a9238481eee9405dfc6 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Wed, 5 Mar 2014 21:30:36 +0900 Subject: [PATCH 077/120] Change method naming : ScanResult.getBinaryCursor to ScanResult.getCursorAsBytes --- src/main/java/redis/clients/jedis/ScanResult.java | 2 +- .../jedis/tests/commands/AllKindOfValuesCommandsTest.java | 4 ++-- .../clients/jedis/tests/commands/HashesCommandsTest.java | 4 ++-- .../redis/clients/jedis/tests/commands/SetCommandsTest.java | 4 ++-- .../clients/jedis/tests/commands/SortedSetCommandsTest.java | 4 ++-- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/main/java/redis/clients/jedis/ScanResult.java b/src/main/java/redis/clients/jedis/ScanResult.java index d864ee5..199689e 100644 --- a/src/main/java/redis/clients/jedis/ScanResult.java +++ b/src/main/java/redis/clients/jedis/ScanResult.java @@ -45,7 +45,7 @@ public class ScanResult { return SafeEncoder.encode(cursor); } - public byte[] getBinaryCursor() { + public byte[] getCursorAsBytes() { return cursor; } diff --git a/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java index c0a9670..261bc3f 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java @@ -520,7 +520,7 @@ public class AllKindOfValuesCommandsTest extends JedisCommandTestBase { // binary ScanResult bResult = jedis.scan(SCAN_POINTER_START_BINARY); - assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getBinaryCursor()); + assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); assertFalse(bResult.getResult().isEmpty()); } @@ -547,7 +547,7 @@ public class AllKindOfValuesCommandsTest extends JedisCommandTestBase { ScanResult bResult = jedis.scan(SCAN_POINTER_START_BINARY, params); - assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getBinaryCursor()); + assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); assertFalse(bResult.getResult().isEmpty()); } diff --git a/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java index 8883f1f..7ecfbf6 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java @@ -312,7 +312,7 @@ public class HashesCommandsTest extends JedisCommandTestBase { ScanResult> bResult = jedis.hscan(bfoo, SCAN_POINTER_START_BINARY); - assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getBinaryCursor()); + assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); assertFalse(bResult.getResult().isEmpty()); } @@ -341,7 +341,7 @@ public class HashesCommandsTest extends JedisCommandTestBase { ScanResult> bResult = jedis.hscan(bfoo, SCAN_POINTER_START_BINARY, params); - assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getBinaryCursor()); + assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); assertFalse(bResult.getResult().isEmpty()); } diff --git a/src/test/java/redis/clients/jedis/tests/commands/SetCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/SetCommandsTest.java index abdfc2b..8687e67 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/SetCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/SetCommandsTest.java @@ -474,7 +474,7 @@ public class SetCommandsTest extends JedisCommandTestBase { ScanResult bResult = jedis.sscan(bfoo, SCAN_POINTER_START_BINARY); - assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getBinaryCursor()); + assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); assertFalse(bResult.getResult().isEmpty()); } @@ -496,7 +496,7 @@ public class SetCommandsTest extends JedisCommandTestBase { jedis.sadd(bfoo, bbar1, bbar2, bbar3); ScanResult bResult = jedis.sscan(bfoo, SCAN_POINTER_START_BINARY, params); - assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getBinaryCursor()); + assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); assertFalse(bResult.getResult().isEmpty()); } diff --git a/src/test/java/redis/clients/jedis/tests/commands/SortedSetCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/SortedSetCommandsTest.java index 6b73cb7..3e66642 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/SortedSetCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/SortedSetCommandsTest.java @@ -912,7 +912,7 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { ScanResult bResult = jedis.zscan(bfoo, SCAN_POINTER_START_BINARY); - assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getBinaryCursor()); + assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); assertFalse(bResult.getResult().isEmpty()); } @@ -938,7 +938,7 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { jedis.zadd(bfoo, 11, bbar3); ScanResult bResult = jedis.zscan(bfoo, SCAN_POINTER_START_BINARY, params); - assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getBinaryCursor()); + assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); assertFalse(bResult.getResult().isEmpty()); } From e7285ade5c10a74e15680158bcfd60ffbad83f06 Mon Sep 17 00:00:00 2001 From: Aniket Schneider Date: Tue, 4 Mar 2014 18:14:41 -0500 Subject: [PATCH 078/120] Accept long parameter for pexpire --- src/main/java/redis/clients/jedis/BinaryClient.java | 5 +++++ src/main/java/redis/clients/jedis/BinaryJedis.java | 5 +++++ src/main/java/redis/clients/jedis/Client.java | 5 +++++ src/main/java/redis/clients/jedis/Jedis.java | 5 +++++ src/main/java/redis/clients/jedis/PipelineBase.java | 12 +++++++++++- .../tests/commands/AllKindOfValuesCommandsTest.java | 11 +++++++++-- 6 files changed, 40 insertions(+), 3 deletions(-) diff --git a/src/main/java/redis/clients/jedis/BinaryClient.java b/src/main/java/redis/clients/jedis/BinaryClient.java index 2377665..10d980c 100644 --- a/src/main/java/redis/clients/jedis/BinaryClient.java +++ b/src/main/java/redis/clients/jedis/BinaryClient.java @@ -1091,7 +1091,12 @@ public class BinaryClient extends Connection { sendCommand(RESTORE, key, toByteArray(ttl), serializedValue); } + @Deprecated public void pexpire(final byte[] key, final int milliseconds) { + pexpire(key, (long) milliseconds); + } + + public void pexpire(final byte[] key, final long milliseconds) { sendCommand(PEXPIRE, key, toByteArray(milliseconds)); } diff --git a/src/main/java/redis/clients/jedis/BinaryJedis.java b/src/main/java/redis/clients/jedis/BinaryJedis.java index eba466f..a08cb09 100644 --- a/src/main/java/redis/clients/jedis/BinaryJedis.java +++ b/src/main/java/redis/clients/jedis/BinaryJedis.java @@ -3314,7 +3314,12 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, return client.getStatusCodeReply(); } + @Deprecated public Long pexpire(final byte[] key, final int milliseconds) { + return pexpire(key, (long) milliseconds); + } + + public Long pexpire(final byte[] key, final long milliseconds) { checkIsInMulti(); client.pexpire(key, milliseconds); return client.getIntegerReply(); diff --git a/src/main/java/redis/clients/jedis/Client.java b/src/main/java/redis/clients/jedis/Client.java index 64f6f5c..98b33b4 100644 --- a/src/main/java/redis/clients/jedis/Client.java +++ b/src/main/java/redis/clients/jedis/Client.java @@ -777,7 +777,12 @@ public class Client extends BinaryClient implements Commands { restore(SafeEncoder.encode(key), ttl, serializedValue); } + @Deprecated public void pexpire(final String key, final int milliseconds) { + pexpire(key, (long) milliseconds); + } + + public void pexpire(final String key, final long milliseconds) { pexpire(SafeEncoder.encode(key), milliseconds); } diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index 4961f42..43e0de9 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -3060,7 +3060,12 @@ public class Jedis extends BinaryJedis implements JedisCommands, return client.getStatusCodeReply(); } + @Deprecated public Long pexpire(final String key, final int milliseconds) { + return pexpire(key, (long) milliseconds); + } + + public Long pexpire(final String key, final long milliseconds) { checkIsInMulti(); client.pexpire(key, milliseconds); return client.getIntegerReply(); diff --git a/src/main/java/redis/clients/jedis/PipelineBase.java b/src/main/java/redis/clients/jedis/PipelineBase.java index 3183ba1..9e237bd 100644 --- a/src/main/java/redis/clients/jedis/PipelineBase.java +++ b/src/main/java/redis/clients/jedis/PipelineBase.java @@ -1080,12 +1080,22 @@ abstract class PipelineBase extends Queable implements BinaryRedisPipeline, return getResponse(BuilderFactory.LONG); } + @Deprecated public Response pexpire(String key, int milliseconds) { + return pexpire(key, (long) milliseconds); + } + + @Deprecated + public Response pexpire(byte[] key, int milliseconds) { + return pexpire(key, (long) milliseconds); + } + + public Response pexpire(String key, long milliseconds) { getClient(key).pexpire(key, milliseconds); return getResponse(BuilderFactory.LONG); } - public Response pexpire(byte[] key, int milliseconds) { + public Response pexpire(byte[] key, long milliseconds) { getClient(key).pexpire(key, milliseconds); return getResponse(BuilderFactory.LONG); } diff --git a/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java index 057537c..8c75c27 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java @@ -474,9 +474,16 @@ public class AllKindOfValuesCommandsTest extends JedisCommandTestBase { long status = jedis.pexpire("foo", 10000); assertEquals(0, status); - jedis.set("foo", "bar"); - status = jedis.pexpire("foo", 10000); + jedis.set("foo1", "bar1"); + status = jedis.pexpire("foo1", 10000); assertEquals(1, status); + + jedis.set("foo2", "bar2"); + status = jedis.pexpire("foo2", 200000000000L); + assertEquals(1, status); + + long pttl = jedis.pttl("foo2"); + assertTrue(pttl > 100000000000L); } @Test From 62b98a3e633434e4f635d4ef1ca0076d4404df42 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Wed, 12 Mar 2014 10:31:22 -0400 Subject: [PATCH 079/120] Add tests to check returning null to pool --- src/main/java/redis/clients/util/Pool.java | 3 +++ .../java/redis/clients/jedis/tests/JedisPoolTest.java | 10 ++++++++++ 2 files changed, 13 insertions(+) diff --git a/src/main/java/redis/clients/util/Pool.java b/src/main/java/redis/clients/util/Pool.java index 2b0d91f..659c731 100644 --- a/src/main/java/redis/clients/util/Pool.java +++ b/src/main/java/redis/clients/util/Pool.java @@ -45,6 +45,9 @@ public abstract class Pool { } public void returnResourceObject(final T resource) { + if (resource == null) { + return; + } try { internalPool.returnObject(resource); } catch (Exception e) { diff --git a/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java b/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java index a501024..514d3b5 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java @@ -198,4 +198,14 @@ public class JedisPoolTest extends Assert { pool.returnResource(jedis2); pool.destroy(); } + + @Test + public void returnNullObjectShouldNotFail() { + JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), + hnp.getPort(), 2000, "foobared", 0, "my_shiny_client_name"); + + pool.returnBrokenResource(null); + pool.returnResource(null); + pool.returnResourceObject(null); + } } From e449923ec01846e7063a3ad468ab5d63fba8709b Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Wed, 12 Mar 2014 10:44:00 -0400 Subject: [PATCH 080/120] [maven-release-plugin] prepare release jedis-2.4.2 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index a55806e..2cf1640 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ jar redis.clients jedis - 2.4.2-SNAPSHOT + 2.4.2 Jedis Jedis is a blazingly small and sane Redis java client. https://github.com/xetorthio/jedis @@ -41,7 +41,7 @@ scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git - jedis-2.2.0 + jedis-2.4.2 From ec03c0940e9a40e31ecce2b6912822c8f2bec64d Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Wed, 12 Mar 2014 10:44:02 -0400 Subject: [PATCH 081/120] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 2cf1640..1be71dd 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ jar redis.clients jedis - 2.4.2 + 2.5.0-SNAPSHOT Jedis Jedis is a blazingly small and sane Redis java client. https://github.com/xetorthio/jedis @@ -41,7 +41,7 @@ scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git - jedis-2.4.2 + jedis-2.2.0 From d00e8b6444b6e4d79e8d0efa2fb20cd0fc915e69 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Wed, 12 Mar 2014 13:13:48 -0400 Subject: [PATCH 082/120] revert back version --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 1be71dd..a55806e 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ jar redis.clients jedis - 2.5.0-SNAPSHOT + 2.4.2-SNAPSHOT Jedis Jedis is a blazingly small and sane Redis java client. https://github.com/xetorthio/jedis From 70fa35f3ba13b90d74cf98095e7525d10e1cf80a Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Wed, 12 Mar 2014 13:14:49 -0400 Subject: [PATCH 083/120] [maven-release-plugin] prepare release jedis-2.4.2 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index a55806e..2cf1640 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ jar redis.clients jedis - 2.4.2-SNAPSHOT + 2.4.2 Jedis Jedis is a blazingly small and sane Redis java client. https://github.com/xetorthio/jedis @@ -41,7 +41,7 @@ scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git - jedis-2.2.0 + jedis-2.4.2 From bcd40b4e34d367cdbcc35c66bd210283f0608ee0 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Wed, 12 Mar 2014 13:14:51 -0400 Subject: [PATCH 084/120] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 2cf1640..1be71dd 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ jar redis.clients jedis - 2.4.2 + 2.5.0-SNAPSHOT Jedis Jedis is a blazingly small and sane Redis java client. https://github.com/xetorthio/jedis @@ -41,7 +41,7 @@ scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git - jedis-2.4.2 + jedis-2.2.0 From d7f88789eacd27b50ab01de0d26caaf3b4edc843 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Sat, 22 Mar 2014 18:00:34 +0900 Subject: [PATCH 085/120] Reflect recent version to maven dependency explain --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bbefbe1..450c574 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ Or use it as a maven dependency: redis.clients jedis - 2.2.1 + 2.4.2 jar compile From b7db408a67019ba2232041ac2d643697a00d2b00 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Thu, 27 Mar 2014 23:33:00 +0900 Subject: [PATCH 086/120] Fix invalid link to download (it's deprecated) - replace to releases --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 450c574..70664a1 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ All of the following redis features are supported: ## How do I use it? You can download the latest build at: - http://github.com/xetorthio/jedis/downloads + http://github.com/xetorthio/jedis/releases Or use it as a maven dependency: From 7a8e8f994d742b32fe3680760be82f9b49901747 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Fri, 28 Mar 2014 23:16:30 +0900 Subject: [PATCH 087/120] Append 'package' command in Makefile --- Makefile | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Makefile b/Makefile index 1ac2bb9..f3bc013 100644 --- a/Makefile +++ b/Makefile @@ -215,6 +215,11 @@ test: mvn -Dtest=${TEST} clean compile test make stop +package: + make start + mvn clean package + make stop + deploy: make start mvn clean deploy From ce1156be44ea2b17073942ad5c60a78b566ed8e8 Mon Sep 17 00:00:00 2001 From: Vijay Ramesh Date: Thu, 3 Apr 2014 16:27:52 -0700 Subject: [PATCH 088/120] JedisSentinelPool#return[Broken]Resource should handle nulls the same was as JedisPool --- .../clients/jedis/JedisSentinelPool.java | 10 ++++--- .../jedis/tests/JedisSentinelPoolTest.java | 26 +++++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/main/java/redis/clients/jedis/JedisSentinelPool.java b/src/main/java/redis/clients/jedis/JedisSentinelPool.java index 4fe5433..224ca99 100644 --- a/src/main/java/redis/clients/jedis/JedisSentinelPool.java +++ b/src/main/java/redis/clients/jedis/JedisSentinelPool.java @@ -75,12 +75,16 @@ public class JedisSentinelPool extends Pool { } public void returnBrokenResource(final Jedis resource) { - returnBrokenResourceObject(resource); + if (resource != null) { + returnBrokenResourceObject(resource); + } } public void returnResource(final Jedis resource) { - resource.resetState(); - returnResourceObject(resource); + if (resource != null) { + resource.resetState(); + returnResourceObject(resource); + } } private volatile HostAndPort currentHostMaster; diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java index c8df9c5..1dd2896 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java @@ -80,6 +80,32 @@ public class JedisSentinelPoolTest extends JedisTestBase { } } + @Test + public void returnResourceWithNullResource() { + GenericObjectPoolConfig config = new GenericObjectPoolConfig(); + config.setMaxTotal(1); + config.setBlockWhenExhausted(false); + JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels, + config, 1000, "foobared", 2); + + Jedis nullJedis = null; + pool.returnResource(nullJedis); + pool.destroy(); + } + + @Test + public void returnBrokenResourceWithNullResource() { + GenericObjectPoolConfig config = new GenericObjectPoolConfig(); + config.setMaxTotal(1); + config.setBlockWhenExhausted(false); + JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels, + config, 1000, "foobared", 2); + + Jedis nullJedis = null; + pool.returnBrokenResource(nullJedis); + pool.destroy(); + } + private void forceFailover(JedisSentinelPool pool) throws InterruptedException { HostAndPort oldMaster = pool.getCurrentHostMaster(); From afefb71e57b0258a52b465b2b4e57c132aef4db9 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Thu, 3 Apr 2014 22:01:15 -0300 Subject: [PATCH 089/120] Add support for HLL --- src/main/java/RedisTimeout.java | 50 +++++++++++++++++++ .../redis/clients/jedis/BinaryClient.java | 13 ++++- src/main/java/redis/clients/jedis/Client.java | 12 +++++ src/main/java/redis/clients/jedis/Jedis.java | 18 +++++++ .../java/redis/clients/jedis/Protocol.java | 2 +- .../commands/HyperLogLogCommandsTest.java | 46 +++++++++++++++++ 6 files changed, 139 insertions(+), 2 deletions(-) create mode 100644 src/main/java/RedisTimeout.java create mode 100644 src/test/java/redis/clients/jedis/tests/commands/HyperLogLogCommandsTest.java diff --git a/src/main/java/RedisTimeout.java b/src/main/java/RedisTimeout.java new file mode 100644 index 0000000..2311080 --- /dev/null +++ b/src/main/java/RedisTimeout.java @@ -0,0 +1,50 @@ +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; + +public class RedisTimeout { + + public static void main(String[] args) { + // set k,v pairs where k == v + Jedis edis = new Jedis("127.0.0.1", 6379, 1000); + for (int i = 0; i < 100000; i++) { + edis.set("" + i, "" + i); + } + edis.close(); + JedisPoolConfig conf = new JedisPoolConfig(); + conf.setMaxTotal(1); + final JedisPool pool = new JedisPool(new JedisPoolConfig(), "127.0.0.1", 6379, 1); + for (int t = 0; t < 100; t++) { + new Thread() { + public void run() { + + final Jedis edis = pool.getResource(); + // timeout + // = 1 + // here. + for (int i = 0; i < 1000; i++) { + try { + String key = "" + i; + String value = edis.get(key); + if (!key.equals(value)) { + System.err.println(Thread.currentThread() + .getName() + + "\t\t\t" + + key + + "<>" + + value); + } + } catch (Exception e) { + System.err.println(">>>>>>>>>>" + e.toString()); + e.printStackTrace(); + } + } + System.out.println("Done"); + pool.returnResource(edis); + }; + }.start(); + } + + } + +} \ No newline at end of file diff --git a/src/main/java/redis/clients/jedis/BinaryClient.java b/src/main/java/redis/clients/jedis/BinaryClient.java index 2377665..bbd0f8f 100644 --- a/src/main/java/redis/clients/jedis/BinaryClient.java +++ b/src/main/java/redis/clients/jedis/BinaryClient.java @@ -320,7 +320,7 @@ public class BinaryClient extends Connection { public void sadd(final byte[] key, final byte[]... members) { sendCommand(SADD, joinParameters(key, members)); } - + public void smembers(final byte[] key) { sendCommand(SMEMBERS, key); } @@ -1253,4 +1253,15 @@ public class BinaryClient extends Connection { public void asking() { sendCommand(Command.ASKING); } + + public void pfadd(final byte[] key, final byte[]... elements) { + sendCommand(PFADD, joinParameters(key, elements)); + } + + public void pfcount(final byte[] key) { + sendCommand(PFCOUNT, key); + } + public void pfmerge(final byte[] deskey, final byte[]... sourcekeys) { + sendCommand(PFMERGE, joinParameters(deskey, sourcekeys)); + } } diff --git a/src/main/java/redis/clients/jedis/Client.java b/src/main/java/redis/clients/jedis/Client.java index 64f6f5c..f6b9529 100644 --- a/src/main/java/redis/clients/jedis/Client.java +++ b/src/main/java/redis/clients/jedis/Client.java @@ -951,4 +951,16 @@ public class Client extends BinaryClient implements Commands { cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot), Protocol.CLUSTER_SETSLOT_IMPORTING, nodeId); } + + public void pfadd(String key, final String... elements) { + pfadd(SafeEncoder.encode(key), SafeEncoder.encodeMany(elements)); + } + + public void pfcount(final String key) { + pfcount(SafeEncoder.encode(key)); + } + + public void pfmerge(final String destkey, final String... sourcekeys) { + pfmerge(SafeEncoder.encode(destkey), SafeEncoder.encodeMany(sourcekeys)); + } } diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index 4961f42..188140f 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -3412,4 +3412,22 @@ public class Jedis extends BinaryJedis implements JedisCommands, return BuilderFactory.STRING_MAP .build(client.getBinaryMultiBulkReply()); } + + public Long pfadd(final String key, String... elements) { + checkIsInMulti(); + client.pfadd(key, elements); + return client.getIntegerReply(); + } + + public long pfcount(final String key) { + checkIsInMulti(); + client.pfcount(key); + return client.getIntegerReply(); + } + + public String pfmerge(final String destkey, final String... sourcekeys) { + checkIsInMulti(); + client.pfmerge(destkey, sourcekeys); + return client.getStatusCodeReply(); + } } diff --git a/src/main/java/redis/clients/jedis/Protocol.java b/src/main/java/redis/clients/jedis/Protocol.java index 681bc56..5ceccaa 100644 --- a/src/main/java/redis/clients/jedis/Protocol.java +++ b/src/main/java/redis/clients/jedis/Protocol.java @@ -208,7 +208,7 @@ public final class Protocol { } public static enum Command { - PING, SET, GET, QUIT, EXISTS, DEL, TYPE, FLUSHDB, KEYS, RANDOMKEY, RENAME, RENAMENX, RENAMEX, DBSIZE, EXPIRE, EXPIREAT, TTL, SELECT, MOVE, FLUSHALL, GETSET, MGET, SETNX, SETEX, MSET, MSETNX, DECRBY, DECR, INCRBY, INCR, APPEND, SUBSTR, HSET, HGET, HSETNX, HMSET, HMGET, HINCRBY, HEXISTS, HDEL, HLEN, HKEYS, HVALS, HGETALL, RPUSH, LPUSH, LLEN, LRANGE, LTRIM, LINDEX, LSET, LREM, LPOP, RPOP, RPOPLPUSH, SADD, SMEMBERS, SREM, SPOP, SMOVE, SCARD, SISMEMBER, SINTER, SINTERSTORE, SUNION, SUNIONSTORE, SDIFF, SDIFFSTORE, SRANDMEMBER, ZADD, ZRANGE, ZREM, ZINCRBY, ZRANK, ZREVRANK, ZREVRANGE, ZCARD, ZSCORE, MULTI, DISCARD, EXEC, WATCH, UNWATCH, SORT, BLPOP, BRPOP, AUTH, SUBSCRIBE, PUBLISH, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, PUBSUB, ZCOUNT, ZRANGEBYSCORE, ZREVRANGEBYSCORE, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZUNIONSTORE, ZINTERSTORE, SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE, SHUTDOWN, INFO, MONITOR, SLAVEOF, CONFIG, STRLEN, SYNC, LPUSHX, PERSIST, RPUSHX, ECHO, LINSERT, DEBUG, BRPOPLPUSH, SETBIT, GETBIT, SETRANGE, GETRANGE, EVAL, EVALSHA, SCRIPT, SLOWLOG, OBJECT, BITCOUNT, BITOP, SENTINEL, DUMP, RESTORE, PEXPIRE, PEXPIREAT, PTTL, INCRBYFLOAT, PSETEX, CLIENT, TIME, MIGRATE, HINCRBYFLOAT, SCAN, HSCAN, SSCAN, ZSCAN, WAIT, CLUSTER, ASKING; + PING, SET, GET, QUIT, EXISTS, DEL, TYPE, FLUSHDB, KEYS, RANDOMKEY, RENAME, RENAMENX, RENAMEX, DBSIZE, EXPIRE, EXPIREAT, TTL, SELECT, MOVE, FLUSHALL, GETSET, MGET, SETNX, SETEX, MSET, MSETNX, DECRBY, DECR, INCRBY, INCR, APPEND, SUBSTR, HSET, HGET, HSETNX, HMSET, HMGET, HINCRBY, HEXISTS, HDEL, HLEN, HKEYS, HVALS, HGETALL, RPUSH, LPUSH, LLEN, LRANGE, LTRIM, LINDEX, LSET, LREM, LPOP, RPOP, RPOPLPUSH, SADD, SMEMBERS, SREM, SPOP, SMOVE, SCARD, SISMEMBER, SINTER, SINTERSTORE, SUNION, SUNIONSTORE, SDIFF, SDIFFSTORE, SRANDMEMBER, ZADD, ZRANGE, ZREM, ZINCRBY, ZRANK, ZREVRANK, ZREVRANGE, ZCARD, ZSCORE, MULTI, DISCARD, EXEC, WATCH, UNWATCH, SORT, BLPOP, BRPOP, AUTH, SUBSCRIBE, PUBLISH, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, PUBSUB, ZCOUNT, ZRANGEBYSCORE, ZREVRANGEBYSCORE, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZUNIONSTORE, ZINTERSTORE, SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE, SHUTDOWN, INFO, MONITOR, SLAVEOF, CONFIG, STRLEN, SYNC, LPUSHX, PERSIST, RPUSHX, ECHO, LINSERT, DEBUG, BRPOPLPUSH, SETBIT, GETBIT, SETRANGE, GETRANGE, EVAL, EVALSHA, SCRIPT, SLOWLOG, OBJECT, BITCOUNT, BITOP, SENTINEL, DUMP, RESTORE, PEXPIRE, PEXPIREAT, PTTL, INCRBYFLOAT, PSETEX, CLIENT, TIME, MIGRATE, HINCRBYFLOAT, SCAN, HSCAN, SSCAN, ZSCAN, WAIT, CLUSTER, ASKING, PFADD, PFCOUNT, PFMERGE; public final byte[] raw; diff --git a/src/test/java/redis/clients/jedis/tests/commands/HyperLogLogCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/HyperLogLogCommandsTest.java new file mode 100644 index 0000000..e14c59b --- /dev/null +++ b/src/test/java/redis/clients/jedis/tests/commands/HyperLogLogCommandsTest.java @@ -0,0 +1,46 @@ +package redis.clients.jedis.tests.commands; + +import org.junit.Test; + +public class HyperLogLogCommandsTest extends JedisCommandTestBase { + + + @Test + public void pfadd() { + long status = jedis.pfadd("foo", "a"); + assertEquals(1, status); + + status = jedis.pfadd("foo", "a"); + assertEquals(0, status); + } + + @Test + public void pfcount() { + long status = jedis.pfadd("hll", "foo", "bar", "zap"); + assertEquals(1, status); + + status = jedis.pfadd("hll", "zap", "zap", "zap"); + assertEquals(0, status); + + status = jedis.pfadd("hll", "foo", "bar"); + assertEquals(0, status); + + status = jedis.pfcount("hll"); + assertEquals(3, status); + } + + @Test + public void pfmerge() { + long status = jedis.pfadd("hll1", "foo", "bar", "zap", "a"); + assertEquals(1, status); + + status = jedis.pfadd("hll2", "a", "b", "c", "foo"); + assertEquals(1, status); + + String mergeStatus = jedis.pfmerge("hll3", "hll1", "hll2"); + assertEquals("OK", mergeStatus); + + status = jedis.pfcount("hll3"); + assertEquals(6, status); + } +} \ No newline at end of file From a6b76ae6651e840c0f4317548ff79223cc82b4ab Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Thu, 3 Apr 2014 22:05:40 -0300 Subject: [PATCH 090/120] Remove RedisTimeout that was added accidentally --- src/main/java/RedisTimeout.java | 50 --------------------------------- 1 file changed, 50 deletions(-) delete mode 100644 src/main/java/RedisTimeout.java diff --git a/src/main/java/RedisTimeout.java b/src/main/java/RedisTimeout.java deleted file mode 100644 index 2311080..0000000 --- a/src/main/java/RedisTimeout.java +++ /dev/null @@ -1,50 +0,0 @@ -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.JedisPoolConfig; - -public class RedisTimeout { - - public static void main(String[] args) { - // set k,v pairs where k == v - Jedis edis = new Jedis("127.0.0.1", 6379, 1000); - for (int i = 0; i < 100000; i++) { - edis.set("" + i, "" + i); - } - edis.close(); - JedisPoolConfig conf = new JedisPoolConfig(); - conf.setMaxTotal(1); - final JedisPool pool = new JedisPool(new JedisPoolConfig(), "127.0.0.1", 6379, 1); - for (int t = 0; t < 100; t++) { - new Thread() { - public void run() { - - final Jedis edis = pool.getResource(); - // timeout - // = 1 - // here. - for (int i = 0; i < 1000; i++) { - try { - String key = "" + i; - String value = edis.get(key); - if (!key.equals(value)) { - System.err.println(Thread.currentThread() - .getName() - + "\t\t\t" - + key - + "<>" - + value); - } - } catch (Exception e) { - System.err.println(">>>>>>>>>>" + e.toString()); - e.printStackTrace(); - } - } - System.out.println("Done"); - pool.returnResource(edis); - }; - }.start(); - } - - } - -} \ No newline at end of file From ac53759f9706b52184963e98af11d2e44bfb1297 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Sat, 5 Apr 2014 18:46:06 +0900 Subject: [PATCH 091/120] Revert "Add support for HLL" This reverts commit afefb71e57b0258a52b465b2b4e57c132aef4db9. --- .../redis/clients/jedis/BinaryClient.java | 13 +----- src/main/java/redis/clients/jedis/Client.java | 12 ----- src/main/java/redis/clients/jedis/Jedis.java | 18 -------- .../java/redis/clients/jedis/Protocol.java | 2 +- .../commands/HyperLogLogCommandsTest.java | 46 ------------------- 5 files changed, 2 insertions(+), 89 deletions(-) delete mode 100644 src/test/java/redis/clients/jedis/tests/commands/HyperLogLogCommandsTest.java diff --git a/src/main/java/redis/clients/jedis/BinaryClient.java b/src/main/java/redis/clients/jedis/BinaryClient.java index bbd0f8f..2377665 100644 --- a/src/main/java/redis/clients/jedis/BinaryClient.java +++ b/src/main/java/redis/clients/jedis/BinaryClient.java @@ -320,7 +320,7 @@ public class BinaryClient extends Connection { public void sadd(final byte[] key, final byte[]... members) { sendCommand(SADD, joinParameters(key, members)); } - + public void smembers(final byte[] key) { sendCommand(SMEMBERS, key); } @@ -1253,15 +1253,4 @@ public class BinaryClient extends Connection { public void asking() { sendCommand(Command.ASKING); } - - public void pfadd(final byte[] key, final byte[]... elements) { - sendCommand(PFADD, joinParameters(key, elements)); - } - - public void pfcount(final byte[] key) { - sendCommand(PFCOUNT, key); - } - public void pfmerge(final byte[] deskey, final byte[]... sourcekeys) { - sendCommand(PFMERGE, joinParameters(deskey, sourcekeys)); - } } diff --git a/src/main/java/redis/clients/jedis/Client.java b/src/main/java/redis/clients/jedis/Client.java index f6b9529..64f6f5c 100644 --- a/src/main/java/redis/clients/jedis/Client.java +++ b/src/main/java/redis/clients/jedis/Client.java @@ -951,16 +951,4 @@ public class Client extends BinaryClient implements Commands { cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot), Protocol.CLUSTER_SETSLOT_IMPORTING, nodeId); } - - public void pfadd(String key, final String... elements) { - pfadd(SafeEncoder.encode(key), SafeEncoder.encodeMany(elements)); - } - - public void pfcount(final String key) { - pfcount(SafeEncoder.encode(key)); - } - - public void pfmerge(final String destkey, final String... sourcekeys) { - pfmerge(SafeEncoder.encode(destkey), SafeEncoder.encodeMany(sourcekeys)); - } } diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index 188140f..4961f42 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -3412,22 +3412,4 @@ public class Jedis extends BinaryJedis implements JedisCommands, return BuilderFactory.STRING_MAP .build(client.getBinaryMultiBulkReply()); } - - public Long pfadd(final String key, String... elements) { - checkIsInMulti(); - client.pfadd(key, elements); - return client.getIntegerReply(); - } - - public long pfcount(final String key) { - checkIsInMulti(); - client.pfcount(key); - return client.getIntegerReply(); - } - - public String pfmerge(final String destkey, final String... sourcekeys) { - checkIsInMulti(); - client.pfmerge(destkey, sourcekeys); - return client.getStatusCodeReply(); - } } diff --git a/src/main/java/redis/clients/jedis/Protocol.java b/src/main/java/redis/clients/jedis/Protocol.java index 5ceccaa..681bc56 100644 --- a/src/main/java/redis/clients/jedis/Protocol.java +++ b/src/main/java/redis/clients/jedis/Protocol.java @@ -208,7 +208,7 @@ public final class Protocol { } public static enum Command { - PING, SET, GET, QUIT, EXISTS, DEL, TYPE, FLUSHDB, KEYS, RANDOMKEY, RENAME, RENAMENX, RENAMEX, DBSIZE, EXPIRE, EXPIREAT, TTL, SELECT, MOVE, FLUSHALL, GETSET, MGET, SETNX, SETEX, MSET, MSETNX, DECRBY, DECR, INCRBY, INCR, APPEND, SUBSTR, HSET, HGET, HSETNX, HMSET, HMGET, HINCRBY, HEXISTS, HDEL, HLEN, HKEYS, HVALS, HGETALL, RPUSH, LPUSH, LLEN, LRANGE, LTRIM, LINDEX, LSET, LREM, LPOP, RPOP, RPOPLPUSH, SADD, SMEMBERS, SREM, SPOP, SMOVE, SCARD, SISMEMBER, SINTER, SINTERSTORE, SUNION, SUNIONSTORE, SDIFF, SDIFFSTORE, SRANDMEMBER, ZADD, ZRANGE, ZREM, ZINCRBY, ZRANK, ZREVRANK, ZREVRANGE, ZCARD, ZSCORE, MULTI, DISCARD, EXEC, WATCH, UNWATCH, SORT, BLPOP, BRPOP, AUTH, SUBSCRIBE, PUBLISH, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, PUBSUB, ZCOUNT, ZRANGEBYSCORE, ZREVRANGEBYSCORE, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZUNIONSTORE, ZINTERSTORE, SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE, SHUTDOWN, INFO, MONITOR, SLAVEOF, CONFIG, STRLEN, SYNC, LPUSHX, PERSIST, RPUSHX, ECHO, LINSERT, DEBUG, BRPOPLPUSH, SETBIT, GETBIT, SETRANGE, GETRANGE, EVAL, EVALSHA, SCRIPT, SLOWLOG, OBJECT, BITCOUNT, BITOP, SENTINEL, DUMP, RESTORE, PEXPIRE, PEXPIREAT, PTTL, INCRBYFLOAT, PSETEX, CLIENT, TIME, MIGRATE, HINCRBYFLOAT, SCAN, HSCAN, SSCAN, ZSCAN, WAIT, CLUSTER, ASKING, PFADD, PFCOUNT, PFMERGE; + PING, SET, GET, QUIT, EXISTS, DEL, TYPE, FLUSHDB, KEYS, RANDOMKEY, RENAME, RENAMENX, RENAMEX, DBSIZE, EXPIRE, EXPIREAT, TTL, SELECT, MOVE, FLUSHALL, GETSET, MGET, SETNX, SETEX, MSET, MSETNX, DECRBY, DECR, INCRBY, INCR, APPEND, SUBSTR, HSET, HGET, HSETNX, HMSET, HMGET, HINCRBY, HEXISTS, HDEL, HLEN, HKEYS, HVALS, HGETALL, RPUSH, LPUSH, LLEN, LRANGE, LTRIM, LINDEX, LSET, LREM, LPOP, RPOP, RPOPLPUSH, SADD, SMEMBERS, SREM, SPOP, SMOVE, SCARD, SISMEMBER, SINTER, SINTERSTORE, SUNION, SUNIONSTORE, SDIFF, SDIFFSTORE, SRANDMEMBER, ZADD, ZRANGE, ZREM, ZINCRBY, ZRANK, ZREVRANK, ZREVRANGE, ZCARD, ZSCORE, MULTI, DISCARD, EXEC, WATCH, UNWATCH, SORT, BLPOP, BRPOP, AUTH, SUBSCRIBE, PUBLISH, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, PUBSUB, ZCOUNT, ZRANGEBYSCORE, ZREVRANGEBYSCORE, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZUNIONSTORE, ZINTERSTORE, SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE, SHUTDOWN, INFO, MONITOR, SLAVEOF, CONFIG, STRLEN, SYNC, LPUSHX, PERSIST, RPUSHX, ECHO, LINSERT, DEBUG, BRPOPLPUSH, SETBIT, GETBIT, SETRANGE, GETRANGE, EVAL, EVALSHA, SCRIPT, SLOWLOG, OBJECT, BITCOUNT, BITOP, SENTINEL, DUMP, RESTORE, PEXPIRE, PEXPIREAT, PTTL, INCRBYFLOAT, PSETEX, CLIENT, TIME, MIGRATE, HINCRBYFLOAT, SCAN, HSCAN, SSCAN, ZSCAN, WAIT, CLUSTER, ASKING; public final byte[] raw; diff --git a/src/test/java/redis/clients/jedis/tests/commands/HyperLogLogCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/HyperLogLogCommandsTest.java deleted file mode 100644 index e14c59b..0000000 --- a/src/test/java/redis/clients/jedis/tests/commands/HyperLogLogCommandsTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package redis.clients.jedis.tests.commands; - -import org.junit.Test; - -public class HyperLogLogCommandsTest extends JedisCommandTestBase { - - - @Test - public void pfadd() { - long status = jedis.pfadd("foo", "a"); - assertEquals(1, status); - - status = jedis.pfadd("foo", "a"); - assertEquals(0, status); - } - - @Test - public void pfcount() { - long status = jedis.pfadd("hll", "foo", "bar", "zap"); - assertEquals(1, status); - - status = jedis.pfadd("hll", "zap", "zap", "zap"); - assertEquals(0, status); - - status = jedis.pfadd("hll", "foo", "bar"); - assertEquals(0, status); - - status = jedis.pfcount("hll"); - assertEquals(3, status); - } - - @Test - public void pfmerge() { - long status = jedis.pfadd("hll1", "foo", "bar", "zap", "a"); - assertEquals(1, status); - - status = jedis.pfadd("hll2", "a", "b", "c", "foo"); - assertEquals(1, status); - - String mergeStatus = jedis.pfmerge("hll3", "hll1", "hll2"); - assertEquals("OK", mergeStatus); - - status = jedis.pfcount("hll3"); - assertEquals(6, status); - } -} \ No newline at end of file From 1345b5c1da180631fdf9d3bf98813e1897dbd9e8 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Sat, 5 Apr 2014 22:19:11 +0900 Subject: [PATCH 092/120] Apply PF* commands to JedisCluster, ShardedJedis * Apply PF* commands to JedisCluster, ShardedJedis * PF* commands to interface ** pfadd / pfcount : JedisCommands ** pfmerge : MultiKeyCommands --- src/main/java/redis/clients/jedis/Jedis.java | 2 +- .../redis/clients/jedis/JedisCluster.java | 23 +++++++++++++++++++ .../redis/clients/jedis/JedisCommands.java | 4 ++++ .../redis/clients/jedis/MultiKeyCommands.java | 2 ++ .../redis/clients/jedis/ShardedJedis.java | 12 ++++++++++ 5 files changed, 42 insertions(+), 1 deletion(-) diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index 188140f..8782fc9 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -3413,7 +3413,7 @@ public class Jedis extends BinaryJedis implements JedisCommands, .build(client.getBinaryMultiBulkReply()); } - public Long pfadd(final String key, String... elements) { + public Long pfadd(final String key, final String... elements) { checkIsInMulti(); client.pfadd(key, elements); return client.getIntegerReply(); diff --git a/src/main/java/redis/clients/jedis/JedisCluster.java b/src/main/java/redis/clients/jedis/JedisCluster.java index 121bde8..a359226 100644 --- a/src/main/java/redis/clients/jedis/JedisCluster.java +++ b/src/main/java/redis/clients/jedis/JedisCluster.java @@ -1481,4 +1481,27 @@ public class JedisCluster implements JedisCommands, BasicCommands { } }.run(null); } + + @Override + public Long pfadd(final String key, final String... elements) { + return new JedisClusterCommand(connectionHandler, + timeout, maxRedirections) { + @Override + public Long execute(Jedis connection) { + return connection.pfadd(key, elements); + } + }.run(key); + } + + @Override + public long pfcount(final String key) { + return new JedisClusterCommand(connectionHandler, + timeout, maxRedirections) { + @Override + public Long execute(Jedis connection) { + return connection.pfcount(key); + } + }.run(key); + } + } diff --git a/src/main/java/redis/clients/jedis/JedisCommands.java b/src/main/java/redis/clients/jedis/JedisCommands.java index 5952bdb..5ce0121 100644 --- a/src/main/java/redis/clients/jedis/JedisCommands.java +++ b/src/main/java/redis/clients/jedis/JedisCommands.java @@ -240,4 +240,8 @@ public interface JedisCommands { ScanResult sscan(final String key, final String cursor); ScanResult zscan(final String key, final String cursor); + + Long pfadd(final String key, final String... elements); + + long pfcount(final String key); } diff --git a/src/main/java/redis/clients/jedis/MultiKeyCommands.java b/src/main/java/redis/clients/jedis/MultiKeyCommands.java index f03f82c..b829fca 100644 --- a/src/main/java/redis/clients/jedis/MultiKeyCommands.java +++ b/src/main/java/redis/clients/jedis/MultiKeyCommands.java @@ -79,4 +79,6 @@ public interface MultiKeyCommands { ScanResult scan(int cursor); ScanResult scan(final String cursor); + + String pfmerge(final String destkey, final String... sourcekeys); } diff --git a/src/main/java/redis/clients/jedis/ShardedJedis.java b/src/main/java/redis/clients/jedis/ShardedJedis.java index 7235cfe..46110ad 100644 --- a/src/main/java/redis/clients/jedis/ShardedJedis.java +++ b/src/main/java/redis/clients/jedis/ShardedJedis.java @@ -570,4 +570,16 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands { Jedis j = getShard(key); return j.zscan(key, cursor); } + + @Override + public Long pfadd(String key, String... elements) { + Jedis j = getShard(key); + return j.pfadd(key, elements); + } + + @Override + public long pfcount(String key) { + Jedis j = getShard(key); + return j.pfcount(key); + } } From 11f05ec161d25ea37338410789d6683a79c91e7b Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Sat, 5 Apr 2014 23:21:47 +0900 Subject: [PATCH 093/120] Apply binary PF* commands to BinaryJedis, BinaryShardedJedis * Apply binary PF* commands to BinaryJedis, BinaryShardedJedis * binary PF* commands to interface ** pfadd / pfcount : BinaryJedisCommands ** pfmerge : MultiKeyBinaryCommands --- .../java/redis/clients/jedis/BinaryJedis.java | 21 +++++++ .../clients/jedis/BinaryJedisCommands.java | 4 ++ .../clients/jedis/BinaryShardedJedis.java | 13 ++++ .../clients/jedis/MultiKeyBinaryCommands.java | 2 + .../commands/HyperLogLogCommandsTest.java | 60 +++++++++++++++++++ 5 files changed, 100 insertions(+) diff --git a/src/main/java/redis/clients/jedis/BinaryJedis.java b/src/main/java/redis/clients/jedis/BinaryJedis.java index eba466f..bed597f 100644 --- a/src/main/java/redis/clients/jedis/BinaryJedis.java +++ b/src/main/java/redis/clients/jedis/BinaryJedis.java @@ -3417,4 +3417,25 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, return client.getIntegerReply(); } + @Override + public Long pfadd(final byte[] key, final byte[]... elements) { + checkIsInMulti(); + client.pfadd(key, elements); + return client.getIntegerReply(); + } + + @Override + public long pfcount(final byte[] key) { + checkIsInMulti(); + client.pfcount(key); + return client.getIntegerReply(); + } + + @Override + public String pfmerge(final byte[] destkey, final byte[]... sourcekeys) { + checkIsInMulti(); + client.pfmerge(destkey, sourcekeys); + return client.getStatusCodeReply(); + } + } diff --git a/src/main/java/redis/clients/jedis/BinaryJedisCommands.java b/src/main/java/redis/clients/jedis/BinaryJedisCommands.java index b229f97..f22428b 100644 --- a/src/main/java/redis/clients/jedis/BinaryJedisCommands.java +++ b/src/main/java/redis/clients/jedis/BinaryJedisCommands.java @@ -211,4 +211,8 @@ public interface BinaryJedisCommands { Long bitcount(final byte[] key); Long bitcount(final byte[] key, long start, long end); + + Long pfadd(final byte[] key, final byte[]... elements); + + long pfcount(final byte[] key); } diff --git a/src/main/java/redis/clients/jedis/BinaryShardedJedis.java b/src/main/java/redis/clients/jedis/BinaryShardedJedis.java index 5895f20..b0dd05c 100644 --- a/src/main/java/redis/clients/jedis/BinaryShardedJedis.java +++ b/src/main/java/redis/clients/jedis/BinaryShardedJedis.java @@ -569,4 +569,17 @@ public class BinaryShardedJedis extends Sharded Jedis j = getShard(key); return j.bitcount(key, start, end); } + + @Override + public Long pfadd(final byte[] key, final byte[]... elements) { + Jedis j = getShard(key); + return j.pfadd(key, elements); + } + + @Override + public long pfcount(final byte[] key) { + Jedis j = getShard(key); + return j.pfcount(key); + } + } \ No newline at end of file diff --git a/src/main/java/redis/clients/jedis/MultiKeyBinaryCommands.java b/src/main/java/redis/clients/jedis/MultiKeyBinaryCommands.java index e6ea8fd..8b54d90 100644 --- a/src/main/java/redis/clients/jedis/MultiKeyBinaryCommands.java +++ b/src/main/java/redis/clients/jedis/MultiKeyBinaryCommands.java @@ -69,4 +69,6 @@ public interface MultiKeyBinaryCommands { byte[] randomBinaryKey(); Long bitop(BitOP op, final byte[] destKey, byte[]... srcKeys); + + String pfmerge(final byte[] destkey, final byte[]... sourcekeys); } diff --git a/src/test/java/redis/clients/jedis/tests/commands/HyperLogLogCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/HyperLogLogCommandsTest.java index e14c59b..4eb7ed4 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/HyperLogLogCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/HyperLogLogCommandsTest.java @@ -2,6 +2,8 @@ package redis.clients.jedis.tests.commands; import org.junit.Test; +import redis.clients.util.SafeEncoder; + public class HyperLogLogCommandsTest extends JedisCommandTestBase { @@ -14,6 +16,19 @@ public class HyperLogLogCommandsTest extends JedisCommandTestBase { assertEquals(0, status); } + @Test + public void pfaddBinary() { + byte[] bFoo = SafeEncoder.encode("foo"); + byte[] bBar = SafeEncoder.encode("bar"); + byte[] bBar2 = SafeEncoder.encode("bar2"); + + long status = jedis.pfadd(bFoo, bBar, bBar2); + assertEquals(1, status); + + status = jedis.pfadd(bFoo, bBar, bBar2); + assertEquals(0, status); + } + @Test public void pfcount() { long status = jedis.pfadd("hll", "foo", "bar", "zap"); @@ -29,6 +44,26 @@ public class HyperLogLogCommandsTest extends JedisCommandTestBase { assertEquals(3, status); } + @Test + public void pfcountBinary() { + byte[] bHll = SafeEncoder.encode("hll"); + byte[] bFoo = SafeEncoder.encode("foo"); + byte[] bBar = SafeEncoder.encode("bar"); + byte[] bZap = SafeEncoder.encode("zap"); + + long status = jedis.pfadd(bHll, bFoo, bBar, bZap); + assertEquals(1, status); + + status = jedis.pfadd(bHll, bZap, bZap, bZap); + assertEquals(0, status); + + status = jedis.pfadd(bHll, bFoo, bBar); + assertEquals(0, status); + + status = jedis.pfcount(bHll); + assertEquals(3, status); + } + @Test public void pfmerge() { long status = jedis.pfadd("hll1", "foo", "bar", "zap", "a"); @@ -43,4 +78,29 @@ public class HyperLogLogCommandsTest extends JedisCommandTestBase { status = jedis.pfcount("hll3"); assertEquals(6, status); } + + @Test + public void pfmergeBinary() { + byte[] bHll1 = SafeEncoder.encode("hll1"); + byte[] bHll2 = SafeEncoder.encode("hll2"); + byte[] bHll3 = SafeEncoder.encode("hll3"); + byte[] bFoo = SafeEncoder.encode("foo"); + byte[] bBar = SafeEncoder.encode("bar"); + byte[] bZap = SafeEncoder.encode("zap"); + byte[] bA = SafeEncoder.encode("a"); + byte[] bB = SafeEncoder.encode("b"); + byte[] bC = SafeEncoder.encode("c"); + + long status = jedis.pfadd(bHll1, bFoo, bBar, bZap, bA); + assertEquals(1, status); + + status = jedis.pfadd(bHll2, bA, bB, bC, bFoo); + assertEquals(1, status); + + String mergeStatus = jedis.pfmerge(bHll3, bHll1, bHll2); + assertEquals("OK", mergeStatus); + + status = jedis.pfcount("hll3"); + assertEquals(6, status); + } } \ No newline at end of file From c2cf79c97273470c76a493d8e53aae6b0962b5ad Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Sat, 5 Apr 2014 23:48:49 +0900 Subject: [PATCH 094/120] Apply PF* (string, binary) commands to Pipeline * Apply PF* (string, binary) commands to Pipeline * PF* Pipeline (string, binary) commands to interface ** pfadd / pfcount : BinaryRedisPipeline, RedisPipeline ** pfmerge : MultiKeyBinaryRedisPipeline, MultiKeyCommandsPipeline --- .../redis/clients/jedis/BinaryClient.java | 4 ++-- .../clients/jedis/BinaryRedisPipeline.java | 4 ++++ .../clients/jedis/JedisClusterCommand.java | 1 - .../jedis/MultiKeyBinaryRedisPipeline.java | 2 ++ .../jedis/MultiKeyCommandsPipeline.java | 2 ++ .../clients/jedis/MultiKeyPipelineBase.java | 12 ++++++++++ .../java/redis/clients/jedis/Pipeline.java | 2 +- .../redis/clients/jedis/PipelineBase.java | 24 +++++++++++++++++++ .../redis/clients/jedis/RedisPipeline.java | 4 ++++ 9 files changed, 51 insertions(+), 4 deletions(-) diff --git a/src/main/java/redis/clients/jedis/BinaryClient.java b/src/main/java/redis/clients/jedis/BinaryClient.java index bbd0f8f..b1aaa96 100644 --- a/src/main/java/redis/clients/jedis/BinaryClient.java +++ b/src/main/java/redis/clients/jedis/BinaryClient.java @@ -1261,7 +1261,7 @@ public class BinaryClient extends Connection { public void pfcount(final byte[] key) { sendCommand(PFCOUNT, key); } - public void pfmerge(final byte[] deskey, final byte[]... sourcekeys) { - sendCommand(PFMERGE, joinParameters(deskey, sourcekeys)); + public void pfmerge(final byte[] destkey, final byte[]... sourcekeys) { + sendCommand(PFMERGE, joinParameters(destkey, sourcekeys)); } } diff --git a/src/main/java/redis/clients/jedis/BinaryRedisPipeline.java b/src/main/java/redis/clients/jedis/BinaryRedisPipeline.java index 73037b7..5ce2ca5 100644 --- a/src/main/java/redis/clients/jedis/BinaryRedisPipeline.java +++ b/src/main/java/redis/clients/jedis/BinaryRedisPipeline.java @@ -210,4 +210,8 @@ public interface BinaryRedisPipeline { Response bitcount(byte[] key); Response bitcount(byte[] key, long start, long end); + + Response pfadd(final byte[] key, final byte[]... elements); + + Response pfcount(final byte[] key); } diff --git a/src/main/java/redis/clients/jedis/JedisClusterCommand.java b/src/main/java/redis/clients/jedis/JedisClusterCommand.java index c1be912..051d5cd 100644 --- a/src/main/java/redis/clients/jedis/JedisClusterCommand.java +++ b/src/main/java/redis/clients/jedis/JedisClusterCommand.java @@ -4,7 +4,6 @@ import redis.clients.jedis.exceptions.JedisAskDataException; import redis.clients.jedis.exceptions.JedisClusterException; import redis.clients.jedis.exceptions.JedisClusterMaxRedirectionsException; import redis.clients.jedis.exceptions.JedisConnectionException; -import redis.clients.jedis.exceptions.JedisException; import redis.clients.jedis.exceptions.JedisMovedDataException; import redis.clients.jedis.exceptions.JedisRedirectionException; import redis.clients.util.JedisClusterCRC16; diff --git a/src/main/java/redis/clients/jedis/MultiKeyBinaryRedisPipeline.java b/src/main/java/redis/clients/jedis/MultiKeyBinaryRedisPipeline.java index fd71016..90bd8ca 100644 --- a/src/main/java/redis/clients/jedis/MultiKeyBinaryRedisPipeline.java +++ b/src/main/java/redis/clients/jedis/MultiKeyBinaryRedisPipeline.java @@ -65,4 +65,6 @@ public interface MultiKeyBinaryRedisPipeline { Response randomKeyBinary(); Response bitop(BitOP op, final byte[] destKey, byte[]... srcKeys); + + Response pfmerge(final byte[] destkey, final byte[]... sourcekeys); } diff --git a/src/main/java/redis/clients/jedis/MultiKeyCommandsPipeline.java b/src/main/java/redis/clients/jedis/MultiKeyCommandsPipeline.java index 92c8d5a..71f00d1 100644 --- a/src/main/java/redis/clients/jedis/MultiKeyCommandsPipeline.java +++ b/src/main/java/redis/clients/jedis/MultiKeyCommandsPipeline.java @@ -64,4 +64,6 @@ public interface MultiKeyCommandsPipeline { Response randomKey(); Response bitop(BitOP op, final String destKey, String... srcKeys); + + Response pfmerge(final String destkey, final String... sourcekeys); } diff --git a/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java b/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java index fa7ae6e..f5a953f 100644 --- a/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java +++ b/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java @@ -446,4 +446,16 @@ abstract class MultiKeyPipelineBase extends PipelineBase implements client.clusterSetSlotImporting(slot, nodeId); return getResponse(BuilderFactory.STRING); } + + @Override + public Response pfmerge(byte[] destkey, byte[]... sourcekeys) { + client.pfmerge(destkey, sourcekeys); + return getResponse(BuilderFactory.STRING); + } + + @Override + public Response pfmerge(String destkey, String... sourcekeys) { + client.pfmerge(destkey, sourcekeys); + return getResponse(BuilderFactory.STRING); + } } diff --git a/src/main/java/redis/clients/jedis/Pipeline.java b/src/main/java/redis/clients/jedis/Pipeline.java index 2687f84..678f6a6 100755 --- a/src/main/java/redis/clients/jedis/Pipeline.java +++ b/src/main/java/redis/clients/jedis/Pipeline.java @@ -124,5 +124,5 @@ public class Pipeline extends MultiKeyPipelineBase { currentMulti = new MultiResponseBuilder(); return response; } - + } diff --git a/src/main/java/redis/clients/jedis/PipelineBase.java b/src/main/java/redis/clients/jedis/PipelineBase.java index 3183ba1..24046eb 100644 --- a/src/main/java/redis/clients/jedis/PipelineBase.java +++ b/src/main/java/redis/clients/jedis/PipelineBase.java @@ -1204,4 +1204,28 @@ abstract class PipelineBase extends Queable implements BinaryRedisPipeline, return getResponse(BuilderFactory.STRING); } + @Override + public Response pfadd(byte[] key, byte[]... elements) { + getClient(key).pfadd(key, elements); + return getResponse(BuilderFactory.LONG); + } + + @Override + public Response pfcount(byte[] key) { + getClient(key).pfcount(key); + return getResponse(BuilderFactory.LONG); + } + + @Override + public Response pfadd(String key, String... elements) { + getClient(key).pfadd(key, elements); + return getResponse(BuilderFactory.LONG); + } + + @Override + public Response pfcount(String key) { + getClient(key).pfcount(key); + return getResponse(BuilderFactory.LONG); + } + } diff --git a/src/main/java/redis/clients/jedis/RedisPipeline.java b/src/main/java/redis/clients/jedis/RedisPipeline.java index bb5226c..6e36d10 100644 --- a/src/main/java/redis/clients/jedis/RedisPipeline.java +++ b/src/main/java/redis/clients/jedis/RedisPipeline.java @@ -188,4 +188,8 @@ public interface RedisPipeline { Response bitcount(String key); Response bitcount(String key, long start, long end); + + Response pfadd(final String key, final String... elements); + + Response pfcount(final String key); } From 986acc8c9e334bc8d0b36215d4eb1c6ef015a77c Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Sun, 6 Apr 2014 00:19:16 +0900 Subject: [PATCH 095/120] Revert "Revert "Add support for HLL"" This reverts commit ac53759f9706b52184963e98af11d2e44bfb1297. Sorry for double reverting, I should revert "merged commit", not origin commit Conflicts: src/main/java/redis/clients/jedis/BinaryClient.java src/main/java/redis/clients/jedis/Jedis.java src/test/java/redis/clients/jedis/tests/commands/HyperLogLogCommandsTest.java --- src/main/java/redis/clients/jedis/BinaryClient.java | 3 ++- src/main/java/redis/clients/jedis/Client.java | 12 ++++++++++++ src/main/java/redis/clients/jedis/Protocol.java | 2 +- .../tests/commands/HyperLogLogCommandsTest.java | 3 +-- 4 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/main/java/redis/clients/jedis/BinaryClient.java b/src/main/java/redis/clients/jedis/BinaryClient.java index 9b2cce6..1537293 100644 --- a/src/main/java/redis/clients/jedis/BinaryClient.java +++ b/src/main/java/redis/clients/jedis/BinaryClient.java @@ -320,7 +320,7 @@ public class BinaryClient extends Connection { public void sadd(final byte[] key, final byte[]... members) { sendCommand(SADD, joinParameters(key, members)); } - + public void smembers(final byte[] key) { sendCommand(SMEMBERS, key); } @@ -1261,6 +1261,7 @@ public class BinaryClient extends Connection { public void pfcount(final byte[] key) { sendCommand(PFCOUNT, key); } + public void pfmerge(final byte[] destkey, final byte[]... sourcekeys) { sendCommand(PFMERGE, joinParameters(destkey, sourcekeys)); } diff --git a/src/main/java/redis/clients/jedis/Client.java b/src/main/java/redis/clients/jedis/Client.java index 64f6f5c..f6b9529 100644 --- a/src/main/java/redis/clients/jedis/Client.java +++ b/src/main/java/redis/clients/jedis/Client.java @@ -951,4 +951,16 @@ public class Client extends BinaryClient implements Commands { cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot), Protocol.CLUSTER_SETSLOT_IMPORTING, nodeId); } + + public void pfadd(String key, final String... elements) { + pfadd(SafeEncoder.encode(key), SafeEncoder.encodeMany(elements)); + } + + public void pfcount(final String key) { + pfcount(SafeEncoder.encode(key)); + } + + public void pfmerge(final String destkey, final String... sourcekeys) { + pfmerge(SafeEncoder.encode(destkey), SafeEncoder.encodeMany(sourcekeys)); + } } diff --git a/src/main/java/redis/clients/jedis/Protocol.java b/src/main/java/redis/clients/jedis/Protocol.java index 681bc56..5ceccaa 100644 --- a/src/main/java/redis/clients/jedis/Protocol.java +++ b/src/main/java/redis/clients/jedis/Protocol.java @@ -208,7 +208,7 @@ public final class Protocol { } public static enum Command { - PING, SET, GET, QUIT, EXISTS, DEL, TYPE, FLUSHDB, KEYS, RANDOMKEY, RENAME, RENAMENX, RENAMEX, DBSIZE, EXPIRE, EXPIREAT, TTL, SELECT, MOVE, FLUSHALL, GETSET, MGET, SETNX, SETEX, MSET, MSETNX, DECRBY, DECR, INCRBY, INCR, APPEND, SUBSTR, HSET, HGET, HSETNX, HMSET, HMGET, HINCRBY, HEXISTS, HDEL, HLEN, HKEYS, HVALS, HGETALL, RPUSH, LPUSH, LLEN, LRANGE, LTRIM, LINDEX, LSET, LREM, LPOP, RPOP, RPOPLPUSH, SADD, SMEMBERS, SREM, SPOP, SMOVE, SCARD, SISMEMBER, SINTER, SINTERSTORE, SUNION, SUNIONSTORE, SDIFF, SDIFFSTORE, SRANDMEMBER, ZADD, ZRANGE, ZREM, ZINCRBY, ZRANK, ZREVRANK, ZREVRANGE, ZCARD, ZSCORE, MULTI, DISCARD, EXEC, WATCH, UNWATCH, SORT, BLPOP, BRPOP, AUTH, SUBSCRIBE, PUBLISH, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, PUBSUB, ZCOUNT, ZRANGEBYSCORE, ZREVRANGEBYSCORE, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZUNIONSTORE, ZINTERSTORE, SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE, SHUTDOWN, INFO, MONITOR, SLAVEOF, CONFIG, STRLEN, SYNC, LPUSHX, PERSIST, RPUSHX, ECHO, LINSERT, DEBUG, BRPOPLPUSH, SETBIT, GETBIT, SETRANGE, GETRANGE, EVAL, EVALSHA, SCRIPT, SLOWLOG, OBJECT, BITCOUNT, BITOP, SENTINEL, DUMP, RESTORE, PEXPIRE, PEXPIREAT, PTTL, INCRBYFLOAT, PSETEX, CLIENT, TIME, MIGRATE, HINCRBYFLOAT, SCAN, HSCAN, SSCAN, ZSCAN, WAIT, CLUSTER, ASKING; + PING, SET, GET, QUIT, EXISTS, DEL, TYPE, FLUSHDB, KEYS, RANDOMKEY, RENAME, RENAMENX, RENAMEX, DBSIZE, EXPIRE, EXPIREAT, TTL, SELECT, MOVE, FLUSHALL, GETSET, MGET, SETNX, SETEX, MSET, MSETNX, DECRBY, DECR, INCRBY, INCR, APPEND, SUBSTR, HSET, HGET, HSETNX, HMSET, HMGET, HINCRBY, HEXISTS, HDEL, HLEN, HKEYS, HVALS, HGETALL, RPUSH, LPUSH, LLEN, LRANGE, LTRIM, LINDEX, LSET, LREM, LPOP, RPOP, RPOPLPUSH, SADD, SMEMBERS, SREM, SPOP, SMOVE, SCARD, SISMEMBER, SINTER, SINTERSTORE, SUNION, SUNIONSTORE, SDIFF, SDIFFSTORE, SRANDMEMBER, ZADD, ZRANGE, ZREM, ZINCRBY, ZRANK, ZREVRANK, ZREVRANGE, ZCARD, ZSCORE, MULTI, DISCARD, EXEC, WATCH, UNWATCH, SORT, BLPOP, BRPOP, AUTH, SUBSCRIBE, PUBLISH, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, PUBSUB, ZCOUNT, ZRANGEBYSCORE, ZREVRANGEBYSCORE, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZUNIONSTORE, ZINTERSTORE, SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE, SHUTDOWN, INFO, MONITOR, SLAVEOF, CONFIG, STRLEN, SYNC, LPUSHX, PERSIST, RPUSHX, ECHO, LINSERT, DEBUG, BRPOPLPUSH, SETBIT, GETBIT, SETRANGE, GETRANGE, EVAL, EVALSHA, SCRIPT, SLOWLOG, OBJECT, BITCOUNT, BITOP, SENTINEL, DUMP, RESTORE, PEXPIRE, PEXPIREAT, PTTL, INCRBYFLOAT, PSETEX, CLIENT, TIME, MIGRATE, HINCRBYFLOAT, SCAN, HSCAN, SSCAN, ZSCAN, WAIT, CLUSTER, ASKING, PFADD, PFCOUNT, PFMERGE; public final byte[] raw; diff --git a/src/test/java/redis/clients/jedis/tests/commands/HyperLogLogCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/HyperLogLogCommandsTest.java index 4eb7ed4..07a5021 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/HyperLogLogCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/HyperLogLogCommandsTest.java @@ -6,7 +6,6 @@ import redis.clients.util.SafeEncoder; public class HyperLogLogCommandsTest extends JedisCommandTestBase { - @Test public void pfadd() { long status = jedis.pfadd("foo", "a"); @@ -103,4 +102,4 @@ public class HyperLogLogCommandsTest extends JedisCommandTestBase { status = jedis.pfcount("hll3"); assertEquals(6, status); } -} \ No newline at end of file +} From 69de8d84d5c80330dfc3c9d759d92792940f5b14 Mon Sep 17 00:00:00 2001 From: mindwind Date: Thu, 24 Apr 2014 10:58:57 +0800 Subject: [PATCH 096/120] fix - ScanParams should be return this reference build pattern for chain code style --- src/main/java/redis/clients/jedis/ScanParams.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/redis/clients/jedis/ScanParams.java b/src/main/java/redis/clients/jedis/ScanParams.java index 980bb13..c9b1ca6 100644 --- a/src/main/java/redis/clients/jedis/ScanParams.java +++ b/src/main/java/redis/clients/jedis/ScanParams.java @@ -14,14 +14,16 @@ public class ScanParams { private List params = new ArrayList(); public final static String SCAN_POINTER_START = String.valueOf(0); - public void match(final String pattern) { + public ScanParams match(final String pattern) { params.add(MATCH.raw); params.add(SafeEncoder.encode(pattern)); + return this; } - public void count(final int count) { + public ScanParams count(final int count) { params.add(COUNT.raw); params.add(Protocol.toByteArray(count)); + return this; } public Collection getParams() { From bbc9078c3f848fe478fad575c607c5de35893f52 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Tue, 29 Apr 2014 00:05:49 +0900 Subject: [PATCH 097/120] Fix Pipeline NPE or sth with multi * followings are now throwing JedisDataException: it was uncontrolled or controlled by Redis itself ** exec without multi ** discard without multi ** multi within multi * updates unit test actually Redis returns ERR and we can pick, but Pipeline + multi has some complex sequence so it can just throw NPE without ERR --- .../java/redis/clients/jedis/Pipeline.java | 9 +++++++++ .../clients/jedis/tests/PipeliningTest.java | 20 +++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/src/main/java/redis/clients/jedis/Pipeline.java b/src/main/java/redis/clients/jedis/Pipeline.java index 2687f84..50fbe3f 100755 --- a/src/main/java/redis/clients/jedis/Pipeline.java +++ b/src/main/java/redis/clients/jedis/Pipeline.java @@ -104,12 +104,18 @@ public class Pipeline extends MultiKeyPipelineBase { } public Response discard() { + if (currentMulti == null) + throw new JedisDataException("DISCARD without MULTI"); + client.discard(); currentMulti = null; return getResponse(BuilderFactory.STRING); } public Response> exec() { + if (currentMulti == null) + throw new JedisDataException("EXEC without MULTI"); + client.exec(); Response> response = super.getResponse(currentMulti); currentMulti.setResponseDependency(response); @@ -118,6 +124,9 @@ public class Pipeline extends MultiKeyPipelineBase { } public Response multi() { + if (currentMulti != null) + throw new JedisDataException("MULTI calls can not be nested"); + client.multi(); Response response = getResponse(BuilderFactory.STRING); // Expecting // OK diff --git a/src/test/java/redis/clients/jedis/tests/PipeliningTest.java b/src/test/java/redis/clients/jedis/tests/PipeliningTest.java index d3cddd0..29b2f86 100755 --- a/src/test/java/redis/clients/jedis/tests/PipeliningTest.java +++ b/src/test/java/redis/clients/jedis/tests/PipeliningTest.java @@ -272,6 +272,26 @@ public class PipeliningTest extends Assert { assertEquals("world", r3.get()); } + @Test(expected = JedisDataException.class) + public void pipelineExecShoudThrowJedisDataExceptionWhenNotInMulti() { + Pipeline pipeline = jedis.pipelined(); + pipeline.exec(); + } + + @Test(expected = JedisDataException.class) + public void pipelineDiscardShoudThrowJedisDataExceptionWhenNotInMulti() { + Pipeline pipeline = jedis.pipelined(); + pipeline.discard(); + } + + @Test(expected = JedisDataException.class) + public void pipelineMultiShoudThrowJedisDataExceptionWhenAlreadyInMulti() { + Pipeline pipeline = jedis.pipelined(); + pipeline.multi(); + pipeline.set("foo", "3"); + pipeline.multi(); + } + @Test public void testDiscardInPipeline() { Pipeline pipeline = jedis.pipelined(); From cd722e5a8283ff9f6c89bef232ee58010e82d218 Mon Sep 17 00:00:00 2001 From: Alok Singh Date: Mon, 28 Apr 2014 14:17:46 -0700 Subject: [PATCH 098/120] Add support for pfcount with multiple keys --- .../redis/clients/jedis/BinaryClient.java | 30 +++++++++---------- src/main/java/redis/clients/jedis/Client.java | 8 +++-- src/main/java/redis/clients/jedis/Jedis.java | 22 +++++++------- .../redis/clients/jedis/JedisCluster.java | 15 ++++++++-- .../redis/clients/jedis/JedisCommands.java | 2 ++ .../redis/clients/jedis/ShardedJedis.java | 13 ++++++-- .../commands/HyperLogLogCommandsTest.java | 25 ++++++++++++++++ 7 files changed, 82 insertions(+), 33 deletions(-) diff --git a/src/main/java/redis/clients/jedis/BinaryClient.java b/src/main/java/redis/clients/jedis/BinaryClient.java index 1537293..edb9274 100644 --- a/src/main/java/redis/clients/jedis/BinaryClient.java +++ b/src/main/java/redis/clients/jedis/BinaryClient.java @@ -1,26 +1,22 @@ package redis.clients.jedis; -import static redis.clients.jedis.Protocol.toByteArray; -import static redis.clients.jedis.Protocol.Command.*; -import static redis.clients.jedis.Protocol.Keyword.ENCODING; -import static redis.clients.jedis.Protocol.Keyword.IDLETIME; -import static redis.clients.jedis.Protocol.Keyword.LEN; -import static redis.clients.jedis.Protocol.Keyword.LIMIT; -import static redis.clients.jedis.Protocol.Keyword.NO; -import static redis.clients.jedis.Protocol.Keyword.ONE; -import static redis.clients.jedis.Protocol.Keyword.REFCOUNT; -import static redis.clients.jedis.Protocol.Keyword.RESET; -import static redis.clients.jedis.Protocol.Keyword.STORE; -import static redis.clients.jedis.Protocol.Keyword.WITHSCORES; +import redis.clients.jedis.Protocol.Command; +import redis.clients.jedis.Protocol.Keyword; +import redis.clients.util.SafeEncoder; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; -import redis.clients.jedis.Protocol.Command; -import redis.clients.jedis.Protocol.Keyword; -import redis.clients.util.SafeEncoder; +import static redis.clients.jedis.Protocol.Command.*; +import static redis.clients.jedis.Protocol.Command.EXISTS; +import static redis.clients.jedis.Protocol.Command.PSUBSCRIBE; +import static redis.clients.jedis.Protocol.Command.PUNSUBSCRIBE; +import static redis.clients.jedis.Protocol.Command.SUBSCRIBE; +import static redis.clients.jedis.Protocol.Command.UNSUBSCRIBE; +import static redis.clients.jedis.Protocol.Keyword.*; +import static redis.clients.jedis.Protocol.toByteArray; public class BinaryClient extends Connection { public enum LIST_POSITION { @@ -1262,6 +1258,10 @@ public class BinaryClient extends Connection { sendCommand(PFCOUNT, key); } + public void pfcount(final byte[]...keys) { + sendCommand(PFCOUNT, keys); + } + public void pfmerge(final byte[] destkey, final byte[]... sourcekeys) { sendCommand(PFMERGE, joinParameters(destkey, sourcekeys)); } diff --git a/src/main/java/redis/clients/jedis/Client.java b/src/main/java/redis/clients/jedis/Client.java index f6b9529..a424528 100644 --- a/src/main/java/redis/clients/jedis/Client.java +++ b/src/main/java/redis/clients/jedis/Client.java @@ -1,6 +1,6 @@ package redis.clients.jedis; -import static redis.clients.jedis.Protocol.toByteArray; +import redis.clients.util.SafeEncoder; import java.util.ArrayList; import java.util.HashMap; @@ -8,7 +8,7 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; -import redis.clients.util.SafeEncoder; +import static redis.clients.jedis.Protocol.toByteArray; public class Client extends BinaryClient implements Commands { public Client(final String host) { @@ -960,6 +960,10 @@ public class Client extends BinaryClient implements Commands { pfcount(SafeEncoder.encode(key)); } + public void pfcount(final String...keys) { + pfcount(SafeEncoder.encodeMany(keys)); + } + public void pfmerge(final String destkey, final String... sourcekeys) { pfmerge(SafeEncoder.encode(destkey), SafeEncoder.encodeMany(sourcekeys)); } diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index 8782fc9..29e53a2 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -1,20 +1,13 @@ package redis.clients.jedis; -import java.net.URI; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - import redis.clients.jedis.BinaryClient.LIST_POSITION; import redis.clients.util.SafeEncoder; import redis.clients.util.Slowlog; +import java.net.URI; +import java.util.*; +import java.util.Map.Entry; + public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommands, AdvancedJedisCommands, ScriptingCommands, BasicCommands, ClusterCommands { @@ -3425,6 +3418,13 @@ public class Jedis extends BinaryJedis implements JedisCommands, return client.getIntegerReply(); } + @Override + public long pfcount(String... keys) { + checkIsInMulti(); + client.pfcount(keys); + return client.getIntegerReply(); + } + public String pfmerge(final String destkey, final String... sourcekeys) { checkIsInMulti(); client.pfmerge(destkey, sourcekeys); diff --git a/src/main/java/redis/clients/jedis/JedisCluster.java b/src/main/java/redis/clients/jedis/JedisCluster.java index a359226..163f033 100644 --- a/src/main/java/redis/clients/jedis/JedisCluster.java +++ b/src/main/java/redis/clients/jedis/JedisCluster.java @@ -1,12 +1,12 @@ package redis.clients.jedis; +import redis.clients.jedis.BinaryClient.LIST_POSITION; + import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import redis.clients.jedis.BinaryClient.LIST_POSITION; - public class JedisCluster implements JedisCommands, BasicCommands { public static final short HASHSLOTS = 16384; private static final int DEFAULT_TIMEOUT = 1; @@ -1504,4 +1504,15 @@ public class JedisCluster implements JedisCommands, BasicCommands { }.run(key); } + @Override + public long pfcount(final String... keys) { + return new JedisClusterCommand(connectionHandler, + timeout, maxRedirections) { + @Override + public Long execute(Jedis connection) { + return connection.pfcount(keys); + } + }.run(keys[0]); + } + } diff --git a/src/main/java/redis/clients/jedis/JedisCommands.java b/src/main/java/redis/clients/jedis/JedisCommands.java index 5ce0121..52c1798 100644 --- a/src/main/java/redis/clients/jedis/JedisCommands.java +++ b/src/main/java/redis/clients/jedis/JedisCommands.java @@ -244,4 +244,6 @@ public interface JedisCommands { Long pfadd(final String key, final String... elements); long pfcount(final String key); + + long pfcount(final String...keys); } diff --git a/src/main/java/redis/clients/jedis/ShardedJedis.java b/src/main/java/redis/clients/jedis/ShardedJedis.java index 46110ad..fc78ddc 100644 --- a/src/main/java/redis/clients/jedis/ShardedJedis.java +++ b/src/main/java/redis/clients/jedis/ShardedJedis.java @@ -1,14 +1,14 @@ package redis.clients.jedis; +import redis.clients.jedis.BinaryClient.LIST_POSITION; +import redis.clients.util.Hashing; + import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Pattern; -import redis.clients.jedis.BinaryClient.LIST_POSITION; -import redis.clients.util.Hashing; - public class ShardedJedis extends BinaryShardedJedis implements JedisCommands { public ShardedJedis(List shards) { super(shards); @@ -582,4 +582,11 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands { Jedis j = getShard(key); return j.pfcount(key); } + + @Override + public long pfcount(String... keys) { + //The command will be sent to the first shard. + Jedis j = getShard(keys[0]); + return j.pfcount(keys); + } } diff --git a/src/test/java/redis/clients/jedis/tests/commands/HyperLogLogCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/HyperLogLogCommandsTest.java index 07a5021..0b25366 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/HyperLogLogCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/HyperLogLogCommandsTest.java @@ -43,6 +43,31 @@ public class HyperLogLogCommandsTest extends JedisCommandTestBase { assertEquals(3, status); } + @Test + public void pfcounts() { + long status = jedis.pfadd("hll_1", "foo", "bar", "zap"); + assertEquals(1, status); + status = jedis.pfadd("hll_2", "foo", "bar", "zap"); + assertEquals(1, status); + + status = jedis.pfadd("hll_3", "foo", "bar", "baz"); + assertEquals(1, status); + status = jedis.pfcount("hll_1"); + assertEquals(3, status); + status = jedis.pfcount("hll_2"); + assertEquals(3, status); + status = jedis.pfcount("hll_3"); + assertEquals(3, status); + + status = jedis.pfcount("hll_1", "hll_2"); + assertEquals(3, status); + + status = jedis.pfcount("hll_1", "hll_2", "hll_3"); + assertEquals(4, status); + + + } + @Test public void pfcountBinary() { byte[] bHll = SafeEncoder.encode("hll"); From b633024c112accec48c0fb485e2fa3124ff8db48 Mon Sep 17 00:00:00 2001 From: Alok Singh Date: Mon, 28 Apr 2014 16:41:09 -0700 Subject: [PATCH 099/120] Move pfcount(keys) method to multikey interfaces --- src/main/java/redis/clients/jedis/JedisCluster.java | 12 ------------ src/main/java/redis/clients/jedis/JedisCommands.java | 1 - .../java/redis/clients/jedis/MultiKeyCommands.java | 2 ++ .../clients/jedis/MultiKeyCommandsPipeline.java | 2 ++ .../redis/clients/jedis/MultiKeyPipelineBase.java | 6 ++++++ src/main/java/redis/clients/jedis/ShardedJedis.java | 7 ------- 6 files changed, 10 insertions(+), 20 deletions(-) diff --git a/src/main/java/redis/clients/jedis/JedisCluster.java b/src/main/java/redis/clients/jedis/JedisCluster.java index 163f033..5440e56 100644 --- a/src/main/java/redis/clients/jedis/JedisCluster.java +++ b/src/main/java/redis/clients/jedis/JedisCluster.java @@ -1503,16 +1503,4 @@ public class JedisCluster implements JedisCommands, BasicCommands { } }.run(key); } - - @Override - public long pfcount(final String... keys) { - return new JedisClusterCommand(connectionHandler, - timeout, maxRedirections) { - @Override - public Long execute(Jedis connection) { - return connection.pfcount(keys); - } - }.run(keys[0]); - } - } diff --git a/src/main/java/redis/clients/jedis/JedisCommands.java b/src/main/java/redis/clients/jedis/JedisCommands.java index 52c1798..dd6d89c 100644 --- a/src/main/java/redis/clients/jedis/JedisCommands.java +++ b/src/main/java/redis/clients/jedis/JedisCommands.java @@ -245,5 +245,4 @@ public interface JedisCommands { long pfcount(final String key); - long pfcount(final String...keys); } diff --git a/src/main/java/redis/clients/jedis/MultiKeyCommands.java b/src/main/java/redis/clients/jedis/MultiKeyCommands.java index b829fca..3f91ea9 100644 --- a/src/main/java/redis/clients/jedis/MultiKeyCommands.java +++ b/src/main/java/redis/clients/jedis/MultiKeyCommands.java @@ -81,4 +81,6 @@ public interface MultiKeyCommands { ScanResult scan(final String cursor); String pfmerge(final String destkey, final String... sourcekeys); + + long pfcount(final String...keys); } diff --git a/src/main/java/redis/clients/jedis/MultiKeyCommandsPipeline.java b/src/main/java/redis/clients/jedis/MultiKeyCommandsPipeline.java index 71f00d1..e2de238 100644 --- a/src/main/java/redis/clients/jedis/MultiKeyCommandsPipeline.java +++ b/src/main/java/redis/clients/jedis/MultiKeyCommandsPipeline.java @@ -66,4 +66,6 @@ public interface MultiKeyCommandsPipeline { Response bitop(BitOP op, final String destKey, String... srcKeys); Response pfmerge(final String destkey, final String... sourcekeys); + + Response pfcount(final String...keys); } diff --git a/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java b/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java index f5a953f..7bffd38 100644 --- a/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java +++ b/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java @@ -458,4 +458,10 @@ abstract class MultiKeyPipelineBase extends PipelineBase implements client.pfmerge(destkey, sourcekeys); return getResponse(BuilderFactory.STRING); } + + @Override + public Response pfcount(String...keys) { + client.pfcount(keys); + return getResponse(BuilderFactory.LONG); + } } diff --git a/src/main/java/redis/clients/jedis/ShardedJedis.java b/src/main/java/redis/clients/jedis/ShardedJedis.java index fc78ddc..62a22da 100644 --- a/src/main/java/redis/clients/jedis/ShardedJedis.java +++ b/src/main/java/redis/clients/jedis/ShardedJedis.java @@ -582,11 +582,4 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands { Jedis j = getShard(key); return j.pfcount(key); } - - @Override - public long pfcount(String... keys) { - //The command will be sent to the first shard. - Jedis j = getShard(keys[0]); - return j.pfcount(keys); - } } From d9d039d06087c19c68aa8c0e64bc902d150260d2 Mon Sep 17 00:00:00 2001 From: Alok Singh Date: Tue, 29 Apr 2014 08:58:15 -0700 Subject: [PATCH 100/120] Added pfcount(keys) to BinaryJedis interfaces --- src/main/java/redis/clients/jedis/BinaryJedis.java | 7 +++++++ .../java/redis/clients/jedis/MultiKeyBinaryCommands.java | 2 ++ 2 files changed, 9 insertions(+) diff --git a/src/main/java/redis/clients/jedis/BinaryJedis.java b/src/main/java/redis/clients/jedis/BinaryJedis.java index bed597f..9066f53 100644 --- a/src/main/java/redis/clients/jedis/BinaryJedis.java +++ b/src/main/java/redis/clients/jedis/BinaryJedis.java @@ -3438,4 +3438,11 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, return client.getStatusCodeReply(); } + @Override + public Long pfcount(byte[]... keys) { + checkIsInMulti(); + client.pfcount(keys); + return client.getIntegerReply(); + } + } diff --git a/src/main/java/redis/clients/jedis/MultiKeyBinaryCommands.java b/src/main/java/redis/clients/jedis/MultiKeyBinaryCommands.java index 8b54d90..186d822 100644 --- a/src/main/java/redis/clients/jedis/MultiKeyBinaryCommands.java +++ b/src/main/java/redis/clients/jedis/MultiKeyBinaryCommands.java @@ -71,4 +71,6 @@ public interface MultiKeyBinaryCommands { Long bitop(BitOP op, final byte[] destKey, byte[]... srcKeys); String pfmerge(final byte[] destkey, final byte[]... sourcekeys); + + Long pfcount(byte[]... keys); } From 6485a7ec08c5293c5c0e0ddb256213d122798b88 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Wed, 30 Apr 2014 08:17:59 +0900 Subject: [PATCH 101/120] Add Binary Pipeline version of pfcount --- .../redis/clients/jedis/MultiKeyBinaryRedisPipeline.java | 2 ++ src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java | 6 ++++++ 2 files changed, 8 insertions(+) diff --git a/src/main/java/redis/clients/jedis/MultiKeyBinaryRedisPipeline.java b/src/main/java/redis/clients/jedis/MultiKeyBinaryRedisPipeline.java index 90bd8ca..a3f8716 100644 --- a/src/main/java/redis/clients/jedis/MultiKeyBinaryRedisPipeline.java +++ b/src/main/java/redis/clients/jedis/MultiKeyBinaryRedisPipeline.java @@ -67,4 +67,6 @@ public interface MultiKeyBinaryRedisPipeline { Response bitop(BitOP op, final byte[] destKey, byte[]... srcKeys); Response pfmerge(final byte[] destkey, final byte[]... sourcekeys); + + Response pfcount(final byte[] ... keys); } diff --git a/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java b/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java index 7bffd38..9a14285 100644 --- a/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java +++ b/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java @@ -464,4 +464,10 @@ abstract class MultiKeyPipelineBase extends PipelineBase implements client.pfcount(keys); return getResponse(BuilderFactory.LONG); } + + @Override + public Response pfcount(final byte[] ... keys) { + client.pfcount(keys); + return getResponse(BuilderFactory.LONG); + } } From c63e901232a2c407cd5269c78b356ce5dc49503d Mon Sep 17 00:00:00 2001 From: PumpkinJack Date: Sat, 3 May 2014 17:25:10 +0800 Subject: [PATCH 102/120] add 'time()' method to MultiKeyPipellineBase --- src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java b/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java index fa7ae6e..45fe51e 100644 --- a/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java +++ b/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java @@ -367,6 +367,11 @@ abstract class MultiKeyPipelineBase extends PipelineBase implements client.info(); return getResponse(BuilderFactory.STRING); } + + public Response> time() { + client.time(); + return getResponse(BuilderFactory.STRING_LIST); + } public Response dbSize() { client.dbSize(); From e17a312d92df250ed4bf24e4afeff9374be5aa09 Mon Sep 17 00:00:00 2001 From: PumpkinJack Date: Sun, 4 May 2014 15:03:18 +0800 Subject: [PATCH 103/120] To solving the error (at Pool.java 35 : The type org.apache.commons.pool2.impl.AbandonedConfig cannot be resolved. It is indirectly referenced from required .class files), we update common-pool2 (2.0 -> 2.2) --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 1be71dd..7ce7b4b 100644 --- a/pom.xml +++ b/pom.xml @@ -62,7 +62,7 @@ org.apache.commons commons-pool2 - 2.0 + 2.2 jar compile From 942fc1d77bec65837e5b9b4becb8d13765f523b3 Mon Sep 17 00:00:00 2001 From: PumpkinJack Date: Sun, 4 May 2014 15:15:21 +0800 Subject: [PATCH 104/120] add the time() method --- src/main/java/redis/clients/jedis/BasicRedisPipeline.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/redis/clients/jedis/BasicRedisPipeline.java b/src/main/java/redis/clients/jedis/BasicRedisPipeline.java index bec6e8c..c56a972 100644 --- a/src/main/java/redis/clients/jedis/BasicRedisPipeline.java +++ b/src/main/java/redis/clients/jedis/BasicRedisPipeline.java @@ -1,5 +1,7 @@ package redis.clients.jedis; +import java.util.List; + /** * Pipelined responses for all of the low level, non key related commands */ @@ -24,6 +26,8 @@ public interface BasicRedisPipeline { Response flushAll(); Response info(); + + Response> time(); Response dbSize(); From 4b07966e748ce25699fa791c5d53f9e28f1b3e84 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Tue, 20 May 2014 11:42:16 -0300 Subject: [PATCH 105/120] Checks for buffer out of bounds before writing to the stream. Fixes #636 --- .../redis/clients/util/RedisOutputStream.java | 8 +++---- .../clients/jedis/tests/ProtocolTest.java | 23 +++++++++++++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/src/main/java/redis/clients/util/RedisOutputStream.java b/src/main/java/redis/clients/util/RedisOutputStream.java index 4dba859..dcec7fa 100644 --- a/src/main/java/redis/clients/util/RedisOutputStream.java +++ b/src/main/java/redis/clients/util/RedisOutputStream.java @@ -34,10 +34,10 @@ public final class RedisOutputStream extends FilterOutputStream { } public void write(final byte b) throws IOException { - buf[count++] = b; if (count == buf.length) { flushBuffer(); } + buf[count++] = b; } public void write(final byte[] b) throws IOException { @@ -63,10 +63,10 @@ public final class RedisOutputStream extends FilterOutputStream { final int size = in.length(); for (int i = 0; i != size; ++i) { - buf[count++] = (byte) in.charAt(i); if (count == buf.length) { flushBuffer(); } + buf[count++] = (byte) in.charAt(i); } writeCrLf(); @@ -111,19 +111,19 @@ public final class RedisOutputStream extends FilterOutputStream { char c = str.charAt(i); if (!(c < 0x80)) break; - buf[count++] = (byte) c; if (count == buf.length) { flushBuffer(); } + buf[count++] = (byte) c; } for (; i < strLen; i++) { char c = str.charAt(i); if (c < 0x80) { - buf[count++] = (byte) c; if (count == buf.length) { flushBuffer(); } + buf[count++] = (byte) c; } else if (c < 0x800) { if (2 >= buf.length - count) { flushBuffer(); diff --git a/src/test/java/redis/clients/jedis/tests/ProtocolTest.java b/src/test/java/redis/clients/jedis/tests/ProtocolTest.java index 504a66a..4245aae 100644 --- a/src/test/java/redis/clients/jedis/tests/ProtocolTest.java +++ b/src/test/java/redis/clients/jedis/tests/ProtocolTest.java @@ -4,6 +4,7 @@ import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.util.ArrayList; @@ -38,6 +39,28 @@ public class ProtocolTest extends JedisTestBase { assertEquals(expectedCommand, sb.toString()); } + + @Test(expected=IOException.class) + public void writeOverflow() throws IOException { + RedisOutputStream ros = new RedisOutputStream(new OutputStream() { + + @Override + public void write(int b) throws IOException { + throw new IOException("thrown exception"); + + } + }); + + ros.write(new byte[8191]); + + try { + ros.write((byte)'*'); + } catch (IOException ioe) {} + + + ros.write((byte)'*'); + + } @Test public void bulkReply() { From 7255a8cae173dc19f8250cca85bfec7e92306c02 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Wed, 21 May 2014 08:08:12 +0900 Subject: [PATCH 106/120] fix "cluster nodes" parse error when slot is in transition * extract cluster nodes info. parser from JedisClusterConnectionHandler * unit test for migrating slot included --- .../jedis/JedisClusterConnectionHandler.java | 90 ++++++++----------- .../clients/util/ClusterNodeInformation.java | 48 ++++++++++ .../util/ClusterNodeInformationParser.java | 81 +++++++++++++++++ ...JedisClusterNodeInformationParserTest.java | 63 +++++++++++++ 4 files changed, 227 insertions(+), 55 deletions(-) create mode 100644 src/main/java/redis/clients/util/ClusterNodeInformation.java create mode 100644 src/main/java/redis/clients/util/ClusterNodeInformationParser.java create mode 100644 src/test/java/redis/clients/jedis/tests/JedisClusterNodeInformationParserTest.java diff --git a/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java index 94f4c75..e6eb01f 100644 --- a/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java +++ b/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java @@ -1,13 +1,13 @@ package redis.clients.jedis; -import java.util.HashMap; -import java.util.Map; -import java.util.Random; -import java.util.Set; +import java.util.*; import redis.clients.jedis.exceptions.JedisConnectionException; +import redis.clients.util.ClusterNodeInformation; +import redis.clients.util.ClusterNodeInformationParser; public abstract class JedisClusterConnectionHandler { + public static ClusterNodeInformationParser nodeInfoParser = new ClusterNodeInformationParser(); protected Map nodes = new HashMap(); protected Map slots = new HashMap(); @@ -65,69 +65,40 @@ public abstract class JedisClusterConnectionHandler { setNodeIfNotExist(node); } } - + private void discoverClusterNodesAndSlots(Jedis jedis) { String localNodes = jedis.clusterNodes(); for (String nodeInfo : localNodes.split("\n")) { - HostAndPort node = getHostAndPortFromNodeLine(nodeInfo, jedis); - setNodeIfNotExist(node); - - JedisPool nodePool = nodes.get(getNodeKey(node)); - populateNodeSlots(nodeInfo, nodePool); - } - } - - private void setNodeIfNotExist(HostAndPort node) { - String nodeKey = getNodeKey(node); - if (nodes.containsKey(nodeKey)) - return; - - JedisPool nodePool = new JedisPool(node.getHost(), node.getPort()); - nodes.put(nodeKey, nodePool); - } + ClusterNodeInformation clusterNodeInfo = nodeInfoParser.parse( + nodeInfo, new HostAndPort(jedis.getClient().getHost(), + jedis.getClient().getPort())); - private void populateNodeSlots(String nodeInfo, JedisPool nodePool) { - String[] nodeInfoArray = nodeInfo.split(" "); - if (nodeInfoArray.length > 7) { - for (int i = 8; i < nodeInfoArray.length; i++) { - processSlot(nodeInfoArray[i], nodePool); - } + HostAndPort targetNode = clusterNodeInfo.getNode(); + setNodeIfNotExist(targetNode); + assignSlotsToNode(clusterNodeInfo.getAvailableSlots(), targetNode); } } - private void processSlot(String slot, JedisPool nodePool) { - if (slot.contains("-")) { - String[] slotRange = slot.split("-"); - for (int i = Integer.valueOf(slotRange[0]); i <= Integer - .valueOf(slotRange[1]); i++) { - slots.put(i, nodePool); - } - } else { - slots.put(Integer.valueOf(slot), nodePool); - } - } - - private HostAndPort getHostAndPortFromNodeLine(String nodeInfo, - Jedis currentConnection) { - String stringHostAndPort = nodeInfo.split(" ", 3)[1]; - if (":0".equals(stringHostAndPort)) { - return new HostAndPort(currentConnection.getClient().getHost(), - currentConnection.getClient().getPort()); - } - String[] arrayHostAndPort = stringHostAndPort.split(":"); - return new HostAndPort(arrayHostAndPort[0], - Integer.valueOf(arrayHostAndPort[1])); - } - public void assignSlotToNode(int slot, HostAndPort targetNode) { JedisPool targetPool = nodes.get(getNodeKey(targetNode)); - if (targetPool != null) { - slots.put(slot, targetPool); - } else { + if (targetPool == null) { setNodeIfNotExist(targetNode); - targetPool = nodes.get(getNodeKey(targetNode)); + } + slots.put(slot, targetPool); + } + + public void assignSlotsToNode(List targetSlots, + HostAndPort targetNode) { + JedisPool targetPool = nodes.get(getNodeKey(targetNode)); + + if (targetPool == null) { + setNodeIfNotExist(targetNode); + targetPool = nodes.get(getNodeKey(targetNode)); + } + + for (Integer slot : targetSlots) { slots.put(slot, targetPool); } } @@ -144,4 +115,13 @@ public abstract class JedisClusterConnectionHandler { protected String getNodeKey(Client client) { return client.getHost() + ":" + client.getPort(); } + + private void setNodeIfNotExist(HostAndPort node) { + String nodeKey = getNodeKey(node); + if (nodes.containsKey(nodeKey)) + return; + + JedisPool nodePool = new JedisPool(node.getHost(), node.getPort()); + nodes.put(nodeKey, nodePool); + } } diff --git a/src/main/java/redis/clients/util/ClusterNodeInformation.java b/src/main/java/redis/clients/util/ClusterNodeInformation.java new file mode 100644 index 0000000..a3833d0 --- /dev/null +++ b/src/main/java/redis/clients/util/ClusterNodeInformation.java @@ -0,0 +1,48 @@ +package redis.clients.util; + +import redis.clients.jedis.HostAndPort; + +import java.util.ArrayList; +import java.util.List; + +public class ClusterNodeInformation { + private HostAndPort node; + private List availableSlots; + private List slotsBeingImported; + private List slotsBeingMigrated; + + public ClusterNodeInformation(HostAndPort node) { + this.node = node; + this.availableSlots = new ArrayList(); + this.slotsBeingImported = new ArrayList(); + this.slotsBeingMigrated = new ArrayList(); + } + + public void addAvailableSlot(int slot) { + availableSlots.add(slot); + } + + public void addSlotBeingImported(int slot) { + slotsBeingImported.add(slot); + } + + public void addSlotBeingMigrated(int slot) { + slotsBeingMigrated.add(slot); + } + + public HostAndPort getNode() { + return node; + } + + public List getAvailableSlots() { + return availableSlots; + } + + public List getSlotsBeingImported() { + return slotsBeingImported; + } + + public List getSlotsBeingMigrated() { + return slotsBeingMigrated; + } +} diff --git a/src/main/java/redis/clients/util/ClusterNodeInformationParser.java b/src/main/java/redis/clients/util/ClusterNodeInformationParser.java new file mode 100644 index 0000000..995df6f --- /dev/null +++ b/src/main/java/redis/clients/util/ClusterNodeInformationParser.java @@ -0,0 +1,81 @@ +package redis.clients.util; + +import redis.clients.jedis.HostAndPort; + +public class ClusterNodeInformationParser { + private static final String HOST_MYSELF_IDENTIFIER = ":0"; + private static final String SLOT_IMPORT_IDENTIFIER = "-<-"; + private static final String SLOT_IN_TRANSITION_IDENTIFIER = "["; + public static final int SLOT_INFORMATIONS_START_INDEX = 8; + public static final int HOST_AND_PORT_INDEX = 1; + + public ClusterNodeInformation parse(String nodeInfo, HostAndPort current) { + String[] nodeInfoPartArray = nodeInfo.split(" "); + + HostAndPort node = getHostAndPortFromNodeLine(nodeInfoPartArray, + current); + ClusterNodeInformation info = new ClusterNodeInformation(node); + + if (nodeInfoPartArray.length >= SLOT_INFORMATIONS_START_INDEX) { + String[] slotInfoPartArray = extractSlotParts(nodeInfoPartArray); + fillSlotInformation(slotInfoPartArray, info); + } + + return info; + } + + private String[] extractSlotParts(String[] nodeInfoPartArray) { + String[] slotInfoPartArray = new String[nodeInfoPartArray.length + - SLOT_INFORMATIONS_START_INDEX]; + for (int i = SLOT_INFORMATIONS_START_INDEX; i < nodeInfoPartArray.length; i++) { + slotInfoPartArray[i - SLOT_INFORMATIONS_START_INDEX] = nodeInfoPartArray[i]; + } + return slotInfoPartArray; + } + + public HostAndPort getHostAndPortFromNodeLine(String[] nodeInfoPartArray, + HostAndPort current) { + String stringHostAndPort = nodeInfoPartArray[HOST_AND_PORT_INDEX]; + if (HOST_MYSELF_IDENTIFIER.equals(stringHostAndPort)) { + return current; + } + + String[] arrayHostAndPort = stringHostAndPort.split(":"); + return new HostAndPort(arrayHostAndPort[0], + Integer.valueOf(arrayHostAndPort[1])); + } + + private void fillSlotInformation(String[] slotInfoPartArray, + ClusterNodeInformation info) { + for (String slotRange : slotInfoPartArray) { + fillSlotInformationFromSlotRange(slotRange, info); + } + } + + private void fillSlotInformationFromSlotRange(String slotRange, + ClusterNodeInformation info) { + if (slotRange.startsWith(SLOT_IN_TRANSITION_IDENTIFIER)) { + // slot is in transition + int slot = Integer.parseInt(slotRange.substring(1).split("-")[0]); + + if (slotRange.contains(SLOT_IMPORT_IDENTIFIER)) { + // import + info.addSlotBeingImported(slot); + } else { + // migrate (->-) + info.addSlotBeingMigrated(slot); + } + } else if (slotRange.contains("-")) { + // slot range + String[] slotRangePart = slotRange.split("-"); + for (int slot = Integer.valueOf(slotRangePart[0]); slot <= Integer + .valueOf(slotRangePart[1]); slot++) { + info.addAvailableSlot(slot); + } + } else { + // single slot + info.addAvailableSlot(Integer.valueOf(slotRange)); + } + } + +} diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterNodeInformationParserTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterNodeInformationParserTest.java new file mode 100644 index 0000000..bc0fd42 --- /dev/null +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterNodeInformationParserTest.java @@ -0,0 +1,63 @@ +package redis.clients.jedis.tests; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import redis.clients.jedis.HostAndPort; +import redis.clients.util.ClusterNodeInformation; +import redis.clients.util.ClusterNodeInformationParser; + +public class JedisClusterNodeInformationParserTest extends Assert { + private ClusterNodeInformationParser parser; + + @Before + public void setUp() { + parser = new ClusterNodeInformationParser(); + } + + @Test + public void testParseNodeMyself() { + String nodeInfo = "9b0d2ab38ee31482c95fdb2c7847a0d40e88d518 :0 myself,master - 0 0 1 connected 0-5460"; + HostAndPort current = new HostAndPort("localhost", 7379); + ClusterNodeInformation clusterNodeInfo = parser + .parse(nodeInfo, current); + assertEquals(clusterNodeInfo.getNode(), current); + } + + @Test + public void testParseNormalState() { + String nodeInfo = "5f4a2236d00008fba7ac0dd24b95762b446767bd 192.168.0.3:7380 master - 0 1400598804016 2 connected 5461-10922"; + HostAndPort current = new HostAndPort("localhost", 7379); + ClusterNodeInformation clusterNodeInfo = parser + .parse(nodeInfo, current); + assertNotEquals(clusterNodeInfo.getNode(), current); + assertEquals(clusterNodeInfo.getNode(), new HostAndPort("192.168.0.3", + 7380)); + + for (int slot = 5461; slot <= 10922; slot++) { + assertTrue(clusterNodeInfo.getAvailableSlots().contains(slot)); + } + + assertTrue(clusterNodeInfo.getSlotsBeingImported().isEmpty()); + assertTrue(clusterNodeInfo.getSlotsBeingMigrated().isEmpty()); + } + + @Test + public void testParseSlotBeingMigrated() { + String nodeInfo = "5f4a2236d00008fba7ac0dd24b95762b446767bd :0 myself,master - 0 0 1 connected 0-5459 [5460->-5f4a2236d00008fba7ac0dd24b95762b446767bd] [5461-<-5f4a2236d00008fba7ac0dd24b95762b446767bd]"; + HostAndPort current = new HostAndPort("localhost", 7379); + ClusterNodeInformation clusterNodeInfo = parser + .parse(nodeInfo, current); + assertEquals(clusterNodeInfo.getNode(), current); + + for (int slot = 0; slot <= 5459; slot++) { + assertTrue(clusterNodeInfo.getAvailableSlots().contains(slot)); + } + + assertEquals(1, clusterNodeInfo.getSlotsBeingMigrated().size()); + assertTrue(clusterNodeInfo.getSlotsBeingMigrated().contains(5460)); + assertEquals(1, clusterNodeInfo.getSlotsBeingImported().size()); + assertTrue(clusterNodeInfo.getSlotsBeingImported().contains(5461)); + } + +} From 51de5f72abacbe544429fa24139ddfe8f57da71f Mon Sep 17 00:00:00 2001 From: Steve Parrington Date: Wed, 21 May 2014 16:09:47 +0100 Subject: [PATCH 107/120] Added Set NXXX and EXPX options for JedisCluster and ShardedJedis --- src/main/java/redis/clients/jedis/JedisCluster.java | 12 ++++++++++++ src/main/java/redis/clients/jedis/JedisCommands.java | 3 +++ src/main/java/redis/clients/jedis/ShardedJedis.java | 5 +++++ 3 files changed, 20 insertions(+) diff --git a/src/main/java/redis/clients/jedis/JedisCluster.java b/src/main/java/redis/clients/jedis/JedisCluster.java index 121bde8..def62ae 100644 --- a/src/main/java/redis/clients/jedis/JedisCluster.java +++ b/src/main/java/redis/clients/jedis/JedisCluster.java @@ -44,6 +44,18 @@ public class JedisCluster implements JedisCommands, BasicCommands { }.run(key); } + @Override + public String set(final String key, final String value, final String nxxx, + final String expx, final long time) { + return new JedisClusterCommand(connectionHandler, timeout, + maxRedirections) { + @Override + public String execute(Jedis connection) { + return connection.set(key, value, nxxx, expx, time); + } + }.run(key); + } + @Override public String get(final String key) { return new JedisClusterCommand(connectionHandler, timeout, diff --git a/src/main/java/redis/clients/jedis/JedisCommands.java b/src/main/java/redis/clients/jedis/JedisCommands.java index 5952bdb..7d1984d 100644 --- a/src/main/java/redis/clients/jedis/JedisCommands.java +++ b/src/main/java/redis/clients/jedis/JedisCommands.java @@ -10,6 +10,9 @@ import java.util.Set; public interface JedisCommands { String set(String key, String value); + String set(String key, String value, String nxxx, + String expx, long time); + String get(String key); Boolean exists(String key); diff --git a/src/main/java/redis/clients/jedis/ShardedJedis.java b/src/main/java/redis/clients/jedis/ShardedJedis.java index 7235cfe..e485c6c 100644 --- a/src/main/java/redis/clients/jedis/ShardedJedis.java +++ b/src/main/java/redis/clients/jedis/ShardedJedis.java @@ -32,6 +32,11 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands { return j.set(key, value); } + public String set(String key, String value, String nxxx, + String expx, long time) { + Jedis j = getShard(key); + return j.set(key, value, nxxx, expx, time); + } public String get(String key) { Jedis j = getShard(key); return j.get(key); From 742e83b1e030706a56c02f61aaa11d65a91d7bdc Mon Sep 17 00:00:00 2001 From: Steve Parrington Date: Thu, 22 May 2014 11:29:55 +0100 Subject: [PATCH 108/120] Added override annotation to ShardedJedis.set() --- src/main/java/redis/clients/jedis/ShardedJedis.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/redis/clients/jedis/ShardedJedis.java b/src/main/java/redis/clients/jedis/ShardedJedis.java index e485c6c..a44d330 100644 --- a/src/main/java/redis/clients/jedis/ShardedJedis.java +++ b/src/main/java/redis/clients/jedis/ShardedJedis.java @@ -32,11 +32,13 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands { return j.set(key, value); } + @Override public String set(String key, String value, String nxxx, String expx, long time) { Jedis j = getShard(key); return j.set(key, value, nxxx, expx, time); } + public String get(String key) { Jedis j = getShard(key); return j.get(key); From 6106f5bbe63e986b9c1ed92fdd8c8835e852e2af Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Sun, 25 May 2014 15:01:24 -0300 Subject: [PATCH 109/120] Manually merge #578 to master --- .../redis/clients/jedis/BinaryClient.java | 10 +- .../java/redis/clients/jedis/BinaryJedis.java | 9 ++ .../redis/clients/jedis/BitPosParams.java | 27 +++++ src/main/java/redis/clients/jedis/Client.java | 4 + src/main/java/redis/clients/jedis/Jedis.java | 9 ++ .../redis/clients/jedis/PipelineBase.java | 20 +++- .../java/redis/clients/jedis/Protocol.java | 2 +- .../jedis/tests/commands/BitCommandsTest.java | 107 ++++++++++++++++++ 8 files changed, 185 insertions(+), 3 deletions(-) create mode 100644 src/main/java/redis/clients/jedis/BitPosParams.java diff --git a/src/main/java/redis/clients/jedis/BinaryClient.java b/src/main/java/redis/clients/jedis/BinaryClient.java index edb9274..4c615f3 100644 --- a/src/main/java/redis/clients/jedis/BinaryClient.java +++ b/src/main/java/redis/clients/jedis/BinaryClient.java @@ -925,7 +925,15 @@ public class BinaryClient extends Connection { public void getbit(byte[] key, long offset) { sendCommand(GETBIT, key, toByteArray(offset)); } - + + public void bitpos(final byte[] key, final boolean value, final BitPosParams params) { + final List args = new ArrayList(); + args.add(key); + args.add(toByteArray(value)); + args.addAll(params.getParams()); + sendCommand(BITPOS, args.toArray(new byte[args.size()][])); + } + public void setrange(byte[] key, long offset, byte[] value) { sendCommand(SETRANGE, key, toByteArray(offset), value); } diff --git a/src/main/java/redis/clients/jedis/BinaryJedis.java b/src/main/java/redis/clients/jedis/BinaryJedis.java index 9066f53..4984990 100644 --- a/src/main/java/redis/clients/jedis/BinaryJedis.java +++ b/src/main/java/redis/clients/jedis/BinaryJedis.java @@ -3125,6 +3125,15 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, client.getbit(key, offset); return client.getIntegerReply() == 1; } + + public Long bitpos(final byte[] key, final boolean value) { + return bitpos(key, value, new BitPosParams()); + } + + public Long bitpos(final byte[] key, final boolean value, final BitPosParams params) { + client.bitpos(key, value, params); + return client.getIntegerReply(); + } public Long setrange(byte[] key, long offset, byte[] value) { client.setrange(key, offset, value); diff --git a/src/main/java/redis/clients/jedis/BitPosParams.java b/src/main/java/redis/clients/jedis/BitPosParams.java new file mode 100644 index 0000000..e480686 --- /dev/null +++ b/src/main/java/redis/clients/jedis/BitPosParams.java @@ -0,0 +1,27 @@ +package redis.clients.jedis; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +public class BitPosParams { + private List params = new ArrayList(); + + protected BitPosParams() { + } + + public BitPosParams(long start) { + params.add(Protocol.toByteArray(start)); + } + + public BitPosParams(long start, long end) { + this(start); + + params.add(Protocol.toByteArray(end)); + } + + public Collection getParams() { + return Collections.unmodifiableCollection(params); + } +} diff --git a/src/main/java/redis/clients/jedis/Client.java b/src/main/java/redis/clients/jedis/Client.java index a424528..3a7a845 100644 --- a/src/main/java/redis/clients/jedis/Client.java +++ b/src/main/java/redis/clients/jedis/Client.java @@ -628,6 +628,10 @@ public class Client extends BinaryClient implements Commands { public void getbit(String key, long offset) { getbit(SafeEncoder.encode(key), offset); } + + public void bitpos(final String key, final boolean value, final BitPosParams params) { + bitpos(SafeEncoder.encode(key), value, params); + } public void setrange(String key, long offset, String value) { setrange(SafeEncoder.encode(key), offset, SafeEncoder.encode(value)); diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index 29e53a2..e6614d8 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -2652,6 +2652,15 @@ public class Jedis extends BinaryJedis implements JedisCommands, client.getrange(key, startOffset, endOffset); return client.getBulkReply(); } + + public Long bitpos(final String key, final boolean value) { + return bitpos(key, value, new BitPosParams()); + } + + public Long bitpos(final String key, final boolean value, final BitPosParams params) { + client.bitpos(key, value, params); + return client.getIntegerReply(); + } /** * Retrieve the configuration of a running Redis server. Not all the diff --git a/src/main/java/redis/clients/jedis/PipelineBase.java b/src/main/java/redis/clients/jedis/PipelineBase.java index 24046eb..101020e 100644 --- a/src/main/java/redis/clients/jedis/PipelineBase.java +++ b/src/main/java/redis/clients/jedis/PipelineBase.java @@ -142,7 +142,25 @@ abstract class PipelineBase extends Queable implements BinaryRedisPipeline, getClient(key).getbit(key, offset); return getResponse(BuilderFactory.BOOLEAN); } - + + public Response bitpos(final String key, final boolean value) { + return bitpos(key, value, new BitPosParams()); + } + + public Response bitpos(final String key, final boolean value, final BitPosParams params) { + getClient(key).bitpos(key, value, params); + return getResponse(BuilderFactory.LONG); + } + + public Response bitpos(final byte[] key, final boolean value) { + return bitpos(key, value, new BitPosParams()); + } + + public Response bitpos(final byte[] key, final boolean value, final BitPosParams params) { + getClient(key).bitpos(key, value, params); + return getResponse(BuilderFactory.LONG); + } + public Response getrange(String key, long startOffset, long endOffset) { getClient(key).getrange(key, startOffset, endOffset); diff --git a/src/main/java/redis/clients/jedis/Protocol.java b/src/main/java/redis/clients/jedis/Protocol.java index 5ceccaa..485c10b 100644 --- a/src/main/java/redis/clients/jedis/Protocol.java +++ b/src/main/java/redis/clients/jedis/Protocol.java @@ -208,7 +208,7 @@ public final class Protocol { } public static enum Command { - PING, SET, GET, QUIT, EXISTS, DEL, TYPE, FLUSHDB, KEYS, RANDOMKEY, RENAME, RENAMENX, RENAMEX, DBSIZE, EXPIRE, EXPIREAT, TTL, SELECT, MOVE, FLUSHALL, GETSET, MGET, SETNX, SETEX, MSET, MSETNX, DECRBY, DECR, INCRBY, INCR, APPEND, SUBSTR, HSET, HGET, HSETNX, HMSET, HMGET, HINCRBY, HEXISTS, HDEL, HLEN, HKEYS, HVALS, HGETALL, RPUSH, LPUSH, LLEN, LRANGE, LTRIM, LINDEX, LSET, LREM, LPOP, RPOP, RPOPLPUSH, SADD, SMEMBERS, SREM, SPOP, SMOVE, SCARD, SISMEMBER, SINTER, SINTERSTORE, SUNION, SUNIONSTORE, SDIFF, SDIFFSTORE, SRANDMEMBER, ZADD, ZRANGE, ZREM, ZINCRBY, ZRANK, ZREVRANK, ZREVRANGE, ZCARD, ZSCORE, MULTI, DISCARD, EXEC, WATCH, UNWATCH, SORT, BLPOP, BRPOP, AUTH, SUBSCRIBE, PUBLISH, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, PUBSUB, ZCOUNT, ZRANGEBYSCORE, ZREVRANGEBYSCORE, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZUNIONSTORE, ZINTERSTORE, SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE, SHUTDOWN, INFO, MONITOR, SLAVEOF, CONFIG, STRLEN, SYNC, LPUSHX, PERSIST, RPUSHX, ECHO, LINSERT, DEBUG, BRPOPLPUSH, SETBIT, GETBIT, SETRANGE, GETRANGE, EVAL, EVALSHA, SCRIPT, SLOWLOG, OBJECT, BITCOUNT, BITOP, SENTINEL, DUMP, RESTORE, PEXPIRE, PEXPIREAT, PTTL, INCRBYFLOAT, PSETEX, CLIENT, TIME, MIGRATE, HINCRBYFLOAT, SCAN, HSCAN, SSCAN, ZSCAN, WAIT, CLUSTER, ASKING, PFADD, PFCOUNT, PFMERGE; + PING, SET, GET, QUIT, EXISTS, DEL, TYPE, FLUSHDB, KEYS, RANDOMKEY, RENAME, RENAMENX, RENAMEX, DBSIZE, EXPIRE, EXPIREAT, TTL, SELECT, MOVE, FLUSHALL, GETSET, MGET, SETNX, SETEX, MSET, MSETNX, DECRBY, DECR, INCRBY, INCR, APPEND, SUBSTR, HSET, HGET, HSETNX, HMSET, HMGET, HINCRBY, HEXISTS, HDEL, HLEN, HKEYS, HVALS, HGETALL, RPUSH, LPUSH, LLEN, LRANGE, LTRIM, LINDEX, LSET, LREM, LPOP, RPOP, RPOPLPUSH, SADD, SMEMBERS, SREM, SPOP, SMOVE, SCARD, SISMEMBER, SINTER, SINTERSTORE, SUNION, SUNIONSTORE, SDIFF, SDIFFSTORE, SRANDMEMBER, ZADD, ZRANGE, ZREM, ZINCRBY, ZRANK, ZREVRANK, ZREVRANGE, ZCARD, ZSCORE, MULTI, DISCARD, EXEC, WATCH, UNWATCH, SORT, BLPOP, BRPOP, AUTH, SUBSCRIBE, PUBLISH, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, PUBSUB, ZCOUNT, ZRANGEBYSCORE, ZREVRANGEBYSCORE, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZUNIONSTORE, ZINTERSTORE, SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE, SHUTDOWN, INFO, MONITOR, SLAVEOF, CONFIG, STRLEN, SYNC, LPUSHX, PERSIST, RPUSHX, ECHO, LINSERT, DEBUG, BRPOPLPUSH, SETBIT, GETBIT, BITPOS, SETRANGE, GETRANGE, EVAL, EVALSHA, SCRIPT, SLOWLOG, OBJECT, BITCOUNT, BITOP, SENTINEL, DUMP, RESTORE, PEXPIRE, PEXPIREAT, PTTL, INCRBYFLOAT, PSETEX, CLIENT, TIME, MIGRATE, HINCRBYFLOAT, SCAN, HSCAN, SSCAN, ZSCAN, WAIT, CLUSTER, ASKING, PFADD, PFCOUNT, PFMERGE; public final byte[] raw; diff --git a/src/test/java/redis/clients/jedis/tests/commands/BitCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/BitCommandsTest.java index fb14f21..b54ca95 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/BitCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/BitCommandsTest.java @@ -3,6 +3,8 @@ package redis.clients.jedis.tests.commands; import org.junit.Test; import redis.clients.jedis.BitOP; +import redis.clients.jedis.BitPosParams; +import redis.clients.jedis.Protocol; public class BitCommandsTest extends JedisCommandTestBase { @Test @@ -20,6 +22,111 @@ public class BitCommandsTest extends JedisCommandTestBase { assertTrue(bbit); } + @Test + public void bitpos() { + String foo = "foo"; + + jedis.set(foo, String.valueOf(0)); + + jedis.setbit(foo, 3, true); + jedis.setbit(foo, 7, true); + jedis.setbit(foo, 13, true); + jedis.setbit(foo, 39, true); + + /* + * byte: 0 1 2 3 4 + * bit: 00010001 / 00000100 / 00000000 / 00000000 / 00000001 + */ + long offset = jedis.bitpos(foo, true); + assertEquals(2, offset); + offset = jedis.bitpos(foo, false); + assertEquals(0, offset); + + offset = jedis.bitpos(foo, true, new BitPosParams(1)); + assertEquals(13, offset); + offset = jedis.bitpos(foo, false, new BitPosParams(1)); + assertEquals(8, offset); + + offset = jedis.bitpos(foo, true, new BitPosParams(2, 3)); + assertEquals(-1, offset); + offset = jedis.bitpos(foo, false, new BitPosParams(2, 3)); + assertEquals(16, offset); + + offset = jedis.bitpos(foo, true, new BitPosParams(3, 4)); + assertEquals(39, offset); + } + + @Test + public void bitposBinary() { + // binary + byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; + + jedis.set(bfoo, Protocol.toByteArray(0)); + + jedis.setbit(bfoo, 3, true); + jedis.setbit(bfoo, 7, true); + jedis.setbit(bfoo, 13, true); + jedis.setbit(bfoo, 39, true); + + /* + * byte: 0 1 2 3 4 + * bit: 00010001 / 00000100 / 00000000 / 00000000 / 00000001 + */ + long offset = jedis.bitpos(bfoo, true); + assertEquals(2, offset); + offset = jedis.bitpos(bfoo, false); + assertEquals(0, offset); + + offset = jedis.bitpos(bfoo, true, new BitPosParams(1)); + assertEquals(13, offset); + offset = jedis.bitpos(bfoo, false, new BitPosParams(1)); + assertEquals(8, offset); + + offset = jedis.bitpos(bfoo, true, new BitPosParams(2, 3)); + assertEquals(-1, offset); + offset = jedis.bitpos(bfoo, false, new BitPosParams(2, 3)); + assertEquals(16, offset); + + offset = jedis.bitpos(bfoo, true, new BitPosParams(3, 4)); + assertEquals(39, offset); + } + + @Test + public void bitposWithNoMatchingBitExist() { + String foo = "foo"; + + jedis.set(foo, String.valueOf(0)); + for (int idx = 0; idx < 8; idx++) { + jedis.setbit(foo, idx, true); + } + + /* + * byte: 0 + * bit: 11111111 + */ + long offset = jedis.bitpos(foo, false); + // offset should be last index + 1 + assertEquals(8, offset); + } + + @Test + public void bitposWithNoMatchingBitExistWithinRange() { + String foo = "foo"; + + jedis.set(foo, String.valueOf(0)); + for (int idx = 0; idx < 8 * 5; idx++) { + jedis.setbit(foo, idx, true); + } + + /* + * byte: 0 1 2 3 4 + * bit: 11111111 / 11111111 / 11111111 / 11111111 / 11111111 + */ + long offset = jedis.bitpos(foo, false, new BitPosParams(2, 3)); + // offset should be -1 + assertEquals(-1, offset); + } + @Test public void setAndgetrange() { jedis.set("key1", "Hello World"); From 1782aaeeb17d872b18e1dc0f06c1dca9492969da Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Sun, 25 May 2014 16:30:41 -0300 Subject: [PATCH 110/120] Manual merge of #581 --- Makefile | 48 ++++ pom.xml | 2 +- src/main/java/redis/clients/jedis/Client.java | 55 +++- .../redis/clients/jedis/ClusterCommands.java | 18 ++ src/main/java/redis/clients/jedis/Jedis.java | 55 ++++ .../java/redis/clients/jedis/Protocol.java | 9 + .../clients/jedis/tests/HostAndPortUtil.java | 4 + .../tests/JedisClusterReplicateTest.java | 167 ++++++++++++ .../clients/jedis/tests/JedisClusterTest.java | 242 ++++++++++++++++-- .../tests/utils/JedisClusterTestUtil.java | 70 +++++ 10 files changed, 634 insertions(+), 36 deletions(-) create mode 100644 src/test/java/redis/clients/jedis/tests/JedisClusterReplicateTest.java create mode 100644 src/test/java/redis/clients/jedis/tests/utils/JedisClusterTestUtil.java diff --git a/Makefile b/Makefile index 1ac2bb9..467541e 100644 --- a/Makefile +++ b/Makefile @@ -153,6 +153,42 @@ cluster-enabled yes cluster-config-file /tmp/redis_cluster_node3.conf endef +define REDIS_CLUSTER_NODE4_CONF +daemonize yes +port 7382 +cluster-node-timeout 50 +pidfile /tmp/redis_cluster_node4.pid +logfile /tmp/redis_cluster_node4.log +save "" +appendonly no +cluster-enabled yes +cluster-config-file /tmp/redis_cluster_node4.conf +endef + +define REDIS_CLUSTER_NODE5_CONF +daemonize yes +port 7383 +cluster-node-timeout 5000 +pidfile /tmp/redis_cluster_node5.pid +logfile /tmp/redis_cluster_node5.log +save "" +appendonly no +cluster-enabled yes +cluster-config-file /tmp/redis_cluster_node5.conf +endef + +define REDIS_CLUSTER_NODE6_CONF +daemonize yes +port 7384 +cluster-node-timeout 5000 +pidfile /tmp/redis_cluster_node6.pid +logfile /tmp/redis_cluster_node6.log +save "" +appendonly no +cluster-enabled yes +cluster-config-file /tmp/redis_cluster_node6.conf +endef + export REDIS1_CONF export REDIS2_CONF export REDIS3_CONF @@ -166,6 +202,9 @@ export REDIS_SENTINEL3 export REDIS_CLUSTER_NODE1_CONF export REDIS_CLUSTER_NODE2_CONF export REDIS_CLUSTER_NODE3_CONF +export REDIS_CLUSTER_NODE4_CONF +export REDIS_CLUSTER_NODE5_CONF +export REDIS_CLUSTER_NODE6_CONF start: cleanup echo "$$REDIS1_CONF" | redis-server - @@ -183,6 +222,9 @@ start: cleanup echo "$$REDIS_CLUSTER_NODE1_CONF" | redis-server - echo "$$REDIS_CLUSTER_NODE2_CONF" | redis-server - echo "$$REDIS_CLUSTER_NODE3_CONF" | redis-server - + echo "$$REDIS_CLUSTER_NODE4_CONF" | redis-server - + echo "$$REDIS_CLUSTER_NODE5_CONF" | redis-server - + echo "$$REDIS_CLUSTER_NODE6_CONF" | redis-server - cleanup: - rm -vf /tmp/redis_cluster_node*.conf 2>/dev/null @@ -202,12 +244,18 @@ stop: kill `cat /tmp/redis_cluster_node1.pid` || true kill `cat /tmp/redis_cluster_node2.pid` || true kill `cat /tmp/redis_cluster_node3.pid` || true + kill `cat /tmp/redis_cluster_node4.pid` || true + kill `cat /tmp/redis_cluster_node5.pid` || true + kill `cat /tmp/redis_cluster_node6.pid` || true rm -f /tmp/sentinel1.conf rm -f /tmp/sentinel2.conf rm -f /tmp/sentinel3.conf rm -f /tmp/redis_cluster_node1.conf rm -f /tmp/redis_cluster_node2.conf rm -f /tmp/redis_cluster_node3.conf + rm -f /tmp/redis_cluster_node4.conf + rm -f /tmp/redis_cluster_node5.conf + rm -f /tmp/redis_cluster_node6.conf test: make start diff --git a/pom.xml b/pom.xml index 1be71dd..ddc40c3 100644 --- a/pom.xml +++ b/pom.xml @@ -47,7 +47,7 @@ localhost:6379,localhost:6380,localhost:6381,localhost:6382,localhost:6383,localhost:6384,localhost:6385 localhost:26379,localhost:26380,localhost:26381 - localhost:7379,localhost:7380,localhost:7381 + localhost:7379,localhost:7380,localhost:7381,localhost:7382,localhost:7383,localhost:7384,localhost:7385 github diff --git a/src/main/java/redis/clients/jedis/Client.java b/src/main/java/redis/clients/jedis/Client.java index ddc8646..69054ef 100644 --- a/src/main/java/redis/clients/jedis/Client.java +++ b/src/main/java/redis/clients/jedis/Client.java @@ -1,6 +1,6 @@ package redis.clients.jedis; -import redis.clients.util.SafeEncoder; +import static redis.clients.jedis.Protocol.toByteArray; import java.util.ArrayList; import java.util.HashMap; @@ -8,7 +8,7 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; -import static redis.clients.jedis.Protocol.toByteArray; +import redis.clients.util.SafeEncoder; public class Client extends BinaryClient implements Commands { public Client(final String host) { @@ -173,10 +173,6 @@ public class Client extends BinaryClient implements Commands { hincrBy(SafeEncoder.encode(key), SafeEncoder.encode(field), value); } - public void hincrByFloat(final String key, final String field, final double value) { - hincrByFloat(SafeEncoder.encode(key), SafeEncoder.encode(field), value); - } - public void hexists(final String key, final String field) { hexists(SafeEncoder.encode(key), SafeEncoder.encode(field)); } @@ -632,11 +628,10 @@ public class Client extends BinaryClient implements Commands { public void getbit(String key, long offset) { getbit(SafeEncoder.encode(key), offset); } - + public void bitpos(final String key, final boolean value, final BitPosParams params) { bitpos(SafeEncoder.encode(key), value, params); } - public void setrange(String key, long offset, String value) { setrange(SafeEncoder.encode(key), offset, SafeEncoder.encode(value)); } @@ -789,7 +784,7 @@ public class Client extends BinaryClient implements Commands { public void pexpire(final String key, final int milliseconds) { pexpire(key, (long) milliseconds); } - + public void pexpire(final String key, final long milliseconds) { pexpire(SafeEncoder.encode(key), milliseconds); } @@ -840,6 +835,12 @@ public class Client extends BinaryClient implements Commands { destinationDb, timeout); } + public void hincrByFloat(final String key, final String field, + double increment) { + hincrByFloat(SafeEncoder.encode(key), SafeEncoder.encode(field), + increment); + } + @Deprecated /** * This method is deprecated due to bug (scan cursor should be unsigned long) @@ -974,4 +975,40 @@ public class Client extends BinaryClient implements Commands { public void pfmerge(final String destkey, final String... sourcekeys) { pfmerge(SafeEncoder.encode(destkey), SafeEncoder.encodeMany(sourcekeys)); } +public void clusterSetSlotStable(final int slot) { + cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot), + Protocol.CLUSTER_SETSLOT_STABLE); + } + + public void clusterForget(final String nodeId) { + cluster(Protocol.CLUSTER_FORGET, nodeId); + } + + public void clusterFlushSlots() { + cluster(Protocol.CLUSTER_FLUSHSLOT); + } + + public void clusterKeySlot(final String key) { + cluster(Protocol.CLUSTER_KEYSLOT, key); + } + + public void clusterCountKeysInSlot(final int slot) { + cluster(Protocol.CLUSTER_COUNTKEYINSLOT, String.valueOf(slot)); + } + + public void clusterSaveConfig() { + cluster(Protocol.CLUSTER_SAVECONFIG); + } + + public void clusterReplicate(final String nodeId) { + cluster(Protocol.CLUSTER_REPLICATE, nodeId); + } + + public void clusterSlaves(final String nodeId) { + cluster(Protocol.CLUSTER_SLAVES, nodeId); + } + + public void clusterFailover() { + cluster(Protocol.CLUSTER_FAILOVER); + } } diff --git a/src/main/java/redis/clients/jedis/ClusterCommands.java b/src/main/java/redis/clients/jedis/ClusterCommands.java index fff4533..b77069b 100644 --- a/src/main/java/redis/clients/jedis/ClusterCommands.java +++ b/src/main/java/redis/clients/jedis/ClusterCommands.java @@ -20,4 +20,22 @@ public interface ClusterCommands { String clusterSetSlotMigrating(final int slot, final String nodeId); String clusterSetSlotImporting(final int slot, final String nodeId); + + String clusterSetSlotStable(final int slot); + + String clusterForget(final String nodeId); + + String clusterFlushSlots(); + + Long clusterKeySlot(final String key); + + Long clusterCountKeysInSlot(final int slot); + + String clusterSaveConfig(); + + String clusterReplicate(final String nodeId); + + List clusterSlaves(final String nodeId); + + String clusterFailover(); } diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index 48968df..8e8a258 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -3136,6 +3136,7 @@ public class Jedis extends BinaryJedis implements JedisCommands, return client.getIntegerReply(); } + public String psetex(final String key, final int milliseconds, final String value) { checkIsInMulti(); @@ -3430,6 +3431,60 @@ public class Jedis extends BinaryJedis implements JedisCommands, client.clusterSetSlotImporting(slot, nodeId); return client.getStatusCodeReply(); } + + public String clusterSetSlotStable(final int slot) { + checkIsInMulti(); + client.clusterSetSlotStable(slot); + return client.getStatusCodeReply(); + } + + public String clusterForget(final String nodeId) { + checkIsInMulti(); + client.clusterForget(nodeId); + return client.getStatusCodeReply(); + } + + public String clusterFlushSlots() { + checkIsInMulti(); + client.clusterFlushSlots(); + return client.getStatusCodeReply(); + } + + public Long clusterKeySlot(final String key) { + checkIsInMulti(); + client.clusterKeySlot(key); + return client.getIntegerReply(); + } + + public Long clusterCountKeysInSlot(final int slot) { + checkIsInMulti(); + client.clusterCountKeysInSlot(slot); + return client.getIntegerReply(); + } + + public String clusterSaveConfig() { + checkIsInMulti(); + client.clusterSaveConfig(); + return client.getStatusCodeReply(); + } + + public String clusterReplicate(final String nodeId) { + checkIsInMulti(); + client.clusterReplicate(nodeId); + return client.getStatusCodeReply(); + } + + public List clusterSlaves(final String nodeId) { + checkIsInMulti(); + client.clusterSlaves(nodeId); + return client.getMultiBulkReply(); + } + + public String clusterFailover() { + checkIsInMulti(); + client.clusterFailover(); + return client.getStatusCodeReply(); + } public String asking() { checkIsInMulti(); diff --git a/src/main/java/redis/clients/jedis/Protocol.java b/src/main/java/redis/clients/jedis/Protocol.java index 485c10b..3f77b9a 100644 --- a/src/main/java/redis/clients/jedis/Protocol.java +++ b/src/main/java/redis/clients/jedis/Protocol.java @@ -50,6 +50,15 @@ public final class Protocol { public static final String CLUSTER_SETSLOT_NODE = "node"; public static final String CLUSTER_SETSLOT_MIGRATING = "migrating"; public static final String CLUSTER_SETSLOT_IMPORTING = "importing"; + public static final String CLUSTER_SETSLOT_STABLE = "stable"; + public static final String CLUSTER_FORGET = "forget"; + public static final String CLUSTER_FLUSHSLOT = "flushslots"; + public static final String CLUSTER_KEYSLOT = "keyslot"; + public static final String CLUSTER_COUNTKEYINSLOT = "countkeysinslot"; + public static final String CLUSTER_SAVECONFIG = "saveconfig"; + public static final String CLUSTER_REPLICATE = "replicate"; + public static final String CLUSTER_SLAVES = "slaves"; + public static final String CLUSTER_FAILOVER = "failover"; public static final String PUBSUB_CHANNELS= "channels"; public static final String PUBSUB_NUMSUB = "numsub"; public static final String PUBSUB_NUM_PAT = "numpat"; diff --git a/src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java b/src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java index cb7a58b..b2c9cf0 100644 --- a/src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java +++ b/src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java @@ -27,6 +27,10 @@ public class HostAndPortUtil { clusterHostAndPortList.add(new HostAndPort("localhost", 7379)); clusterHostAndPortList.add(new HostAndPort("localhost", 7380)); clusterHostAndPortList.add(new HostAndPort("localhost", 7381)); + clusterHostAndPortList.add(new HostAndPort("localhost", 7382)); + clusterHostAndPortList.add(new HostAndPort("localhost", 7383)); + clusterHostAndPortList.add(new HostAndPort("localhost", 7384)); + clusterHostAndPortList.add(new HostAndPort("localhost", 7385)); String envRedisHosts = System.getProperty("redis-hosts"); String envSentinelHosts = System.getProperty("sentinel-hosts"); diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterReplicateTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterReplicateTest.java new file mode 100644 index 0000000..39d9ff1 --- /dev/null +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterReplicateTest.java @@ -0,0 +1,167 @@ +package redis.clients.jedis.tests; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisCluster; +import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.exceptions.JedisException; +import redis.clients.jedis.tests.utils.JedisClusterTestUtil; + +public class JedisClusterReplicateTest { + private static Jedis node5; + private static Jedis node6; + + private HostAndPort nodeInfo5 = HostAndPortUtil.getClusterServers().get(4); + private HostAndPort nodeInfo6 = HostAndPortUtil.getClusterServers().get(5); + + private static int TIMEOUT = 15000; // cluster-node-timeout * 3 + + @Before + public void setUp() throws InterruptedException { + node5 = new Jedis(nodeInfo5.getHost(), nodeInfo5.getPort(), TIMEOUT); + node5.connect(); + node5.flushAll(); + + node6 = new Jedis(nodeInfo6.getHost(), nodeInfo6.getPort(), TIMEOUT); + node6.connect(); + // cannot flushall - it will be slave + + // ---- configure cluster + + // add nodes to cluster + node5.clusterMeet("127.0.0.1", nodeInfo6.getPort()); + + JedisClusterTestUtil.assertNodeIsKnown(node5, JedisClusterTestUtil.getNodeId(node6.clusterNodes()), 1000); + JedisClusterTestUtil.assertNodeIsKnown(node6, JedisClusterTestUtil.getNodeId(node5.clusterNodes()), 1000); + + // split available slots across the three nodes + int[] node5Slots = new int[JedisCluster.HASHSLOTS]; + for (int i = 0 ; i < JedisCluster.HASHSLOTS; i++) { + node5Slots[i] = i; + } + + node5.clusterAddSlots(node5Slots); + + JedisClusterTestUtil.waitForClusterReady(node5); + + // replicate full 1on1 + node6.clusterReplicate(JedisClusterTestUtil.getNodeId(node5 + .clusterNodes())); + + Map replMap = new HashMap(); + replMap.put(node5, node6); + + waitForReplicateReady(replMap, TIMEOUT); + JedisClusterTestUtil.waitForClusterReady(node5, node6); + } + + private void waitForReplicateReady(Map replMap, int timeoutMs) { + int interval = 100; + + for (int timeout = 0; timeout <= timeoutMs; timeout += interval) { + for (Entry entry : replMap.entrySet()) { + Jedis master = entry.getKey(); + Jedis slave = entry.getValue(); + + String masterNodeId = JedisClusterTestUtil.getNodeId(master + .clusterNodes()); + String slaveNodeId = JedisClusterTestUtil.getNodeId(slave + .clusterNodes()); + + try { + List slaves = master.clusterSlaves(masterNodeId); + + if (slaves.size() > 0 && slaves.get(0).contains(slaveNodeId)) { + return; + } + } catch (JedisDataException e) { + if (!e.getMessage().startsWith("ERR The specified node is not a master")) + throw e; + + // retry... + } + } + + try { + Thread.sleep(interval); + } catch (InterruptedException e) { + } + } + + throw new JedisException("there seems to replication error"); + } + + @After + public void tearDown() throws InterruptedException { + // clear all slots + int[] slotsToDelete = new int[JedisCluster.HASHSLOTS]; + for (int i = 0; i < JedisCluster.HASHSLOTS; i++) { + slotsToDelete[i] = i; + } + + node5.clusterDelSlots(slotsToDelete); + } + + @Test + public void testClusterReplicate() { + // we're already replicate 1on1 + List slaveInfos = node5.clusterSlaves(JedisClusterTestUtil + .getNodeId(node5.clusterNodes())); + assertEquals(1, slaveInfos.size()); + assertTrue(slaveInfos.get(0).contains( + JedisClusterTestUtil.getNodeId(node6.clusterNodes()))); + } + + @Test + public void testClusterFailover() throws InterruptedException { + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort(nodeInfo5.getHost(), nodeInfo5.getPort())); + JedisCluster jc = new JedisCluster(jedisClusterNode); + + jc.set("51", "foo"); + // node5 is responsible of taking care of slot for key "51" (7186) + + node6.clusterFailover(); + + try { + // wait for failover + Map replMap = new HashMap(); + replMap.put(node6, node5); + waitForReplicateReady(replMap, TIMEOUT); + JedisClusterTestUtil.waitForClusterReady(node5, node6); + + List slaveInfos = node6.clusterSlaves(JedisClusterTestUtil + .getNodeId(node6.clusterNodes())); + assertEquals(1, slaveInfos.size()); + assertTrue(slaveInfos.get(0).contains( + JedisClusterTestUtil.getNodeId(node5.clusterNodes()))); + } finally { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + } + + // rollback + node5.clusterFailover(); + + Map replMap = new HashMap(); + replMap.put(node5, node6); + waitForReplicateReady(replMap, TIMEOUT); + JedisClusterTestUtil.waitForClusterReady(node5, node6); + } + } +} diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java index c138e8d..28af2a4 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java @@ -1,6 +1,8 @@ package redis.clients.jedis.tests; +import java.util.ArrayList; import java.util.HashSet; +import java.util.List; import java.util.Set; import org.junit.After; @@ -15,17 +17,21 @@ import redis.clients.jedis.JedisCluster; import redis.clients.jedis.exceptions.JedisAskDataException; import redis.clients.jedis.exceptions.JedisClusterException; import redis.clients.jedis.exceptions.JedisClusterMaxRedirectionsException; +import redis.clients.jedis.exceptions.JedisException; import redis.clients.jedis.exceptions.JedisMovedDataException; +import redis.clients.jedis.tests.utils.JedisClusterTestUtil; import redis.clients.util.JedisClusterCRC16; public class JedisClusterTest extends Assert { - private Jedis node1; + private static Jedis node1; private static Jedis node2; private static Jedis node3; + private static Jedis node4; private HostAndPort nodeInfo1 = HostAndPortUtil.getClusterServers().get(0); private HostAndPort nodeInfo2 = HostAndPortUtil.getClusterServers().get(1); private HostAndPort nodeInfo3 = HostAndPortUtil.getClusterServers().get(2); + private HostAndPort nodeInfo4 = HostAndPortUtil.getClusterServers().get(3); @Before public void setUp() throws InterruptedException { @@ -40,6 +46,10 @@ public class JedisClusterTest extends Assert { node3 = new Jedis(nodeInfo3.getHost(), nodeInfo3.getPort()); node3.connect(); node3.flushAll(); + + node4 = new Jedis(nodeInfo4.getHost(), nodeInfo4.getPort()); + node4.connect(); + node4.flushAll(); // ---- configure cluster @@ -66,29 +76,53 @@ public class JedisClusterTest extends Assert { node2.clusterAddSlots(node2Slots); node3.clusterAddSlots(node3Slots); - waitForClusterReady(); + JedisClusterTestUtil.waitForClusterReady(node1, node2, node3); } @AfterClass public static void cleanUp() { int slotTest = JedisClusterCRC16.getSlot("test"); int slot51 = JedisClusterCRC16.getSlot("51"); - String node3Id = getNodeId(node3.clusterNodes()); + + String node1Id = JedisClusterTestUtil.getNodeId(node1.clusterNodes()); + String node2Id = JedisClusterTestUtil.getNodeId(node2.clusterNodes()); + String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes()); node2.clusterSetSlotNode(slotTest, node3Id); node2.clusterSetSlotNode(slot51, node3Id); node2.clusterDelSlots(slotTest, slot51); + + // forget about all nodes + node1.clusterForget(node2Id); + node1.clusterForget(node3Id); + node2.clusterForget(node1Id); + node2.clusterForget(node3Id); + node3.clusterForget(node1Id); + node3.clusterForget(node2Id); } @After - public void tearDown() { + public void tearDown() throws InterruptedException { // clear all slots int[] slotsToDelete = new int[JedisCluster.HASHSLOTS]; for (int i = 0; i < JedisCluster.HASHSLOTS; i++) { slotsToDelete[i] = i; } + node1.clusterDelSlots(slotsToDelete); node2.clusterDelSlots(slotsToDelete); node3.clusterDelSlots(slotsToDelete); + + clearAnyInconsistentMigration(node1); + clearAnyInconsistentMigration(node2); + clearAnyInconsistentMigration(node3); + } + + private void clearAnyInconsistentMigration(Jedis node) { + // FIXME: it's too slow... apply pipeline if possible + List slots = getInconsistentSlots(node.clusterNodes()); + for (Integer slot : slots) { + node.clusterSetSlotStable(slot); + } } @Test(expected = JedisMovedDataException.class) @@ -112,7 +146,7 @@ public class JedisClusterTest extends Assert { @Test(expected = JedisAskDataException.class) public void testThrowAskException() { int keySlot = JedisClusterCRC16.getSlot("test"); - String node3Id = getNodeId(node3.clusterNodes()); + String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes()); node2.clusterSetSlotMigrating(keySlot, node3Id); node2.get("test"); } @@ -122,7 +156,7 @@ public class JedisClusterTest extends Assert { Set jedisClusterNode = new HashSet(); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); JedisCluster jc = new JedisCluster(jedisClusterNode); - assertEquals(jc.getClusterNodes().size(), 3); + assertEquals(3, jc.getClusterNodes().size()); } @Test @@ -146,7 +180,7 @@ public class JedisClusterTest extends Assert { node3.clusterDelSlots(slot51); node3.clusterAddSlots(slot51); - waitForClusterReady(); + JedisClusterTestUtil.waitForClusterReady(node1, node2, node3); jc.set("51", "foo"); assertEquals("foo", jc.get("51")); } @@ -157,8 +191,8 @@ public class JedisClusterTest extends Assert { jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); JedisCluster jc = new JedisCluster(jedisClusterNode); int slot51 = JedisClusterCRC16.getSlot("51"); - node3.clusterSetSlotImporting(slot51, getNodeId(node2.clusterNodes())); - node2.clusterSetSlotMigrating(slot51, getNodeId(node3.clusterNodes())); + node3.clusterSetSlotImporting(slot51, JedisClusterTestUtil.getNodeId(node2.clusterNodes())); + node2.clusterSetSlotMigrating(slot51, JedisClusterTestUtil.getNodeId(node3.clusterNodes())); jc.set("51", "foo"); assertEquals("foo", jc.get("51")); } @@ -178,7 +212,7 @@ public class JedisClusterTest extends Assert { JedisCluster jc = new JedisCluster(jedisClusterNode); int slot51 = JedisClusterCRC16.getSlot("51"); // This will cause an infinite redirection loop - node2.clusterSetSlotMigrating(slot51, getNodeId(node3.clusterNodes())); + node2.clusterSetSlotMigrating(slot51, JedisClusterTestUtil.getNodeId(node3.clusterNodes())); jc.set("51", "foo"); } @@ -190,25 +224,181 @@ public class JedisClusterTest extends Assert { assertEquals(JedisClusterCRC16.getSlot("foo{bar}{zap}"), JedisClusterCRC16.getSlot("bar")); } - private static String getNodeId(String infoOutput) { - for (String infoLine : infoOutput.split("\n")) { - if (infoLine.contains("myself")) { - return infoLine.split(" ")[0]; - } - } - return ""; + @Test + public void testClusterForgetNode() throws InterruptedException { + // at first, join node4 to cluster + node1.clusterMeet("127.0.0.1", nodeInfo4.getPort()); + + String node7Id = JedisClusterTestUtil.getNodeId(node4.clusterNodes()); + + JedisClusterTestUtil.assertNodeIsKnown(node3, node7Id, 1000); + JedisClusterTestUtil.assertNodeIsKnown(node2, node7Id, 1000); + JedisClusterTestUtil.assertNodeIsKnown(node1, node7Id, 1000); + + assertNodeHandshakeEnded(node3, 1000); + assertNodeHandshakeEnded(node2, 1000); + assertNodeHandshakeEnded(node1, 1000); + + assertEquals(4, node1.clusterNodes().split("\n").length); + assertEquals(4, node2.clusterNodes().split("\n").length); + assertEquals(4, node3.clusterNodes().split("\n").length); + + // do cluster forget + node1.clusterForget(node7Id); + node2.clusterForget(node7Id); + node3.clusterForget(node7Id); + + JedisClusterTestUtil.assertNodeIsUnknown(node1, node7Id, 1000); + JedisClusterTestUtil.assertNodeIsUnknown(node2, node7Id, 1000); + JedisClusterTestUtil.assertNodeIsUnknown(node3, node7Id, 1000); + + assertEquals(3, node1.clusterNodes().split("\n").length); + assertEquals(3, node2.clusterNodes().split("\n").length); + assertEquals(3, node3.clusterNodes().split("\n").length); } - - private void waitForClusterReady() throws InterruptedException { - boolean clusterOk = false; - while (!clusterOk) { - if (node1.clusterInfo().split("\n")[0].contains("ok") - && node2.clusterInfo().split("\n")[0].contains("ok") - && node3.clusterInfo().split("\n")[0].contains("ok")) { - clusterOk = true; + + @Test + public void testClusterFlushSlots() { + String slotRange = getNodeServingSlotRange(node1.clusterNodes()); + assertNotNull(slotRange); + + try { + node1.clusterFlushSlots(); + assertNull(getNodeServingSlotRange(node1.clusterNodes())); + } finally { + // rollback + String[] rangeInfo = slotRange.split("-"); + int lower = Integer.parseInt(rangeInfo[0]); + int upper = Integer.parseInt(rangeInfo[1]); + + int[] node1Slots = new int[upper - lower + 1]; + for (int i = 0 ; lower <= upper ; ) { + node1Slots[i++] = lower++; } - Thread.sleep(50); + node1.clusterAddSlots(node1Slots); } } + @Test + public void testClusterKeySlot() { + // It assumes JedisClusterCRC16 is correctly implemented + assertEquals(node1.clusterKeySlot("foo{bar}zap}").intValue(), JedisClusterCRC16.getSlot("foo{bar}zap")); + assertEquals(node1.clusterKeySlot("{user1000}.following").intValue(), JedisClusterCRC16.getSlot("{user1000}.following")); + } + + @Test + public void testClusterCountKeysInSlot() { + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort())); + JedisCluster jc = new JedisCluster(jedisClusterNode); + + for (int index = 0 ; index < 5 ; index++) { + jc.set("foo{bar}" + index, "hello"); + } + + int slot = JedisClusterCRC16.getSlot("foo{bar}"); + assertEquals(5, node1.clusterCountKeysInSlot(slot).intValue()); + } + + @Test + public void testStableSlotWhenMigratingNodeOrImportingNodeIsNotSpecified() throws InterruptedException { + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort())); + JedisCluster jc = new JedisCluster(jedisClusterNode); + + int slot51 = JedisClusterCRC16.getSlot("51"); + jc.set("51", "foo"); + // node2 is responsible of taking care of slot51 (7186) + + node3.clusterSetSlotImporting(slot51, JedisClusterTestUtil.getNodeId(node2.clusterNodes())); + assertEquals("foo", jc.get("51")); + node3.clusterSetSlotStable(slot51); + assertEquals("foo", jc.get("51")); + + node2.clusterSetSlotMigrating(slot51, JedisClusterTestUtil.getNodeId(node3.clusterNodes())); + //assertEquals("foo", jc.get("51")); // it leads Max Redirections + node2.clusterSetSlotStable(slot51); + assertEquals("foo", jc.get("51")); + } + + private static String getNodeServingSlotRange(String infoOutput) { + // f4f3dc4befda352a4e0beccf29f5e8828438705d 127.0.0.1:7380 master - 0 1394372400827 0 connected 5461-10922 + for (String infoLine : infoOutput.split("\n")) { + if (infoLine.contains("myself")) { + try { + return infoLine.split(" ")[8]; + } catch (ArrayIndexOutOfBoundsException e) { + return null; + } + } + } + return null; + } + + private List getInconsistentSlots(String infoOuput) { + for (String infoLine : infoOuput.split("\n")) { + if (infoLine.contains("myself")) { + return getSlotsBeingMigrated(infoLine); + } + } + + return null; + } + + private List getSlotsBeingMigrated(String infoLine) { + List inconsistentSlots = new ArrayList(); + + String[] splitted = infoLine.split(" "); + + if (splitted.length > 8) { + for (int index = 8 ; index < splitted.length ; index++) { + String info = splitted[index]; + Integer slot = getSlotFromMigrationInfo(info); + if (slot != null) { + inconsistentSlots.add(slot); + } + } + } + + return inconsistentSlots; + } + + private Integer getSlotFromMigrationInfo(String info) { + if (info.startsWith("[")) { + if (info.contains("-<-")) { + return Integer.parseInt(info.split("-<-")[0].substring(1)); + } else if (info.contains("->-")) { + return Integer.parseInt(info.split("->-")[0].substring(1)); + } + } + + return null; + } + + private void assertNodeHandshakeEnded(Jedis node, int timeoutMs) { + int sleepInterval = 100; + for (int sleepTime = 0 ; sleepTime <= timeoutMs ; sleepTime += sleepInterval) { + boolean isHandshaking = isAnyNodeHandshaking(node); + if (!isHandshaking) + return; + + try { + Thread.sleep(sleepInterval); + } catch (InterruptedException e) { + } + } + + throw new JedisException("Node handshaking is not ended"); + } + + private boolean isAnyNodeHandshaking(Jedis node) { + String infoOutput = node.clusterNodes(); + for (String infoLine : infoOutput.split("\n")) { + if (infoLine.contains("handshake")) { + return true; + } + } + return false; + } + } diff --git a/src/test/java/redis/clients/jedis/tests/utils/JedisClusterTestUtil.java b/src/test/java/redis/clients/jedis/tests/utils/JedisClusterTestUtil.java new file mode 100644 index 0000000..c7f7928 --- /dev/null +++ b/src/test/java/redis/clients/jedis/tests/utils/JedisClusterTestUtil.java @@ -0,0 +1,70 @@ +package redis.clients.jedis.tests.utils; + +import redis.clients.jedis.Jedis; +import redis.clients.jedis.exceptions.JedisException; + +public class JedisClusterTestUtil { + public static void waitForClusterReady(Jedis...nodes) throws InterruptedException { + boolean clusterOk = false; + while (!clusterOk) { + boolean isOk = true; + for (Jedis node : nodes) { + if (!node.clusterInfo().split("\n")[0].contains("ok")) { + isOk = false; + break; + } + } + + if (isOk) { + clusterOk = true; + } + + Thread.sleep(50); + } + } + + public static String getNodeId(String infoOutput) { + for (String infoLine : infoOutput.split("\n")) { + if (infoLine.contains("myself")) { + return infoLine.split(" ")[0]; + } + } + return ""; + } + + public static void assertNodeIsKnown(Jedis node, String targetNodeId, int timeoutMs) { + assertNodeRecognizedStatus(node, targetNodeId, true, timeoutMs); + } + + public static void assertNodeIsUnknown(Jedis node, String targetNodeId, int timeoutMs) { + assertNodeRecognizedStatus(node, targetNodeId, false, timeoutMs); + } + + private static void assertNodeRecognizedStatus(Jedis node, String targetNodeId, boolean shouldRecognized, int timeoutMs) { + int sleepInterval = 100; + for (int sleepTime = 0 ; sleepTime <= timeoutMs ; sleepTime += sleepInterval) { + boolean known = isKnownNode(node, targetNodeId); + if (shouldRecognized == known) + return; + + try { + Thread.sleep(sleepInterval); + } catch (InterruptedException e) { + } + } + + throw new JedisException("Node recognize check error"); + } + + private static boolean isKnownNode(Jedis node, String nodeId) { + String infoOutput = node.clusterNodes(); + for (String infoLine : infoOutput.split("\n")) { + if (infoLine.contains(nodeId)) { + return true; + } + } + return false; + } + + +} From 1fba7de9bc5f60574af28f50327c321bd469d7d5 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Sun, 25 May 2014 16:51:47 -0300 Subject: [PATCH 111/120] Change back commons pool to 2.0 as 2.2 isn't fully tested --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 38d94b2..ddc40c3 100644 --- a/pom.xml +++ b/pom.xml @@ -62,7 +62,7 @@ org.apache.commons commons-pool2 - 2.2 + 2.0 jar compile From 9aab05f9d03f9259c7a7d6f1a95c3f13126954e7 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Tue, 27 May 2014 12:50:23 -0400 Subject: [PATCH 112/120] [maven-release-plugin] prepare release jedis-2.5.0 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index ddc40c3..d4ab0f2 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ jar redis.clients jedis - 2.5.0-SNAPSHOT + 2.5.0 Jedis Jedis is a blazingly small and sane Redis java client. https://github.com/xetorthio/jedis @@ -41,7 +41,7 @@ scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git - jedis-2.2.0 + jedis-2.5.0 From 7e8b09e610143df1f3b8ef68bb9872a72464e4d7 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Tue, 27 May 2014 12:50:25 -0400 Subject: [PATCH 113/120] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index d4ab0f2..69ba0be 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ jar redis.clients jedis - 2.5.0 + 2.5.1-SNAPSHOT Jedis Jedis is a blazingly small and sane Redis java client. https://github.com/xetorthio/jedis @@ -41,7 +41,7 @@ scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git - jedis-2.5.0 + jedis-2.2.0 From 58ebeed00ea3c1b18379adb51a6fc5ca24205ae3 Mon Sep 17 00:00:00 2001 From: Dustin Lineweber Date: Tue, 27 May 2014 15:37:42 -0500 Subject: [PATCH 114/120] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 70664a1..bce8aa1 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,7 @@ Redis cluster [specification](http://redis.io/topics/cluster-spec) (still under Set jedisClusterNodes = new HashSet(); //Jedis Cluster will attempt to discover cluster nodes automatically jedisClusterNodes.add(new HostAndPort("127.0.0.1", 7379)); -JedisCluster jc = new JedisCluster(jedisClusterNode); +JedisCluster jc = new JedisCluster(jedisClusterNodes); jc.set("foo", "bar"); String value = jc.get("foo"); ``` From fdce5fb69215a647a8ce9d54de2c29f23ef9f94d Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Thu, 29 May 2014 11:44:56 -0400 Subject: [PATCH 115/120] [maven-release-plugin] prepare release jedis-2.5.1 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 69ba0be..eda967e 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ jar redis.clients jedis - 2.5.1-SNAPSHOT + 2.5.1 Jedis Jedis is a blazingly small and sane Redis java client. https://github.com/xetorthio/jedis @@ -41,7 +41,7 @@ scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git - jedis-2.2.0 + jedis-2.5.1 From e05eaa2b071b7698593b049baeab29448c1c767d Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Thu, 29 May 2014 11:44:57 -0400 Subject: [PATCH 116/120] [maven-release-plugin] prepare for next development iteration --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index eda967e..2ad2a55 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ jar redis.clients jedis - 2.5.1 + 2.5.2-SNAPSHOT Jedis Jedis is a blazingly small and sane Redis java client. https://github.com/xetorthio/jedis @@ -41,7 +41,7 @@ scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git scm:git:git@github.com:xetorthio/jedis.git - jedis-2.5.1 + jedis-2.2.0 From 0f472c97a27da62c86444a1c72e599fdb81edf83 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Wed, 2 Jul 2014 07:42:29 +0900 Subject: [PATCH 117/120] fix build after CLUSTER NODES output has been changed * https://github.com/antirez/redis/issues/1848 * we don't need to handle :0 by changes --- .../clients/util/ClusterNodeInformationParser.java | 11 +++++------ .../tests/JedisClusterNodeInformationParserTest.java | 4 ++-- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/main/java/redis/clients/util/ClusterNodeInformationParser.java b/src/main/java/redis/clients/util/ClusterNodeInformationParser.java index 995df6f..3c10c95 100644 --- a/src/main/java/redis/clients/util/ClusterNodeInformationParser.java +++ b/src/main/java/redis/clients/util/ClusterNodeInformationParser.java @@ -3,7 +3,6 @@ package redis.clients.util; import redis.clients.jedis.HostAndPort; public class ClusterNodeInformationParser { - private static final String HOST_MYSELF_IDENTIFIER = ":0"; private static final String SLOT_IMPORT_IDENTIFIER = "-<-"; private static final String SLOT_IN_TRANSITION_IDENTIFIER = "["; public static final int SLOT_INFORMATIONS_START_INDEX = 8; @@ -36,13 +35,13 @@ public class ClusterNodeInformationParser { public HostAndPort getHostAndPortFromNodeLine(String[] nodeInfoPartArray, HostAndPort current) { String stringHostAndPort = nodeInfoPartArray[HOST_AND_PORT_INDEX]; - if (HOST_MYSELF_IDENTIFIER.equals(stringHostAndPort)) { - return current; - } String[] arrayHostAndPort = stringHostAndPort.split(":"); - return new HostAndPort(arrayHostAndPort[0], - Integer.valueOf(arrayHostAndPort[1])); + return new HostAndPort( + arrayHostAndPort[0].isEmpty() ? current.getHost() + : arrayHostAndPort[0], + arrayHostAndPort[1].isEmpty() ? current.getPort() : Integer + .valueOf(arrayHostAndPort[1])); } private void fillSlotInformation(String[] slotInfoPartArray, diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterNodeInformationParserTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterNodeInformationParserTest.java index bc0fd42..14b830f 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterNodeInformationParserTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterNodeInformationParserTest.java @@ -17,7 +17,7 @@ public class JedisClusterNodeInformationParserTest extends Assert { @Test public void testParseNodeMyself() { - String nodeInfo = "9b0d2ab38ee31482c95fdb2c7847a0d40e88d518 :0 myself,master - 0 0 1 connected 0-5460"; + String nodeInfo = "9b0d2ab38ee31482c95fdb2c7847a0d40e88d518 :7379 myself,master - 0 0 1 connected 0-5460"; HostAndPort current = new HostAndPort("localhost", 7379); ClusterNodeInformation clusterNodeInfo = parser .parse(nodeInfo, current); @@ -44,7 +44,7 @@ public class JedisClusterNodeInformationParserTest extends Assert { @Test public void testParseSlotBeingMigrated() { - String nodeInfo = "5f4a2236d00008fba7ac0dd24b95762b446767bd :0 myself,master - 0 0 1 connected 0-5459 [5460->-5f4a2236d00008fba7ac0dd24b95762b446767bd] [5461-<-5f4a2236d00008fba7ac0dd24b95762b446767bd]"; + String nodeInfo = "5f4a2236d00008fba7ac0dd24b95762b446767bd :7379 myself,master - 0 0 1 connected 0-5459 [5460->-5f4a2236d00008fba7ac0dd24b95762b446767bd] [5461-<-5f4a2236d00008fba7ac0dd24b95762b446767bd]"; HostAndPort current = new HostAndPort("localhost", 7379); ClusterNodeInformation clusterNodeInfo = parser .parse(nodeInfo, current); From 088d86a60fc7cfd3ba55156fc949059b5e9ecdc9 Mon Sep 17 00:00:00 2001 From: xuyifei Date: Thu, 17 Jul 2014 16:40:22 +0800 Subject: [PATCH 118/120] Update Jedis.java edit the rpop note (just makei it Specific --- src/main/java/redis/clients/jedis/Jedis.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index fbf430c..77cb245 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -1116,8 +1116,8 @@ public class Jedis extends BinaryJedis implements JedisCommands, /** * Atomically return and remove the first (LPOP) or last (RPOP) element of - * the list. For example if the list contains the elements "a","b","c" LPOP - * will return "a" and the list will become "b","c". + * the list. For example if the list contains the elements "a","b","c" RPOP + * will return "c" and the list will become "a","b". *

* If the key does not exist or the list is already empty the special value * 'nil' is returned. From c2624c6c932e3ed2fee1873fcb72d33f5816904c Mon Sep 17 00:00:00 2001 From: Greg Tam Date: Thu, 17 Jul 2014 15:11:02 -0600 Subject: [PATCH 119/120] fixed the name of archiveBaseName to archivesBaseName --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 30af731..3905e3e 100644 --- a/build.gradle +++ b/build.gradle @@ -3,7 +3,7 @@ apply plugin: 'maven' apply plugin: 'eclipse' group = 'com.googlecode.jedis' -archiveBaseName = 'jedis' +archivesBaseName = 'jedis' version = '1.5.0' repositories { From d7cd3a0af671b0fcf30b7cd4819fa9026f8d92f8 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Mon, 4 Aug 2014 09:28:17 +0900 Subject: [PATCH 120/120] Fixed critical JedisCluster bug : hlen calls hdel --- src/main/java/redis/clients/jedis/JedisCluster.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/redis/clients/jedis/JedisCluster.java b/src/main/java/redis/clients/jedis/JedisCluster.java index f6cb6fd..d39d43d 100644 --- a/src/main/java/redis/clients/jedis/JedisCluster.java +++ b/src/main/java/redis/clients/jedis/JedisCluster.java @@ -394,7 +394,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { maxRedirections) { @Override public Long execute(Jedis connection) { - return connection.hdel(key); + return connection.hlen(key); } }.run(key); }