From 5e2cdb9c088fc4c36bbf80d1d76ab414d973f4cc Mon Sep 17 00:00:00 2001 From: Darren Shepherd Date: Fri, 29 Mar 2013 22:28:01 -0700 Subject: [PATCH 01/70] 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 7e1a1a70b2f646b22485e7d40a285aa6d87011b6 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Mon, 7 Oct 2013 11:03:32 +0900 Subject: [PATCH 02/70] Speed up Sentinel related tests * remove FIXME sleep codes for Sentinel related tests ** add functions for Sentinel tests (JedisSentinelTestUtil) *** waitForSentinelRecognizeRedisReplication *** waitForNewPromotedMaster *** waitForSentinelsRecognizeEachOthers **** TODO: there're no command for sentinel to list recognized sentinel **** sleep 5.5 sec (sentinel pings to master every 5 sec) * set HostAndPort class to public(no longer inner) class ** reason: We cannot know pool's current master if HostAndPort class is private inner class / HostAndPort classes are duplicated (main/test) ** make getter method and parameterized constructor *** set fields once, get anytime --- .../java/redis/clients/jedis/HostAndPort.java | 39 ++++ .../clients/jedis/JedisSentinelPool.java | 33 +--- .../clients/jedis/tests/HostAndPortUtil.java | 64 ++----- .../clients/jedis/tests/JedisPoolTest.java | 42 +++-- .../jedis/tests/JedisSentinelPoolTest.java | 174 +++++++++++------- .../jedis/tests/JedisSentinelTest.java | 113 +++++++----- .../clients/jedis/tests/PipeliningTest.java | 22 ++- .../jedis/tests/ShardedJedisPipelineTest.java | 13 +- .../jedis/tests/ShardedJedisPoolTest.java | 6 +- .../clients/jedis/tests/ShardedJedisTest.java | 22 +-- .../tests/benchmark/GetSetBenchmark.java | 4 +- .../tests/benchmark/HashingBenchmark.java | 6 +- .../benchmark/PipelinedGetSetBenchmark.java | 4 +- .../jedis/tests/benchmark/PoolBenchmark.java | 6 +- .../ConnectionHandlingCommandsTest.java | 4 +- .../tests/commands/JedisCommandTestBase.java | 21 ++- .../PublishSubscribeCommandsTest.java | 2 +- .../commands/TransactionCommandsTest.java | 2 +- .../tests/utils/JedisSentinelTestUtil.java | 113 ++++++++++++ 19 files changed, 431 insertions(+), 259 deletions(-) create mode 100644 src/main/java/redis/clients/jedis/HostAndPort.java create mode 100644 src/test/java/redis/clients/jedis/tests/utils/JedisSentinelTestUtil.java diff --git a/src/main/java/redis/clients/jedis/HostAndPort.java b/src/main/java/redis/clients/jedis/HostAndPort.java new file mode 100644 index 0000000..488eac3 --- /dev/null +++ b/src/main/java/redis/clients/jedis/HostAndPort.java @@ -0,0 +1,39 @@ +package redis.clients.jedis; + +public class HostAndPort { + 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; + + // localhost and 127.0.0.1 is same + return port == hp.port && + (host.equals(hp.host) || + (host.equals("localhost") && hp.host.equals("127.0.0.1")) || + (host.equals("127.0.0.1") && hp.host.equals("localhost")) ); + } + + return false; + } + + @Override + public String toString() { + return host + ":" + port; + } +} diff --git a/src/main/java/redis/clients/jedis/JedisSentinelPool.java b/src/main/java/redis/clients/jedis/JedisSentinelPool.java index 0d87bdd..de7e9af 100644 --- a/src/main/java/redis/clients/jedis/JedisSentinelPool.java +++ b/src/main/java/redis/clients/jedis/JedisSentinelPool.java @@ -81,25 +81,6 @@ public class JedisSentinelPool extends Pool { returnResourceObject(resource); } - private class HostAndPort { - String host; - int port; - - @Override - public boolean equals(Object obj) { - if (obj instanceof HostAndPort) { - HostAndPort hp = (HostAndPort) obj; - return port == hp.port && host.equals(hp.host); - } - return false; - } - - @Override - public String toString() { - return host + ":" + port; - } - } - private volatile HostAndPort currentHostMaster; public void destroy() { @@ -118,7 +99,7 @@ public class JedisSentinelPool extends Pool { if (!master.equals(currentHostMaster)) { currentHostMaster = master; log.info("Created JedisPool to master at " + master); - initPool(poolConfig, new JedisFactory(master.host, master.port, + initPool(poolConfig, new JedisFactory(master.getHost(), master.getPort(), timeout, password, database)); } } @@ -141,7 +122,7 @@ public class JedisSentinelPool extends Pool { log.fine("Connecting to Sentinel " + hap); try { - Jedis jedis = new Jedis(hap.host, hap.port); + Jedis jedis = new Jedis(hap.getHost(), hap.getPort()); if (master == null) { master = toHostAndPort(jedis @@ -172,7 +153,7 @@ public class JedisSentinelPool extends Pool { final HostAndPort hap = toHostAndPort(Arrays.asList(sentinel .split(":"))); MasterListener masterListener = new MasterListener(masterName, - hap.host, hap.port); + hap.getHost(), hap.getPort()); masterListeners.add(masterListener); masterListener.start(); } @@ -181,10 +162,10 @@ public class JedisSentinelPool extends Pool { } private HostAndPort toHostAndPort(List getMasterAddrByNameResult) { - final HostAndPort hap = new HostAndPort(); - hap.host = getMasterAddrByNameResult.get(0); - hap.port = Integer.parseInt(getMasterAddrByNameResult.get(1)); - return hap; + 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/test/java/redis/clients/jedis/tests/HostAndPortUtil.java b/src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java index 648725e..03e421e 100644 --- a/src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java +++ b/src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java @@ -3,52 +3,37 @@ package redis.clients.jedis.tests; import java.util.ArrayList; import java.util.List; +import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Protocol; public class HostAndPortUtil { - private static List redisHostAndPortList = new ArrayList(); - private static List sentinelHostAndPortList = new ArrayList(); + private static List redisHostAndPortList = new ArrayList(); + private static List sentinelHostAndPortList = new ArrayList(); static { - HostAndPort defaulthnp1 = new HostAndPort(); - defaulthnp1.host = "localhost"; - defaulthnp1.port = Protocol.DEFAULT_PORT; + HostAndPort defaulthnp1 = new HostAndPort("localhost", Protocol.DEFAULT_PORT); redisHostAndPortList.add(defaulthnp1); - HostAndPort defaulthnp2 = new HostAndPort(); - defaulthnp2.host = "localhost"; - defaulthnp2.port = Protocol.DEFAULT_PORT + 1; + HostAndPort defaulthnp2 = new HostAndPort("localhost", Protocol.DEFAULT_PORT + 1); redisHostAndPortList.add(defaulthnp2); - HostAndPort defaulthnp3 = new HostAndPort(); - defaulthnp3.host = "localhost"; - defaulthnp3.port = Protocol.DEFAULT_PORT + 2; + HostAndPort defaulthnp3 = new HostAndPort("localhost", Protocol.DEFAULT_PORT + 2); redisHostAndPortList.add(defaulthnp3); - HostAndPort defaulthnp4 = new HostAndPort(); - defaulthnp4.host = "localhost"; - defaulthnp4.port = Protocol.DEFAULT_PORT + 3; + HostAndPort defaulthnp4 = new HostAndPort("localhost", Protocol.DEFAULT_PORT + 3); redisHostAndPortList.add(defaulthnp4); - HostAndPort defaulthnp5 = new HostAndPort(); - defaulthnp5.host = "localhost"; - defaulthnp5.port = Protocol.DEFAULT_PORT + 4; + HostAndPort defaulthnp5 = new HostAndPort("localhost", Protocol.DEFAULT_PORT + 4); redisHostAndPortList.add(defaulthnp5); - HostAndPort defaulthnp6 = new HostAndPort(); - defaulthnp6.host = "localhost"; - defaulthnp6.port = Protocol.DEFAULT_SENTINEL_PORT; + HostAndPort defaulthnp6 = new HostAndPort("localhost", Protocol.DEFAULT_SENTINEL_PORT); sentinelHostAndPortList.add(defaulthnp6); - HostAndPort defaulthnp7 = new HostAndPort(); - defaulthnp7.host = "localhost"; - defaulthnp7.port = Protocol.DEFAULT_SENTINEL_PORT + 1; + HostAndPort defaulthnp7 = new HostAndPort("localhost", Protocol.DEFAULT_SENTINEL_PORT + 1); sentinelHostAndPortList.add(defaulthnp7); - HostAndPort defaulthnp8 = new HostAndPort(); - defaulthnp8.host = "localhost"; - defaulthnp8.port = Protocol.DEFAULT_SENTINEL_PORT + 2; + HostAndPort defaulthnp8 = new HostAndPort("localhost", Protocol.DEFAULT_SENTINEL_PORT + 2); sentinelHostAndPortList.add(defaulthnp8); String envRedisHosts = System.getProperty("redis-hosts"); @@ -66,24 +51,22 @@ public class HostAndPortUtil { if (null != hostDefs && 2 <= hostDefs.length) { - List envHostsAndPorts = new ArrayList(hostDefs.length); + List envHostsAndPorts = new ArrayList(hostDefs.length); for (String hostDef : hostDefs) { String[] hostAndPort = hostDef.split(":"); if (null != hostAndPort && 2 == hostAndPort.length) { + String host = hostAndPort[0]; + int port = Protocol.DEFAULT_PORT; - HostAndPort hnp = new HostAndPort(); - hnp.host = hostAndPort[0]; - - try { - hnp.port = Integer.parseInt(hostAndPort[1]); + try { + port = Integer.parseInt(hostAndPort[1]); } catch (final NumberFormatException nfe) { - hnp.port = Protocol.DEFAULT_PORT; - } - - envHostsAndPorts.add(hnp); + } + + envHostsAndPorts.add(new HostAndPort(host, port)); } } @@ -102,13 +85,4 @@ public class HostAndPortUtil { return sentinelHostAndPortList; } - public static class HostAndPort { - public String host; - public int port; - - @Override - public String toString() { - return host + ":" + port; - } - } } diff --git a/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java b/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java index 58964ff..08727df 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java @@ -9,19 +9,19 @@ import org.junit.Assert; import org.junit.Test; import redis.clients.jedis.BinaryJedis; +import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.exceptions.JedisConnectionException; -import redis.clients.jedis.tests.HostAndPortUtil.HostAndPort; public class JedisPoolTest extends Assert { private static HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); @Test public void checkConnections() { - JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.host, - hnp.port, 2000); + JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), + hnp.getPort(), 2000); Jedis jedis = pool.getResource(); jedis.auth("foobared"); jedis.set("foo", "bar"); @@ -32,8 +32,8 @@ public class JedisPoolTest extends Assert { @Test public void checkConnectionWithDefaultPort() { - JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.host, - hnp.port); + JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), + hnp.getPort()); Jedis jedis = pool.getResource(); jedis.auth("foobared"); jedis.set("foo", "bar"); @@ -44,8 +44,8 @@ public class JedisPoolTest extends Assert { @Test public void checkJedisIsReusedWhenReturned() { - JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.host, - hnp.port); + JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), + hnp.getPort()); Jedis jedis = pool.getResource(); jedis.auth("foobared"); jedis.set("foo", "0"); @@ -60,8 +60,8 @@ public class JedisPoolTest extends Assert { @Test public void checkPoolRepairedWhenJedisIsBroken() { - JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.host, - hnp.port); + JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), + hnp.getPort()); Jedis jedis = pool.getResource(); jedis.auth("foobared"); jedis.quit(); @@ -79,7 +79,7 @@ public class JedisPoolTest extends Assert { Config config = new Config(); config.maxActive = 1; config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL; - JedisPool pool = new JedisPool(config, hnp.host, hnp.port); + JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort()); Jedis jedis = pool.getResource(); jedis.auth("foobared"); jedis.set("foo", "0"); @@ -93,7 +93,8 @@ public class JedisPoolTest extends Assert { public void securePool() { JedisPoolConfig config = new JedisPoolConfig(); config.setTestOnBorrow(true); - JedisPool pool = new JedisPool(config, hnp.host, hnp.port, 2000, "foobared"); + JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(), + 2000, "foobared"); Jedis jedis = pool.getResource(); jedis.set("foo", "bar"); pool.returnResource(jedis); @@ -102,16 +103,16 @@ public class JedisPoolTest extends Assert { @Test public void nonDefaultDatabase() { - JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.host, - hnp.port, 2000, "foobared"); + JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.getHost(), + hnp.getPort(), 2000, "foobared"); Jedis jedis0 = pool0.getResource(); jedis0.set("foo", "bar"); assertEquals( "bar", jedis0.get("foo") ); pool0.returnResource(jedis0); pool0.destroy(); - JedisPool pool1 = new JedisPool(new JedisPoolConfig(), hnp.host, - hnp.port, 2000, "foobared", 1); + JedisPool pool1 = new JedisPool(new JedisPoolConfig(), hnp.getHost(), + hnp.getPort(), 2000, "foobared", 1); Jedis jedis1 = pool1.getResource(); assertNull( jedis1.get("foo") ); pool1.returnResource(jedis0); @@ -120,8 +121,8 @@ public class JedisPoolTest extends Assert { @Test public void returnBinary() { - JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.host, - hnp.port, 2000); + JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), + hnp.getPort(), 2000); BinaryJedis jedis = pool.getResource(); pool.returnResource(jedis); pool.destroy(); @@ -153,7 +154,8 @@ public class JedisPoolTest extends Assert { @Test public void selectDatabaseOnActivation() { - JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.host, hnp.port, 2000, "foobared"); + JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(), + hnp.getPort(), 2000, "foobared"); Jedis jedis0 = pool.getResource(); assertEquals(0L, jedis0.getDB().longValue()); @@ -173,8 +175,8 @@ public class JedisPoolTest extends Assert { @Test public void customClientName() { - JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.host, - hnp.port, 2000, "foobared", 0, "my_shiny_client_name"); + JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.getHost(), + hnp.getPort(), 2000, "foobared", 0, "my_shiny_client_name"); Jedis jedis = pool0.getResource(); diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java index 5f8e494..2b497f8 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.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.apache.commons.pool.impl.GenericObjectPool.Config; @@ -8,91 +10,121 @@ 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.JedisSentinelPool; -import redis.clients.jedis.tests.HostAndPortUtil.HostAndPort; +import redis.clients.jedis.tests.utils.JedisSentinelTestUtil; public class JedisSentinelPoolTest extends JedisTestBase { + private static final String MASTER_NAME = "mymaster"; - protected static HostAndPort master = HostAndPortUtil.getRedisServers() - .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); - protected static HostAndPort sentinel2 = HostAndPortUtil - .getSentinelServers().get(2); + protected static HostAndPort master = HostAndPortUtil.getRedisServers() + .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); + protected static HostAndPort sentinel2 = HostAndPortUtil + .getSentinelServers().get(2); - protected static Jedis masterJedis; - protected static Jedis slaveJedis1; - protected static Jedis slaveJedis2; - - protected static int slaveCount = 0; + protected static Jedis masterJedis; + protected static Jedis slaveJedis1; + protected static Jedis slaveJedis2; + protected static Jedis sentinelJedis1; + protected static Jedis sentinelJedis2; - protected Set sentinels = new HashSet(); + protected Set sentinels = new HashSet(); - @Before - public void setUp() throws Exception { + @Before + public void setUp() throws Exception { - // set up master and slaves - masterJedis = new Jedis(master.host, master.port); - masterJedis.auth("foobared"); - masterJedis.slaveofNoOne(); + // set up master and slaves + masterJedis = new Jedis(master.getHost(), master.getPort()); + masterJedis.auth("foobared"); + masterJedis.slaveofNoOne(); - slaveJedis1 = new Jedis(slave1.host, slave1.port); - slaveJedis1.auth("foobared"); - slaveJedis1.slaveof(master.host, master.port); - slaveCount++; - - slaveJedis2 = new Jedis(slave2.host, slave2.port); - slaveJedis2.auth("foobared"); - slaveJedis2.slaveof(master.host, master.port); - slaveCount++; + slaveJedis1 = new Jedis(slave1.getHost(), slave1.getPort()); + slaveJedis1.auth("foobared"); + slaveJedis1.slaveof(master.getHost(), master.getPort()); - sentinels.add(sentinel1.toString()); - sentinels.add(sentinel2.toString()); + slaveJedis2 = new Jedis(slave2.getHost(), slave2.getPort()); + slaveJedis2.auth("foobared"); + slaveJedis2.slaveof(master.getHost(), master.getPort()); - // FIXME: The following allows the master/slave relationship to - // be established, and let sentinels know about this relationship. - // We can do this more elegantly. - Thread.sleep(10000); - } + sentinels.add(sentinel1.toString()); + sentinels.add(sentinel2.toString()); - @Test - public void ensureSafeTwiceFailover() throws InterruptedException { - JedisSentinelPool pool = new JedisSentinelPool("mymaster", sentinels, - new Config(), 1000, "foobared", 2); - - // perform failover - doSegFaultMaster(pool); - - // perform failover once again - doSegFaultMaster(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 { - // jedis connection should be master - Jedis jedis = pool.getResource(); - assertEquals("PONG", jedis.ping()); + List slaves = new ArrayList(); + slaves.add(slave1); + slaves.add(slave2); - try { - jedis.debug(DebugParams.SEGFAULT()); - } catch (Exception e) { - } + JedisSentinelTestUtil.waitForSentinelRecognizeRedisReplication(sentinel1, + MASTER_NAME, master, slaves); + JedisSentinelTestUtil.waitForSentinelRecognizeRedisReplication(sentinel2, + MASTER_NAME, master, slaves); + + // No need to wait for sentinels to recognize each other + } - // wait for the sentinel to promote a master - // FIXME: we can query the sentinel and sleep - // right until the master is promoted - Thread.sleep(35000); + @Test + public void ensureSafeTwiceFailover() throws InterruptedException { + JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels, + new Config(), 1000, "foobared", 2); + + // perform failover + doSegFaultMaster(pool); + + // perform failover once again + doSegFaultMaster(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 { + 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) { + } + + waitForFailover(pool, oldMaster); + + jedis = pool.getResource(); + assertEquals("PONG", jedis.ping()); + assertEquals("foobared", jedis.configGet("requirepass").get(1)); + assertEquals(2, jedis.getDB().intValue()); + } + + private void waitForFailover(JedisSentinelPool pool, HostAndPort oldMaster) throws InterruptedException { + HostAndPort newMaster = JedisSentinelTestUtil.waitForNewPromotedMaster(sentinel1, + MASTER_NAME, oldMaster); + JedisSentinelTestUtil.waitForNewPromotedMaster(sentinel2, MASTER_NAME, oldMaster); + JedisSentinelTestUtil.waitForSentinelsRecognizeEachOthers(); + waitForJedisSentinelPoolRecognizeNewMaster(pool, newMaster); + } + + private void waitForJedisSentinelPoolRecognizeNewMaster(JedisSentinelPool pool, + HostAndPort newMaster) throws InterruptedException { + + while (true) { + String host = pool.getCurrentHostMaster().getHost(); + int port = pool.getCurrentHostMaster().getPort(); + + if (host.equals(newMaster.getHost()) && port == newMaster.getPort()) + break; + + System.out.println("JedisSentinelPool's master is not yet changed, sleep..."); + + Thread.sleep(1000); + } + } - jedis = pool.getResource(); - assertEquals("PONG", jedis.ping()); - assertEquals("foobared", jedis.configGet("requirepass").get(1)); - assertEquals(2, jedis.getDB().intValue()); - } } diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java b/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java index 868527f..3247f21 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java @@ -1,9 +1,6 @@ package redis.clients.jedis.tests; -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.assertFalse; -import static junit.framework.Assert.assertTrue; - +import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -11,59 +8,81 @@ 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.tests.utils.JedisSentinelTestUtil; -public class JedisSentinelTest { - private static final String MASTER_NAME = "mymaster"; +public class JedisSentinelTest extends JedisTestBase { + private static final String MASTER_NAME = "mymaster"; - @Before - public void setup() throws InterruptedException { - Jedis j = new Jedis("localhost", 6380); - j.auth("foobared"); - j.configSet("masterauth", "foobared"); - j.slaveof("localhost", 6379); - // TODO: The sleep is to give time to the slave to synchronize with the - // master and also let know the sentinels about this new topology. We - // should find a better way to do this. - Thread.sleep(10000); - } + protected static HostAndPort master = HostAndPortUtil.getRedisServers() + .get(0); + protected static HostAndPort slave = HostAndPortUtil.getRedisServers() + .get(1); + protected static HostAndPort sentinel = HostAndPortUtil + .getSentinelServers().get(0); - @After - public void clear() { - Jedis j = new Jedis("localhost", 6380); - j.auth("foobared"); - j.slaveofNoOne(); - } + protected static Jedis masterJedis; + protected static Jedis slaveJedis; + protected static Jedis sentinelJedis; - @Test - public void sentinel() { - Jedis j = new Jedis("localhost", 26379); - List> masters = j.sentinelMasters(); - final String masterName = masters.get(0).get("name"); + @Before + public void setup() throws InterruptedException { + masterJedis = new Jedis(master.getHost(), master.getPort()); - assertEquals(MASTER_NAME, masterName); + slaveJedis = new Jedis(slave.getHost(), slave.getPort()); + slaveJedis.auth("foobared"); + slaveJedis.configSet("masterauth", "foobared"); + slaveJedis.slaveof(master.getHost(), master.getPort()); - List masterHostAndPort = j - .sentinelGetMasterAddrByName(masterName); - assertEquals("127.0.0.1", masterHostAndPort.get(0)); - assertEquals("6379", masterHostAndPort.get(1)); + List slaves = new ArrayList(); + slaves.add(slave); - List> slaves = j.sentinelSlaves(masterName); - assertTrue(slaves.size() > 0); - assertEquals("6379", slaves.get(0).get("master-port")); + JedisSentinelTestUtil.waitForSentinelRecognizeRedisReplication(sentinel, + MASTER_NAME, master, slaves); + + // No need to wait for sentinels to recognize each other + } - List isMasterDownByAddr = j - .sentinelIsMasterDownByAddr("127.0.0.1", 6379); - assertEquals(Long.valueOf(0), (Long) isMasterDownByAddr.get(0)); - assertFalse("?".equals(isMasterDownByAddr.get(1))); + @After + public void clear() throws InterruptedException { + Jedis j = new Jedis("localhost", 6380); + j.auth("foobared"); + j.slaveofNoOne(); - isMasterDownByAddr = j.sentinelIsMasterDownByAddr("127.0.0.1", 1); - assertEquals(Long.valueOf(0), (Long) isMasterDownByAddr.get(0)); - assertTrue("?".equals(isMasterDownByAddr.get(1))); + JedisSentinelTestUtil.waitForSentinelRecognizeRedisReplication(sentinel, + MASTER_NAME, master, new ArrayList()); + } - // 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)); + @Test + public void sentinel() { + Jedis j = new Jedis("localhost", 26379); + List> masters = j.sentinelMasters(); + final String masterName = masters.get(0).get("name"); - } + assertEquals(MASTER_NAME, masterName); + + List masterHostAndPort = j + .sentinelGetMasterAddrByName(masterName); + assertEquals("127.0.0.1", masterHostAndPort.get(0)); + assertEquals("6379", masterHostAndPort.get(1)); + + List> slaves = j.sentinelSlaves(masterName); + assertTrue(slaves.size() > 0); + assertEquals("6379", slaves.get(0).get("master-port")); + + List isMasterDownByAddr = j + .sentinelIsMasterDownByAddr("127.0.0.1", 6379); + assertEquals(Long.valueOf(0), (Long) isMasterDownByAddr.get(0)); + assertFalse("?".equals(isMasterDownByAddr.get(1))); + + isMasterDownByAddr = j.sentinelIsMasterDownByAddr("127.0.0.1", 1); + assertEquals(Long.valueOf(0), (Long) isMasterDownByAddr.get(0)); + assertTrue("?".equals(isMasterDownByAddr.get(1))); + + // 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)); + + } } diff --git a/src/test/java/redis/clients/jedis/tests/PipeliningTest.java b/src/test/java/redis/clients/jedis/tests/PipeliningTest.java index c5ab782..1fe063c 100755 --- a/src/test/java/redis/clients/jedis/tests/PipeliningTest.java +++ b/src/test/java/redis/clients/jedis/tests/PipeliningTest.java @@ -1,14 +1,24 @@ package redis.clients.jedis.tests; +import java.io.UnsupportedEncodingException; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import redis.clients.jedis.*; -import redis.clients.jedis.exceptions.JedisDataException; -import redis.clients.jedis.tests.HostAndPortUtil.HostAndPort; -import java.io.UnsupportedEncodingException; -import java.util.*; +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; public class PipeliningTest extends Assert { private static HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); @@ -17,7 +27,7 @@ public class PipeliningTest extends Assert { @Before public void setUp() throws Exception { - jedis = new Jedis(hnp.host, hnp.port, 500); + jedis = new Jedis(hnp.getHost(), hnp.getPort(), 500); jedis.connect(); jedis.auth("foobared"); jedis.flushAll(); diff --git a/src/test/java/redis/clients/jedis/tests/ShardedJedisPipelineTest.java b/src/test/java/redis/clients/jedis/tests/ShardedJedisPipelineTest.java index 7574f08..b9b4334 100644 --- a/src/test/java/redis/clients/jedis/tests/ShardedJedisPipelineTest.java +++ b/src/test/java/redis/clients/jedis/tests/ShardedJedisPipelineTest.java @@ -15,6 +15,7 @@ import java.util.UUID; import org.junit.Before; import org.junit.Test; +import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisShardInfo; import redis.clients.jedis.Response; @@ -24,26 +25,26 @@ import redis.clients.jedis.Tuple; import redis.clients.jedis.exceptions.JedisDataException; public class ShardedJedisPipelineTest { - private static HostAndPortUtil.HostAndPort redis1 = HostAndPortUtil + private static HostAndPort redis1 = HostAndPortUtil .getRedisServers().get(0); - private static HostAndPortUtil.HostAndPort redis2 = HostAndPortUtil + private static HostAndPort redis2 = HostAndPortUtil .getRedisServers().get(1); private ShardedJedis jedis; @Before public void setUp() throws Exception { - Jedis jedis = new Jedis(redis1.host, redis1.port); + Jedis jedis = new Jedis(redis1.getHost(), redis1.getPort()); jedis.auth("foobared"); jedis.flushAll(); jedis.disconnect(); - jedis = new Jedis(redis2.host, redis2.port); + jedis = new Jedis(redis2.getHost(), redis2.getPort()); jedis.auth("foobared"); jedis.flushAll(); jedis.disconnect(); - JedisShardInfo shardInfo1 = new JedisShardInfo(redis1.host, redis1.port); - JedisShardInfo shardInfo2 = new JedisShardInfo(redis2.host, redis2.port); + JedisShardInfo shardInfo1 = new JedisShardInfo(redis1.getHost(), redis1.getPort()); + JedisShardInfo shardInfo2 = new JedisShardInfo(redis2.getHost(), redis2.getPort()); shardInfo1.setPassword("foobared"); shardInfo2.setPassword("foobared"); List shards = new ArrayList(); diff --git a/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolTest.java b/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolTest.java index 664e767..bc0bf14 100644 --- a/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolTest.java +++ b/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolTest.java @@ -11,12 +11,12 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisShardInfo; import redis.clients.jedis.ShardedJedis; import redis.clients.jedis.ShardedJedisPool; import redis.clients.jedis.exceptions.JedisConnectionException; -import redis.clients.jedis.tests.HostAndPortUtil.HostAndPort; public class ShardedJedisPoolTest extends Assert { private static HostAndPort redis1 = HostAndPortUtil.getRedisServers() @@ -29,8 +29,8 @@ public class ShardedJedisPoolTest extends Assert { @Before public void startUp() { shards = new ArrayList(); - shards.add(new JedisShardInfo(redis1.host, redis1.port)); - shards.add(new JedisShardInfo(redis2.host, redis2.port)); + 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"); Jedis j = new Jedis(shards.get(0)); diff --git a/src/test/java/redis/clients/jedis/tests/ShardedJedisTest.java b/src/test/java/redis/clients/jedis/tests/ShardedJedisTest.java index e04a998..73532c7 100644 --- a/src/test/java/redis/clients/jedis/tests/ShardedJedisTest.java +++ b/src/test/java/redis/clients/jedis/tests/ShardedJedisTest.java @@ -6,12 +6,12 @@ import java.util.List; import org.junit.Assert; import org.junit.Test; +import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisShardInfo; import redis.clients.jedis.Protocol; import redis.clients.jedis.ShardedJedis; import redis.clients.jedis.ShardedJedisPipeline; -import redis.clients.jedis.tests.HostAndPortUtil.HostAndPort; import redis.clients.util.Hashing; import redis.clients.util.SafeEncoder; import redis.clients.util.Sharded; @@ -41,8 +41,8 @@ public class ShardedJedisTest extends Assert { @Test public void checkSharding() { List shards = new ArrayList(); - shards.add(new JedisShardInfo(redis1.host, redis1.port)); - shards.add(new JedisShardInfo(redis2.host, redis2.port)); + 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)); @@ -53,10 +53,10 @@ public class ShardedJedisTest extends Assert { @Test public void trySharding() { List shards = new ArrayList(); - JedisShardInfo si = new JedisShardInfo(redis1.host, redis1.port); + JedisShardInfo si = new JedisShardInfo(redis1.getHost(), redis1.getPort()); si.setPassword("foobared"); shards.add(si); - si = new JedisShardInfo(redis2.host, redis2.port); + si = new JedisShardInfo(redis2.getHost(), redis2.getPort()); si.setPassword("foobared"); shards.add(si); ShardedJedis jedis = new ShardedJedis(shards); @@ -80,10 +80,10 @@ public class ShardedJedisTest extends Assert { @Test public void tryShardingWithMurmure() { List shards = new ArrayList(); - JedisShardInfo si = new JedisShardInfo(redis1.host, redis1.port); + JedisShardInfo si = new JedisShardInfo(redis1.getHost(), redis1.getPort()); si.setPassword("foobared"); shards.add(si); - si = new JedisShardInfo(redis2.host, redis2.port); + si = new JedisShardInfo(redis2.getHost(), redis2.getPort()); si.setPassword("foobared"); shards.add(si); ShardedJedis jedis = new ShardedJedis(shards, Hashing.MURMUR_HASH); @@ -107,8 +107,8 @@ public class ShardedJedisTest extends Assert { @Test public void checkKeyTags() { List shards = new ArrayList(); - shards.add(new JedisShardInfo(redis1.host, redis1.port)); - shards.add(new JedisShardInfo(redis2.host, redis2.port)); + 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); @@ -143,8 +143,8 @@ public class ShardedJedisTest extends Assert { @Test public void shardedPipeline() { List shards = new ArrayList(); - shards.add(new JedisShardInfo(redis1.host, redis1.port)); - shards.add(new JedisShardInfo(redis2.host, redis2.port)); + 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); 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 8f944f4..9ce403d 100644 --- a/src/test/java/redis/clients/jedis/tests/benchmark/GetSetBenchmark.java +++ b/src/test/java/redis/clients/jedis/tests/benchmark/GetSetBenchmark.java @@ -4,9 +4,9 @@ import java.io.IOException; import java.net.UnknownHostException; import java.util.Calendar; +import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; import redis.clients.jedis.tests.HostAndPortUtil; -import redis.clients.jedis.tests.HostAndPortUtil.HostAndPort; public class GetSetBenchmark { private static HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); @@ -14,7 +14,7 @@ public class GetSetBenchmark { public static void main(String[] args) throws UnknownHostException, IOException { - Jedis jedis = new Jedis(hnp.host, hnp.port); + Jedis jedis = new Jedis(hnp.getHost(), hnp.getPort()); jedis.connect(); jedis.auth("foobared"); jedis.flushAll(); 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 95a7991..4783754 100644 --- a/src/test/java/redis/clients/jedis/tests/benchmark/HashingBenchmark.java +++ b/src/test/java/redis/clients/jedis/tests/benchmark/HashingBenchmark.java @@ -7,11 +7,11 @@ import java.util.Calendar; import java.util.Collection; import java.util.List; +import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisShardInfo; import redis.clients.jedis.ShardedJedis; import redis.clients.jedis.tests.HostAndPortUtil; -import redis.clients.jedis.tests.HostAndPortUtil.HostAndPort; public class HashingBenchmark { private static HostAndPort hnp1 = HostAndPortUtil.getRedisServers().get(0); @@ -21,10 +21,10 @@ public class HashingBenchmark { public static void main(String[] args) throws UnknownHostException, IOException { List shards = new ArrayList(); - JedisShardInfo shard = new JedisShardInfo(hnp1.host, hnp1.port); + JedisShardInfo shard = new JedisShardInfo(hnp1.getHost(), hnp1.getPort()); shard.setPassword("foobared"); shards.add(shard); - shard = new JedisShardInfo(hnp2.host, hnp2.port); + shard = new JedisShardInfo(hnp2.getHost(), hnp2.getPort()); shard.setPassword("foobared"); shards.add(shard); ShardedJedis jedis = new ShardedJedis(shards); 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 ae2f024..f8c41d7 100644 --- a/src/test/java/redis/clients/jedis/tests/benchmark/PipelinedGetSetBenchmark.java +++ b/src/test/java/redis/clients/jedis/tests/benchmark/PipelinedGetSetBenchmark.java @@ -4,10 +4,10 @@ import java.io.IOException; import java.net.UnknownHostException; import java.util.Calendar; +import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; import redis.clients.jedis.Pipeline; import redis.clients.jedis.tests.HostAndPortUtil; -import redis.clients.jedis.tests.HostAndPortUtil.HostAndPort; public class PipelinedGetSetBenchmark { private static HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); @@ -15,7 +15,7 @@ public class PipelinedGetSetBenchmark { public static void main(String[] args) throws UnknownHostException, IOException { - Jedis jedis = new Jedis(hnp.host, hnp.port); + Jedis jedis = new Jedis(hnp.getHost(), hnp.getPort()); jedis.connect(); jedis.auth("foobared"); jedis.flushAll(); diff --git a/src/test/java/redis/clients/jedis/tests/benchmark/PoolBenchmark.java b/src/test/java/redis/clients/jedis/tests/benchmark/PoolBenchmark.java index ae1ffc3..aa4e7d7 100644 --- a/src/test/java/redis/clients/jedis/tests/benchmark/PoolBenchmark.java +++ b/src/test/java/redis/clients/jedis/tests/benchmark/PoolBenchmark.java @@ -6,17 +6,17 @@ import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.pool.impl.GenericObjectPool.Config; +import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.tests.HostAndPortUtil; -import redis.clients.jedis.tests.HostAndPortUtil.HostAndPort; public class PoolBenchmark { private static HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); private static final int TOTAL_OPERATIONS = 100000; public static void main(String[] args) throws Exception { - Jedis j = new Jedis(hnp.host, hnp.port); + Jedis j = new Jedis(hnp.getHost(), hnp.getPort()); j.connect(); j.auth("foobared"); j.flushAll(); @@ -30,7 +30,7 @@ public class PoolBenchmark { } private static void withPool() throws Exception { - final JedisPool pool = new JedisPool(new Config(), hnp.host, hnp.port, + final JedisPool pool = new JedisPool(new Config(), hnp.getHost(), hnp.getPort(), 2000, "foobared"); List tds = new ArrayList(); 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 6b523fd..c6d91c2 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ConnectionHandlingCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ConnectionHandlingCommandsTest.java @@ -3,8 +3,8 @@ package redis.clients.jedis.tests.commands; import org.junit.Test; import redis.clients.jedis.BinaryJedis; +import redis.clients.jedis.HostAndPort; import redis.clients.jedis.tests.HostAndPortUtil; -import redis.clients.jedis.tests.HostAndPortUtil.HostAndPort; public class ConnectionHandlingCommandsTest extends JedisCommandTestBase { protected static HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); @@ -16,7 +16,7 @@ public class ConnectionHandlingCommandsTest extends JedisCommandTestBase { @Test public void binary_quit() { - BinaryJedis bj = new BinaryJedis(hnp.host); + 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/JedisCommandTestBase.java b/src/test/java/redis/clients/jedis/tests/commands/JedisCommandTestBase.java index 8d92c4c..bf787f9 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/JedisCommandTestBase.java +++ b/src/test/java/redis/clients/jedis/tests/commands/JedisCommandTestBase.java @@ -1,18 +1,19 @@ package redis.clients.jedis.tests.commands; -import org.junit.After; -import org.junit.Before; -import org.junit.ComparisonFailure; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.tests.HostAndPortUtil; -import redis.clients.jedis.tests.HostAndPortUtil.HostAndPort; -import redis.clients.jedis.tests.JedisTestBase; - import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Set; +import org.junit.After; +import org.junit.Before; +import org.junit.ComparisonFailure; + +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.tests.HostAndPortUtil; +import redis.clients.jedis.tests.JedisTestBase; + public abstract class JedisCommandTestBase extends JedisTestBase { protected static HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); @@ -24,7 +25,7 @@ public abstract class JedisCommandTestBase extends JedisTestBase { @Before public void setUp() throws Exception { - jedis = new Jedis(hnp.host, hnp.port, 500); + jedis = new Jedis(hnp.getHost(), hnp.getPort(), 500); jedis.connect(); jedis.auth("foobared"); jedis.configSet("timeout", "300"); @@ -37,7 +38,7 @@ public abstract class JedisCommandTestBase extends JedisTestBase { } protected Jedis createJedis() { - Jedis j = new Jedis(hnp.host, hnp.port); + Jedis j = new Jedis(hnp.getHost(), hnp.getPort()); j.connect(); j.auth("foobared"); j.flushAll(); 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 c7a94f4..8f7ccaf 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java @@ -475,7 +475,7 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { @Test @Ignore public void subscribeWithoutConnecting() { try { - Jedis jedis = new Jedis(hnp.host, hnp.port); + Jedis jedis = new Jedis(hnp.getHost(), hnp.getPort()); jedis.subscribe(new JedisPubSub() { public void onMessage(String channel, String message) { } 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 5e03270..cf0aa96 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java @@ -32,7 +32,7 @@ public class TransactionCommandsTest extends JedisCommandTestBase { public void setUp() throws Exception { super.setUp(); - nj = new Jedis(hnp.host, hnp.port, 500); + nj = new Jedis(hnp.getHost(), hnp.getPort(), 500); nj.connect(); nj.auth("foobared"); nj.flushAll(); diff --git a/src/test/java/redis/clients/jedis/tests/utils/JedisSentinelTestUtil.java b/src/test/java/redis/clients/jedis/tests/utils/JedisSentinelTestUtil.java new file mode 100644 index 0000000..31644a4 --- /dev/null +++ b/src/test/java/redis/clients/jedis/tests/utils/JedisSentinelTestUtil.java @@ -0,0 +1,113 @@ +package redis.clients.jedis.tests.utils; + +import java.util.List; +import java.util.Map; + +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.Jedis; + +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) throws InterruptedException { + Jedis sentinelJedis = new Jedis(sentinel.getHost(), sentinel.getPort()); + + HostAndPort newMaster = null; + while (true) { + Thread.sleep(1000); + + List sentinelMasterInfos = sentinelJedis.sentinelGetMasterAddrByName(masterName); + if (sentinelMasterInfos == null) + continue; + + newMaster = new HostAndPort(sentinelMasterInfos.get(0), + Integer.parseInt(sentinelMasterInfos.get(1)) ); + + if (!newMaster.equals(oldMaster)) + break; + + System.out.println("Sentinel's master is not yet changed, sleep..."); + } + + 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 e9506298f88ac17f0acc63dcc99b4aeec4b62e7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=9E=84=EC=A0=95=ED=83=9D?= Date: Wed, 16 Oct 2013 18:22:04 +0900 Subject: [PATCH 03/70] fix bug in Protocol.processBulkReply() * if RedisInputStream().read() at Protocol.processBulkReply() returns -1, it runs with unexpected behavior * fix: check and if return value is -1, it throws JedisConnectionException with message "server has closed the connection" ** prevent unexpected behavior, specially ArrayIndexOutOfBoundException *** calls System.arraycopy() with length = -1 (cause limit = -1) at RedisInputStream.read() add pubsub unit test scenario : client-output-buffer-limit exceed * Redis warns event(disconnect client) to their log, and suddenly disconnected connection ** http://redis.io/topics/clients -> Output buffers limits ** so test expects JedisConnectionException with proper message --- Makefile | 1 + .../java/redis/clients/jedis/Protocol.java | 5 +- .../PublishSubscribeCommandsTest.java | 71 +++++++++++++++++++ 3 files changed, 76 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 761d033..bb6597d 100644 --- a/Makefile +++ b/Makefile @@ -6,6 +6,7 @@ pidfile /tmp/redis1.pid logfile /tmp/redis1.log save "" appendonly no +client-output-buffer-limit pubsub 256k 128k 5 endef define REDIS2_CONF diff --git a/src/main/java/redis/clients/jedis/Protocol.java b/src/main/java/redis/clients/jedis/Protocol.java index db3d915..6133159 100644 --- a/src/main/java/redis/clients/jedis/Protocol.java +++ b/src/main/java/redis/clients/jedis/Protocol.java @@ -101,7 +101,10 @@ public final class Protocol { int offset = 0; try { while (offset < len) { - offset += is.read(read, offset, (len - offset)); + 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(); 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 c7a94f4..9da4cbb 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java @@ -528,4 +528,75 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { }; pubsub.unsubscribe(); } + + //@Test(expected = JedisConnectionException.class) + @Test + public void handleClientOutputBufferLimitForSubscribeTooSlow() throws InterruptedException { + final Thread t = new Thread(new Runnable() { + public void run() { + try { + Jedis j = createJedis(); + + Thread.sleep(1000); + + // we already set jedis1 config to client-output-buffer-limit pubsub 256k 128k 5 + // it means if subscriber delayed to receive over 256k or 128k continuously 5 sec, + // redis disconnects subscriber + + // we publish over 10M data for making situation for exceed client-output-buffer-limit + String veryLargeString = makeLargeString(1024 * 10); + + // 10K * 1024 = 10M + for (int i = 0 ; i < 1024 ; i++) + j.publish("foo", veryLargeString); // 1k + + j.disconnect(); + } catch (Exception ex) { + fail(ex.getMessage()); + } + } + }); + t.start(); + jedis.subscribe(new JedisPubSub() { + public void onMessage(String channel, String message) { + try { + // wait 0.5 secs to slow down subscribe and client-output-buffer exceed + System.out.println("channel - " + channel + " / message - " + message); + Thread.sleep(500); + } catch (Exception e) { + try { + t.join(); + } catch (InterruptedException e1) { + } + + fail(e.getMessage()); + } + } + + public void onSubscribe(String channel, int subscribedChannels) { + } + + public void onUnsubscribe(String channel, int subscribedChannels) { + } + + public void onPSubscribe(String pattern, int subscribedChannels) { + } + + public void onPUnsubscribe(String pattern, int subscribedChannels) { + } + + public void onPMessage(String pattern, String channel, + String message) { + } + }, "foo"); + t.join(); + } + + private String makeLargeString(int size) { + StringBuffer sb = new StringBuffer(); + for (int i = 0 ; i < size ; i++) + sb.append((char)('a' + i % 26)); + + return sb.toString(); + } } From 52bb245203f066818ebdd8b36fcfe63009c7e764 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=9E=84=EC=A0=95=ED=83=9D?= Date: Wed, 16 Oct 2013 19:42:29 +0900 Subject: [PATCH 04/70] * fix bug: test expects JedisConnectionException ** I have mistaken while verifying seeing Exception's message * remove huge print messages --- .../jedis/tests/commands/PublishSubscribeCommandsTest.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) 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 9da4cbb..7855110 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java @@ -529,8 +529,7 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { pubsub.unsubscribe(); } - //@Test(expected = JedisConnectionException.class) - @Test + @Test(expected = JedisConnectionException.class) public void handleClientOutputBufferLimitForSubscribeTooSlow() throws InterruptedException { final Thread t = new Thread(new Runnable() { public void run() { @@ -561,7 +560,7 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { public void onMessage(String channel, String message) { try { // wait 0.5 secs to slow down subscribe and client-output-buffer exceed - System.out.println("channel - " + channel + " / message - " + message); + //System.out.println("channel - " + channel + " / message - " + message); Thread.sleep(500); } catch (Exception e) { try { From c5a5e1419b20e20ffb118059a818109da288ad2c Mon Sep 17 00:00:00 2001 From: Ivan Dyedov Date: Mon, 4 Nov 2013 18:13:57 -0500 Subject: [PATCH 05/70] upgrade dependencies in gradle build file (to match the ones in pom.xml) and update version of gradle wrapper --- build.gradle | 6 +- gradle/wrapper/gradle-wrapper.jar | Bin 13031 -> 50514 bytes gradle/wrapper/gradle-wrapper.properties | 4 +- gradlew | 114 +++++++++++------------ gradlew.bat | 54 ++++++----- 5 files changed, 91 insertions(+), 87 deletions(-) diff --git a/build.gradle b/build.gradle index e9076f3..eb73a5c 100644 --- a/build.gradle +++ b/build.gradle @@ -11,8 +11,8 @@ repositories { } dependencies { - testCompile 'junit:junit:4.8.1' - compile 'commons-pool:commons-pool:1.5.5' + testCompile 'junit:junit:4.11' + compile 'commons-pool:commons-pool:1.6' } @@ -28,6 +28,6 @@ uploadArchives { */ task createWrapper(type: Wrapper) { - gradleVersion = '1.0-milestone-6' + gradleVersion = '1.8' } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 45bfb5c85ea4b9b0d02616718f2637b2075acb1c..667288ad6c2b3b87c990ece1267e56f0bcbf3622 100644 GIT binary patch literal 50514 zcmagFbChSz(k5EAZQHhOS9NvSwr&2(Rb94i+qSxF+w8*h%sKPjdA~XL-o1A2m48I8 z#Ey)JC!a_qSx_(-ARs6xAQ?F>QJ}vM$p8HOeW3pqd2uyidT9j-Mo=K7e+XW0&Y<)E z6;S(I(Ed+Bd0_=<32{|526>4G`Kd`cS$c+fcv*UynW@=E6{aQD-J|;{`Z4Kg`Dt2d zI$)UdFq4$SA}#7RO!AV$BBL=9%jVsq{Ueb7*4^J8{%c%df9v*6=Kt4_{!ba$f6JIV z8JgIb{(p+1{!`T5$U)an0fVi9CwR`^$R`EMcp&rQVa-R*4b4Nb_H8H{ZVot=H7 z#(J{{DW4ze_Ck|1(EbPiGfXTO}v^zl-H!Y3ls9=HV&q>SAGP=VEDW z=wk2muSF2y_lb}fJxZ}al~$+3RF^U!k9x5x zWyl(8dbQ0`AG$%Y?*M0m+cp^Qa}1udZW_Tm3>qdzZv!1x+<_Uf(p@M@ymKp>OX9|F z#L1je z9d6SUXxx2fS*7N*e<;=+3&t4*d+M`}GIPJUbTo-OSVjvF3WrfXg7*_H3ct9cxJKZ9 zLrMzth3?nx0{#c^OdHM`vr>x#A)-roI0OOn<=2h_wo|XV0&wMtLI5!@**l*_XQ2R` zrLSV49cUPRsX#(O5oQzZaIYwwq8Zs2DLXGdDKbr!Yg?7fxU|>+HHQ`48#X--yYCk5 z2_CBTW9rX2eLQC0%EyQli<87+%+Sy))FFW+RMC{*hfJ$|;#$?pAT~P0nL-F}%M*RxwBh)JT4trq7rR7dHloLmiM^IC{>usB=4fXXH9NMyWznFd(bffDK zE@*_maXO?|$?M^W>jXtsnk2}7g8b8%oLp);SNzqtjlYHDKkJ?J|K42x(kk(o{=Zub zF6?{i>=+HX3r6qB=&q|022@z-QLmMSLx%Up}FGL44Gk+C_QL5BU+!i2(vEvNf8Z)-btUdpVY9ovODm+#V7jjU7Y!AWEnY5L4 zy;^;=x#{x<{pUJOVPj)cXJ>gsJ418R ze{ZN{4Os^?bu@m)^eIMs5MU5c;IIG|=#WSfkfeyP1R(>Iv2Y(9if76Ptu~dWzdSmPFUp;6Ezs&WmP-Mn-9ah*g8e8 znAxyrWhx~~tuF4fFyFI)v-S3=C$HmPHmqv%hb3*;ljbj9zaA_}QvfU@RJCGH%&3Mc=GR}sQDh$UWT-8|{1QwhXWO-dM z3?^C@cbP^-hfFljgacs|7mE%a1FSMK5?o1{VuaVB3iP=LvFEL@C0pfwirZ4SXxMUy zrMG05M!9CU@G7-}bgjI%x$|_B9Z@Hc86jXlPhZpJfk@$BToMpqU8Y zS7rRkdp>e0{86ZjFbE^zkdwV*R|JV3EhCJcqjJlZ1HJnbe0I+>a5?HpHLs6A`4&VE zZkHUK@cLRF?y^Gi~ zzERBcPdAs0R^=N{aeUhK(Oc+@?mb~Y)__*Dt{8Wawz6H_)v6niTA_*_%)UP`0`WBL zFONOa&+T9+RMF!QsgKq(%Ib;a-!w+*&V)Y#Xz0(87=H{^VBk3UVeed$SFCL{IJMl-`1FQ@Es zq)F=J+jn(WH_*lNW;=>)d5ZFyL~O+t;)Rex`&~h0ZJ`wg7K@*lu0E7;tx>KLWPduY zB{4G}TQLJE$Fp^?*3raESC`NSpmv`$M^ zR?`+VFj;fQu`)I4O1dHwa_R-0y`qHjG*yT1*ta##G_W-;1ira)uP6}+r|OX64}vD7 zCfB#p>H^?YEyF6K(H( zcSh4u5_|{iq)=K{S8Z{@n?&h}u!l2^EP#?v?Obp5kDl`o9~up%2*s>1Ix5~kT~M3` zo9Mg;n$TcwaN!PHHbuUUw3tRqYfjpz$rm9)1|S{rtPnG|3qao}1W27Wig_4j-(rTjVi`D@Hu z`P>h7i$K>zzc1rQ!~L?29sG(`4ewg^)@Jc)II0KI)@q=D4CEaX%j&RlZ>Dhv0p=|f zDJPQ~ioTP^ju2_j2(V9haP$r!cTNIK`eUF|-}43c=4*G09&bROE80IECDekrK%+jW zBayIlJSDqrri?dj#ZGRQI45{XfBLkOiWIkGb#Tk>GU0NMA&{q`1jQe9jlfJZSTNF_ z5nD5A=Z=a%6uCagCu3np^0R1ibyV8p>-XWfFJK2Gb#o`L=pCm3Bz0F-w`5gv7zJaA z)RS8mWR&`<;DgOxA@S6FQ*5HVF=Pi6>}viGQ3jbA1*0gz7vev?ig9gVhr!>t4e76E zq5scb<;TCmT2XsDGfQ(RVj)A|h<&2OW-AJrbhweQvr{uOf)AdTJN|xO zAOSplNX(IEhc4?4!HsA&Vy7Ayn|y;{2-yn=}+S<{JboP z+O;`IR0`XIjUt&s+%;#~ImRt_GtRFatr{*eLSOp`M&L2~I&K?Jn-<|hTDADdW0!CI zT`L(i=DpZ{m#h7}m5b)AA2rK@4IrsGNhTCLuA(5#C4^ihsG8k9wtfgz{e1{i2dg)4 z+mI{R5E#Qkbkp^PpXHo%=j>nj&GC#hXN&B=ng^Nz`nHCfc3$|&N@`tY-`ccR_&0zX zWOMW?UqQVp6a|9)%p$rhzNSyZx#rwXmnhl-bz2n%^a-VY_->1Rq3M@UM*B73Rbh3KcNU|sUv}tj}yqehs%OmelPMB0M zliOnQ$*!7!%0vXViN+eRgc?|(1-`Kgq(g{Uq<|t%Bz*Q}Y@)~Dxqfxxh@oH`C}F!u zVKM>}SoSAuA}tUnZK%W}VFDOojbWmn1c%601hYWY6h!VJL@bC6^kD6@5DA{~rDbc` zz$!9AztbeXVgISB%D(uPM}Of3_Fv4&^q*DrzatANL%Y8i?%&Z*jK+mCsyf=YZKlbf z+hn1Vj7%sLh~;}k0J;qf&74dzBAF6hP=~yIQm6^14M!6?dhV;l=Kx&n;12=r;6bdu znKAcoswa2O{OPE5Gq3CJ6W7_dZ0Fg_o$rq~%z)3=pMwn1WgeoUs1j^hLuCL?_E++U zUl8cV_e>1#s5BJnSsHgKVH(k3juJJ{(latn3c<1EL^IYNxQh#yBCy;2!x%aPorztP zjJ%Y^H`Yu{q|z#bbRlXv*1|BB=p}$j7!c7C(+){=Hpz}swAa{;Mv?w7=0z0L(939t z85~w@r}dG`qJ(r7Jk^{@x!g>S2N}H{+N(b&vsMA1Z#qSh8<*eRxUKlI&Oa;*Luox`bScaqq#hN!IK3bgB zB`i9szi)5mm7=-Sfccdew3}(DLGfBO@@O!zHa3jAA@asvg`6x7z?j<@r!?HkxDGl; zA4MQQdP?iygX<&#Pt&fZ>4)tZ`4;uBW9N{x=T%*k!S#nf$>KRy}>6yQy?^(R#_fv9|9gTaH7IwKpOb=Xo?gi;akww64+&sf$z|_oI zuZahhq^LF60F>Rc%fkD!7@rigV#kVa^+@?Px~$YsNR3)QPBOZ(f96@IYTBerb(63c zz>}2iX36tDclpTaec;b}1pAap^JYHW{v(X;O)ygVC?+2IJ<4~lV|hQY9F&fz1UDoX5607wu*7FLP=u_rpZVqb zT#DD($Gu8`ZL1j?)6BP@h^#Ro?+wo>lacs#^O^h3c%lrP#Tk&f76F66$)uko$~U{i zFxE>!FOr^ZN46l7O(fh3ODY*ED*fGB+br75!b zD9RQm9(DT(;y?RI{yGj7%_y8*a2V>LYb1M$e5qJezC!U zR-eGYfjYJ!gD34F6x`2&w_<7T-E^D#yUo<&OS zc1dmXr~k)`Uat3yd(Xob>E|E8mmLrXobN;jv|@g)D0OHYJ1I8rlyDYAbYvcT+%8Sj zyDTth@@-~MGjYR*#RQ^#3j3XXL*1dUkl@#l5XF0c^E)53T$DRY=-htu!q=>j*#p?F zSCUz~s8xl*&iOy(^Ngfv-XmA*;GBW zd)}`C2W_ashy}02xm~3DH36VWBLJ10Il7Id6nt$~7hora6?Ils4LaFoFuZm?UJmAT z-3&$(^VAx-lSbLl_O;C=Q{eh>+zEMdU5!VT4k3ic1#w_+)-by@fE^>1sU&)xy_ws4 zq>WjPpOyZ&8o<pKeHD!`!)ch6}P=2?*1GiR*lYgDdHl?x-o7`hcV{KiLo}+xZ%sf#cl0pH_6K{bq zJ^!4l)|nnxEEZo|+C^#VtxL;YGSGqvxx;)O*@`@qRekwLLNq6DAOt*bI;>KPM!}** z*1Fv^$Ob1f_^3hhEllh0rml_3l0gYu~zep zi*ck$)DHOCTC>mzKw9~QfB`qEqwJY9v`tosEI@3GmTICiWK7~mMjAyp`O1}(QXfHS z>I0_glIrf2a);VQV~kDfQmL&R&8yX3mcimT!67&}8=24)t$%BU*8A&@Hs=$k7KZC# zTYN^qk95D4#q5?W`MM}sK)U$CCNE8|C%e3CXNafxch(eEGL_+Piz|4%*V5)8zAF*P8JmMUCYz%v(Y>ssFWfrj)^We?D7Hx)U#H`)OGH2IiptVS z2*zF^F)h%($!r@~7>1<19H#-i?~NUfQGG)@kw(C!+efD4E|L8jmIO9uP6su+9Vme) z_Ut*1ruchGUdny9ogKS9J#EHo68*jLp!D!uee*%?fo0~NSf8QchIDo8oULzpP`tQ3 zT}c@f(sqT>I-GJSSpkR;CSJA;>Vy5h`}yCCQ(YrT&O4d3zYfl}u(z6VCE6!F;F*76 z9j0J8{ssW#uLmNn53($aP9>wroVI83#TbxmSWb`TR@1fFW3)dyT%j-X7{NjG)mBPt z8z+G-hb{;ve{Nq7hNHIcwvmwURm%F#C{Jia_1Xs2a;#VmHY@`q_oFT2!7gKT1L$_S ze4X%%XFJ_o4wSPX)sr=BrRLuUVxO2k%NiH>WW1LwEI*K{3Gz#YW*r(J_Sjb*2iasE z!QPPy6q}ec#&eKI67nf|({Azk6jE$x>w`_s;hWgIE=e_ovbyj_2_8Fh5WIi)Q06ex zK_rmt=gfYqkR{}_CY95yTSFZsiL!^3CJvV4kYI{vBVoSPTEKg^5Yhjh6Q*qkbl3Z` zxrAGk8TrF!V-9SzKxWt&%eP$HlsQs0ga${AUpu%Lh1E=Z@$g5?rRAwX)DueM5vQtCS;kk&S~>Q(zA}iXj?uYPSN2g;`3 zr)tMR>iS6fS{Bt4(+lHMq?p7GTTP4Z-3CxC>~=?1uq|2lu9RZ)h-_brR*o4NcMfZt z>9{-CUh@iJ&~YV=FmZ$@bUu>LCHA9Bs#;S-ykkxyG&;)aSds(|=LmlnnN>@$5#y6f z52PWa7ov;Cg&4n9^e8SUIxgmgdaGopW=?jeS>5hOHimVi!ixB z&L3V_Y{(6VZK+dE@^d&Lp5biwj+@@G6Y|R6E7bpetG}Z6lodOa3o-q%rZKdO?53uHjV=~>M>LX0e}LqA0#;Wi z>Fi99*d>>vgM$sFrG?jSll(bPvE3F0SBr`E-F%7bVw3zL1%G0T0xl)LpRL!9rRcZ4 znW820$m!^d?*snLNAF9IeeeBXsy=xE{l^`V_?cqSTM64v;<2La{6~897oU{tV~NPl zGm`(o6A}0+qsbLx@tZ>YcEJtAnfK!lVXycvt&CpfQ~O{wVSh^PZ@v7R)Oo=a~+pMUfd_P;?MMbq0W zn5d_K8KCPRQ7_>a%$}tW5E}*pRTz%)226#|i#S263Qo`)>UAV&gS!BZJCB^* zD)9KKv*&q?w2V58r&^+i9tld&yUj=}t)c(aVaT2V_ry>mvCmQ%m0*}^30i0^;xDFP z#GK)q)7zR!wDLf_FI+hJNHi+CQYLx%kd$c4;YQ(OP45JYT0gFhYtmR|&A;F>cY8aj zC{lzsg>cZL@c@)hdyj$RA8y!D!n)(iTko!hyL)Wp!_&LE&D6}bxGl&Y_tbnuS`jQY z(f*_-X`iYEoxr&a*76lkZCe-a5AIOXCY># zbiVD(DT$0EI=U*Yf6Sl8f6>23pKEMNQ4Ajg^{ZHghmvEQH$3o{ms4*o6hgYvpNE+( z#AZ;x7E{DM`7Hvh|Bml=1j#gyl{K&_{-jEI@)yyKG&XZ8%52}!B`ZE?EL7#WtMBKol?Mvj2saaE<61>mL%<6)IXN}3^`@*!@} z341EQrH}dRV~Fjv>F3@mjwCOV$Y%oyGr0LwkxkuPb6X#ms0o?9o+d9{x3cbiGKmX3 z^!+;D#Al?M&g?P9kq(7|b*i(XsOwP?H!ElS*uhTDBDKArqGP#E7dcE;HWkvkaEAW? zF!3|NMZb>RCGHa5#)`X}8w)%}Ey|gW@8DUXNsDR*{esPO{W?k2a}RxGK|616o0)}e zw?Os9aROYmtw`mSga!UI{x(DS%Vyo@y>JF`^Fi2A{GhSfM8=YCUiq2tRfBwSZeFh1 z8SG=1Ot08%#iR0jnhZp?#@V2YFnQ7qP$zE3&#`>FhsO>}OG$enmf?*FVG@qB!C+bO{M}K?d?H2@pq=}!TIg&Q z<|^+Ey(ErEeOf1wvGI?LX+DEA>A4Ka7Q!%PAW&4a-t8+>1M9b(T0qACQ=f;57D`tu0g(=;a7O*h_Jc4JEypx1gs; zCDX69d|g$NsXEuD1H|$3$ZHE}u3HP4b!9=Q%rqHBgCfvK3>j?XLQkgDUg`93gF?}s zS4$rqaDE(s2IL!2Y@kw=(NL~wa24NU3sm0I71mIjZ>?9}bNl5^Al?Sk^y(`qsW$ER z@g$;Pyb*^A=G{Yrb0a>4vvBBZ5U2|)}iX;AAo6X<=K0YOtm49s4edp~uvJxx$&=o-&rGttC2~o83 zfuN5-wJBS(4plr-Qmhz$`*di+<4KB`>;9BgrbANhj6VsJNxLq5IoU%8vF$2M+Z2ek zTw84Kxg}m}jc^*zK>s;O8dE$R&kkO5>*Y75eKaR2>i5fb7o!D~D0P;E`CzLz<48 zBzH@erfNN`nS4Uy3@n#r)*^n}uKHeJxygl)GV-F`w49%s`cYMPYi5Gahg$5e??^in2I<7 zUKZDwHf#riMrllW@f~Nsm&l0q?KJzSfp9hXd2pb;UnzJj^xc9bqY2zVLk%GU)}?}} zB7(TNFqdZnN}qRsHgj1;xcwQt^<58f3wN(P=y%mH3&}An)2M$}(>TF|q1;N5^ZX`t zd&q8vtB(q@FPC>=6)%sC=t3jOE{U+j(IShmITq`TXA`_QKhoBZ7GXEN9MCEV z+~@7gbqUElkbsjU7o$HOfy49&nNHI)#@Dt#fvePViP1MzItEa|goh@hCZ273Hd#4Xdhb+D?L0E87T>DawyVvc3J#zePjBG zaZj%zUc`L}>#2=d=9E*RS9(6nm|%{&E`OI4~x8fs!0ZZ3b-$x(I3NCjCbUBu$h&4 zvkoaim?yiSh1?-2osDeuCf;fbpe3>H#44}rDb%z#W=Jf-*l&-c4uk{yAX)0;9gvX= z#)Ov%5_L%}8e9yEMI=PVh2w~CbgO6&n#>WB?TO?1h+5Yitr3i}=1JW98CC66#>33g zXG+Th=cRh7?7HQYiRy+vd{ov@)w1~xg@TuyK2?xGWXu88_2%M2@eaFd&c-wqqNP26!WU&USZ z8lIHzv`SrJIVF=z2amJL`aB8>O7!d0X?{4zEM+hWKZDaY!_ekJhvtHd^7?hm>;4d@ zeK2Evnj=*zE(YguNX`-&354G{M`WHLvobFJIa9yg@YweQb2NV_p4&_KA0#<1V4d`|3w~@!Wda7`st< zYW?_t6&a=_{Uf&^ zGZWvYxn={#fj-{6v~}bU*&E+%&Wlu@!G)AUL<|!YF&;Wt5x}BM0*{RdB?B3}`gI!y zj553FXs}D9SFRVNei9isSJcMC!3@^b=ePm!`OM}?eK*P2HgZK{1j$CJKRVD)>81IkA@&{z~;ow^HGAt9aw-uE=tusp@Din2k-hBfMQG|V1erRt^^#(kf zQgupM_mjXiJP~C9gG88#+vMpN>pP3tsvec=R=AjpK6(QH<hWIpOCT{1tvWALW6Lfn1W{#(itOApM^OhR99D@A%6#OSz-s+Q!9QsS& zCI3wh{eNMaMeOZeoL&CX&GLqpcB(FhPA>lsclT3!Lj#F_paHxBrO$>L%mD-~b67!D z1~-olI4)rvJ!SWC8`+8~*2V+>RkNnOb#`h)vdAAyqV9xtx zMECS`Ugw#qZsX6lS$js{u0TT5SH~X`jAmqAjD{K#w8ti!gI&?!boYkRVUWz&lbU;j zpI&^siQ!M0$w;Y8f6pGRQGT1+7^n_FK1n%n#=X`JhmStJDve0KY7S67DZM#qOJF9V zsDSvWX5_Ceg7D?vh5F&(%8r5@;-NmtUM&Z~CdhPHI<~GF>GNyiKPMbBbs?{JaFpUQsE*gVRbs zEv49jG95i*$&=}FTc(jg(zL{cLDWfnG7V?guH&aE6kMsRMlX`f2A_$)&f1YNJtD_G zEQRHuh&2^kQ#&G~_Tdnw#7hD^OP={T-S`-#7hL-v%-Yo+CsrqZStHFQd`|C z8@mVz18m8%DgMB0My7%LL@iHak7P4Ah^U6z1F{v&MJJvISf*T}A7KH-4c%fj=~gT- zHX0-tQ8*3d8Qlj)Rv5#D((4pQe6vFQ5#(Tu-+Z>7YHTlH?qLbF8gNPN0T2b2KiU7Y z;jIP@EeRtqcp`2R$~G6e(rg>M4-2lpPYXVK%YNrH7>6+!ClN+~>M1+G3DYy|u6FqV zRLMQ~o8_{~0L09EDk}#Drv!hg{E`E9y_4=#1q#C#0`sN{g1wMR!Sa`_E$=8l7$jsv zFf#b;9e?<9a6td}ThnPw7AURoVe|BpI*p4em5$dICdDLevr=8O`p=QEhH8?PVXfAZ zbbP^ybvo6rIsgHUB3EtV8lqYhw%UzDJtP{bt^XjXYH_o^OqFd@!kwVvTk2 zBG|Ahenv*#WTt1SAkrj_V~5HSuQ~GpT{->!jrjE-v`Zf|a?upEKsR@Z&l7eVgyDKx zIDZ1gJEvHlP8FUycaZm|AJ9DkFDoYnx0Aj8*#)$Fy;@{GLD$BQAC4M>u!Elq_c1vzSH@#&FR16q3Cxx4oLvwP=f+<@S8~wy}z=stlxT|jUJ$d z7cJ6nZF=Hr*d-9e8FDv5WjBhiytFq%g|TaZWe+eyM);j@Kh4r59@aW>%dyuZ8`c?m zc!k_0dh9+i(|LHI1a_11#?R8l8T2y#;fF1N)DLO;6%Q9a*hU$I7&Q|Ib5;cq%!c5DCI5wVr|1{4;5WVk%7rjfIP8hpujO@b~BuVlr29_JWtJ>hp z7A;x0N@bFp^2W-7ryDSO`!nIbok@UDoUw;UrUz>{_12X6idNYNT|a97;#C4{N3E`_ zl#!ihVWru$$=`n=h^UoGhbts>^OIOi!t9sJYex zcWq{GLBO_(QPq~CfvsV?m~BeoXB4J48?9t`7{IN^B2|pL#%|)|Nk;&(8 zd*p6;RXJJ*U8;8rG}ClE(=G}neQYM7w-S%n4>B$Z>5;c zaaFy_anPH*Iff?(4tOo)x{j(uWciGp(pj(CdQ#uE`^6Y1ad1*oFh&s7K9B@aLIusr zvrQ%{S7R&HqK%>e)vG1@Ygnp=g=GVM4CsRWisf_%v<(c^d6lo&1V8SaHp});3TlFk zG#e?^KSZefsKd{jB?QFNTvMNZINe?VKvNGmoo=CYRU?nvmJz#3kon4YoO}Y15~ii< zw`0%`p{>o+EQ~{}#TW!D&T8Tn7_+A-&mOYP^~>Hl#q^H!spWjs+8YbVgxO25UOsUN z(<7r#ZN-Y|o#k}~8SSyJ4jSgG2g5<;8IK%#EcoU}Wcs;K2RA|6f@+&2uZ&Na1+{y! zT;JvU`mgR--^zFT-XJi$H?~ClDYfY6LhB!_Ny7nx=U(#ANjOQ9v`?>wfw~{iF z7iy``+ne+ZHHI(z9M$i67}3t^eaKrOdU~_qpt*>I&Z?*lwH-fFVF%MF>aY0Bvhf7h zAlI1y-Ljs7H*OPTr(#w$4n^uB3aSI_pVg&-Ocy-|^KzFz4#@0e(^$H9Rh3J`ozlWFj&MQyrIxnfkda8;6m}LjSsPrxErj|osSsJ z&jo8TaWE!yAfCfv2+(<<2A-cY#~I^>HZ4vgd5Ba%XU?;u7MVy?F>|NMPNIp0#2YwiZTB<_ip#a=5n+UbTCvk^-;PCb06bq2hu{kC=ala6;aYD60)q3&7JGDnwT;z^yce=7daJ|-puuzal;!BAu=ok#ta0d{S zOY92%j^NNEC64@f_q2YOc@2K3Ht#+bkWS6Y!U$76?$E(tBS1TRu+X`T2%Hm}5 z$G}vhy#EjY|0ga-lGVSw`WuMSVgUis{O3Sa@_${0{C7C|Ke73L@!2|fe?!sUI;Ke` zG81Cx%rq0!BnNN}RAaayDqtfhT%j2wn*)>dzVn9Q#zt;0E5$3rjmJ8z%IBu%=ye9Q ziu%-+=bG-DKXos@+J71BpU-J{y9vdy@$Ie-Mo?j#JCH#6j@d_NnDSN{J$ImxhG4K1-AAJTfTm@y zkwzeV_Rk%-=W&#uk92?P(Z!F$V^pVyN|aM*!5)ghp6gLgG#}M-ClQ35`vbGLj~2om z#_4u1a$ZU2izx8ddYMF z#gRInDsFTHdYY+T9h!q^ZnfOxy2;G4E6k)B4e~PG{ge2GZ)yuUx}yanU0KWTuO9hM zAl4TT(^-N^1gg3mHB{CxW4JKcO>Cs{3~?3jBrL*J%hyH&b%TSTTfw8KEq-*gOqL&x zBZWS*BO+mH>r{hgLv@J=;?sO_9}yLN`zURJ3d(e(mL*kX^EqTO`HIkVlM}zQ(-hXO zS>mk1Rq9_~1CZH`7Tr>&0%wz*WIxwF^^1D^DWSKD)FAOaHzV})eyPyk7lnyNSfvfX zvTsJ$<&E_C92MF>*AHiq@?)`Dn%#|_Qh za(?Iz3f?M$e=pqHe@G7c-=TfhAzl1=vV{LG^mW8*weTRwsf8xSpe_(Y6;P(BTOe)e zH0_Qa1=sMjam$cIbyOuZ*XZDtWbcCGoVO~V+mU;qe0TM3;7?~O(LA7&E*(98L|$`0)graBHY!{tsoLS4* zluf$Jxt+S9_sS4?5D}yUJ0nggbdNR+!=$b!h6pOJ7%i+~+c5ZwSf+{kbP-D&0%eUX zQ~3L__Ams-qVs8?shPyVRnFEI9Fp(D@&g=u6(gt~b2;Tkb>z~ogt}P@EsP&6uY>iG zzr;6e=_=-iC&naxoa>OxsN>Eu*q=F0tZ$tHiNTJTSD&^~LgBrI>2_Q$j5HW}XAx^ym9D&~X_ zZ_d}T$`AcZkQ>;eg#ldX6`u3%Hka9#NRHaAu9V$8sxVSSb>3ZcO(KQ%An>4%cDST>@~&74Zl{1mEkXEVt7jfO7|_C#=ks<~N1E3-dd z9qn~MPSEoiE>UWqUA(KL#Q-MurE7nxH_S+FA25TbvWkZ}*8HNVj^tZ7R=h-$QaqQY zlM;O5?N+dZ=cPqE@}}AZibpMLO`nEc^Y&;^n3PLhyv)PH-4Q&p?wn>>;u;mqxC{*y zJFao4I#f74vU#W3H%_)UtuFXq$XfxSC|+6m1*M}im_6&DaXAqq@;?u8XYrceVyP}w z#Fx`%3{x|1G;_=f72Ui5ejJxJiW@F=zijT=G>-*gO?}u=Bwq`7*){XtvMy8Gg~t@p zH(XNd5Dc4usl=7Gd0#PxSl`e*Fm^EWvmS!Eo!@E;teuWOvo5$FfOC-UC&Lc7ehm1) zMDB2bI_8QRInX&{{5W8eoF?xBqj;l}gj-1jgb%adCJ{Tl&|!#Ym?<~p2G_bH6dSWr zSwDgMT2d7X>z|3<#wCMIK#uwVyE4T9*qY|K)e@~7tu5=+7U-ehaTd$0=re~GG|0;w zn(1QtNXrxoDaMvftH1JkJuxOZcjC|+%WUZpQ#facxj4d;jRVyix$Ge-PwLF*PILR$ zu|tmQV&Q(5I(`M|bt(@#lKQNQ$)DF@!D|LeSgnUd%|*-32PxWHB={GuvWjv}CbLOcpbin3wj(wkwzN9OC2jsj2K+KWXr)1Uw7lIYfp4DU}iJ|6y zWsYq>Dkcq~r+WFGO&6ZR&t0p$tqB&~%nUc3ou{)6oh1SGfeR-8W88{uGPelX-T-ke zk`7;RfYs4s#!&gfZyvhXNf;LkP)iG5@iIpnJ?xcdtgxUc&Kg_BR}ZJ3XWAinV$R) zekh20+d^x|)cdR~bO$Lwyi`YnOZOBa7# zzs9L-LwYI;h*DF2&7Ld$QSF)^U*^T6`wCZjm~2fVFHI~TnVO4YWA>)R+=Zm2?6A6%&V+igaN5`0 zQ?mRv#Ul$=hdpMH$oOb7jIGKWM3f~!?3-=X_7kpT{GtHDzk=oqAJ10Y z&yvY$`2V}@z(1s)|Ly4Usd3Uk(?I{=XCY>ej-=AApsK77rRr~}45R|pwibhcXlQhk z$~JOMk4Su2yTlDUL7g9Cm09`lbuZ!6l02mU)YRuXA%yi{Db|l zi;hHuv<0(K38!#VRt(yIZAFxQy{$!*jYdT@7p>hFX+1#9U#rJi*qt@RY^Ml!s-Aur z18QcAHkMGt^2-^xM@bI?m2rOM z;Wg#_KPzwfXjRk8K)~k^XOrE_^T?AD$z&}IRog;`Xu%~W(x6UZO)woHQPEKD`?(y+ zy(_yx7vn)Kf_d?+Y+}vop1+$Dr8U|JtR}Oh+SY~2_01TA?jSR}REUWo$^F_~ zugzs8%a_p4A^^_N8pbR~8jFsDb*Po)3YQw!)kk7w7QNWJ(A`eaVbebZcD zD$|h|OFU5+OI_a=$}~f~F%Z^*Yqfzq?Q+m6oQh7knGl%rzs~@@?7OSVttd&2ks4QJ zk&9P6W~DtmRXgyLi`xho4m%Z*P0e1JW|v!fUmQe5>Ig6{w=0k?%b!4qWOe2w!#)U%&09pluOgJ?^0+fb$YofO zg=R=-YjIBzBK4bmMU5M;4aL^>$ zDbnQ7!@GBME=7F{8t3qrCEO@#YLA95++Nj3`N{@WT#=z0oL0DRz&{lQv9cC%1NCbp z*VFAPc<~|RCkLqx7y}%~XLC@+<;B%Q>R|MDys5OPnuK)j<9lCF8d&(3Q%BW983-1X z`Hye1WchSn5>peL_Xx+2i@PnSOXOyN%|ELKhU^Ty#MjcJ)vTgVB@gzSeYlQ?zL1y~ zQK6-v$vz+liwY^@S<;0oKVVOy7d?v`QqjU>Rlh^8Mh|)u2+-u?n?(Mj>)AJw8UC1Y$A?R3sfBfV?JK#4=l@63iu=1w;Qdlhdme* zzj61I%uOB2h7+EoD2|LiKR}f@3_aX^)@FF)9)XREew@~1S8z_1Adp`vcX8D_!;{oo z!;|N|FnfxqjbJBFVR$koHiADY>B!g!9X+a)n-4@?gW&e$K)VhmVi2dEk+mzMA{a;> z_e_~37jCy9e)Q0$?@xeQC99Rp6*9lV`VlA0B@L{hs8-7r_=3Ypf7LvqIfyARp3~Fv zM-_n|NWvywevkTPQImE*(;qHbK!Ubb`9%jHOAPHvk$Vo#^HA z`nbpq)D|YG&Vyzq)9llv!bTgC#-+l%#m>lYP(QH;8|;(sFoc{zs%rCquMVlv%!JG<{Hy}VO!`K#* zge&eKsU*h6Kd=>D!xvqGT2&dL*(-uNuYktS9g5ctv!z|uz+>0m{ZmeG;~D|=k?p! z#GOwKXThlmC&U-%cr^l+fRBGOv^fK)bJl$U0Z|770pa?e>6m{h*&~y4Ffp*^9>t$q7<%)Yo}wk3F6$Az+Vv_p0n_=5Njw6W;vUtT zX&TZr?7QuHDWy9EM%Bz-zPhe_t9+!*uUaBB>ZUF8NRBn zF-pCG=L9u=m5IW6H_^zxLoB6_Dm^oNH}3fjF#%Ffc1Dtz0cmI6G%@3CZM3)e4)dm2 zS$kmXiA~a66gMkdpvl)?g}!Tl$B~1&Vm>eUw)7qlcQ&9cExr&DmngeT16>rVW#)#8 zXZ>d3`8Ju1jEjUHGJvdDiXGM1m)TF3@jt|XC?98IzUN*fuy^$j? z6A2mJ2Aun4;H^(LV(Qs*@_OLrw>7QZv?+&wg&3N~O|7KV&*@JE2vcn|0osoE8M(cQ|KEZb427Yj^-JTRpYLrd=ZtRBvVCO6=|EIB%9K-;{+q z*m%nKd9e9v^gXiq8uXpg_~-71d5QuvY5WU!24Qo%rL)$StgZju)I+YA|erFq502iPAbdAQX=C4R@p58(LWAzS zP*10IYwDH6p}ESu>g~f(sju*pRhc=%A#_@8fld=@UzTG>yV^a$x^=lwPJ1E-d8w<~ zo0#yc`BL&e%peQgSn(NpBX@SbS^XL8VSi$YvVx#fIRzSRXVgbk`!0a9lo7%_Ec1kop#JdZixt!qcH@W&xl~?IuM>}jGZpm$ zujoC~QHWVImrO01BbhtSa*SW#^VVW%cn2XVNhvF>wIyXdCuQE!%NG(D61GiBp1s2i zvsx<*yjsM0<{=L1-Qjm8Un88rBpv6v(VV%y1Y+tvw9iOMtA~u~02L74-~}}t-@afp ze0&h`;Mj=+8R6SQn$+HAx~s2jz`A-I5V8iOF}hf<5Uc9gIJfa1ThLo1w523X?%B#r zzi*CiBhkEDZt1-ZcWY&lg5U6m`hlvxEq5C@j&&P2i2~)pF1H;Z^}FfS`@ObaXN4QWsG+?$kOG2?I$+$$E*wIy#cl!03YFHAw-U&e z-Wp0ZK04v_1jTJFq3fYbW07eiXZ3FS`M&3&fWoc3(8rCHN}kN{Wl(}Hzfjb}fmfB7 zO8d}Y4rY7g*)lSXdTVt8@ceQdF}Aj|J$~mx7E7A_0Bv7Mh)y#qof^H`1`@xpJ%?%c zNQyrGX|lDJ(sQUXEx#R<4c!;7B5V=lHZN}P=-a;bI`Au{D#3*se|+X;F7CMDjbV%M zRr8{QPt5^#CwG0+?{bjvSA+g~2p*AbMOCzztwC4(VvD)v$!eA!$fbi(F9Jj%p?~h2 zr{YX(m(+Ht(z~TEQUwm1buJw6%7m(O?}0yh^3Hv>9H zzDR8*{1|7~;yd92_>0=^5;RLbf4UwEFScPHfTEANKv9f4#7)r;M~FCGNrM^7GW8-J zdtc9_OVnQWiYtEgrxcx1Vza!kT`CQeH7D%KiekbA6{1rrVdFumBc+)awo{8N&#|eK zq<&V}VewDn4euDKP7yi-(%5P=AZNrDtl6dF1A`eSRh#%SZuVma6|)TO<&lbR7|y=9 z9Bb$at4k;fn>FGtTE#JRhhT_SVV*3c^;+d(vre@$R=1u%t(no?^*1Jk9O2GM8kg~_ zO!8>`b6!=KRtk$~n7WH|q0Diu)9}V%HK|k==n_u6)v%>SqLeCr-&a|aJ z2mpNJrIB8@0<{HePvF9?sNeT+Z1y`9UM(tu^ac8~;LcUJCbi=A2d=dyMDE<87bIaW znPBv;wh`jlG9+VNM-Py5?U5}POYr(7b3gt~nB~e%Bc$}X-zt1wf4O!3qoR}kpB0_- z|7FkV_-UHJ;P}4{ELA4P6{yFh)ug25N5@9#hQ}s%l@Y1s)u6x8D>AVtG1b(waMZG} zC_1_$ASyAjFtHubP>oE=$TLtk$}`Hy4NK3Ky^oe)uKR+@2pnoWa_(o;o7kQPFp@J&h# z3Z{e1xAqgH7v&`@*+3rG%8gF+27UHl$Q`Bfa{ebWGMU+v)3*{*BZsr0{9+Wz$qe7^Mm_Hae|{Qj4R>pv@PO>C|H#c=hn z+ruwz3=cm|t>Qo76Z3!GE^Pdl$k@bH)WOc~(;!IB%HHhL+{*pajP$?d#wluc3TU6s zqpA7^T%%E%dHEt=5*}8Rg~SURV2E+0X;7`C-aI?94-+0_sx*=Xw;g&I$*22?w&GYO zE`BxKeWN03W##2$on)=6TQ%tF`T(zq{SA*(u7qwHZKyUtwb0x+(SXp&w>>&bl`US2 z19St zwk^6LTv8;knrD)kO58kB-D&v}VbWOPj;;e=5C$+R{Wb{LxfMMeR@{frJQj8iRO*N` zc0BLQe{+JT?K8#VYXob%fI{3ubvpX$8aAoXy%-OoiPy@!cj4S>cAWEA(O963>&B6Q z*pFDOclcOz()i)C?9ghA?W;mf)X38a=;CrAFN>$^YTv@s3urFVsjfkM&L%^(wm3_5JUPdb1J{D_HX9a zH2cBpe6&o6%3Wp>13XG#QZSD?l7-R4FKyDv2+%5b>sN_~o7GxCUL|Cp(ds3FonVvd z2lSxU0Q`=JiR8kG)5G#A_zE5pEMm?FP!a;VU+>h1-H54MY_YZ(NDleGJ8h>5MF$R2 zWq}o~DI$g2uu3VvV2iKy(fxsNys}EH(#St_%V{T!XGri3=bn*ZVhk_hGlnAb%BnC; zVaV6(pMZ+|g@M0z<{TF!w~Tf4+V$HE$qU&*X^Y;=(?D8=EJ>gAA%)LDESr{czCxnDg6_xQp5TzXc;ZtfX;hoW z(V?~0Uhvq*m;aM+{1r7U24-=9&uBUNy#7s*`d5(sEm{3+b-U?Lu-jRXtdl;&UZmXlftss&4#_1nV&>`e7Xi>4? zBU}5%ExXF}nj!gB8NCaeaY`$KRX5VhM5fIn5gd)vlkWBTWMcE+qS};_3ObA^k@=lN zuM`xaa1ZUe@f6os0^;KY5ox`M-J41IJ6T{xHca7Bkf+41$p<1R(lfT^>nbzY*HvtJ^EW(qWBf50$&{qp zufU%2q7SV`mkfsut!A=s@3J<%lf_&Yyf?k zh)d!U@0HG{2VaY++89*l%5jmoi!Xge7GdW4YfubC4<=WJp(||Ykwf8!?uh~ce$lv+ z;}c&KjuwL6kKMq_hWw)n?Q0Nr^Jb;d`{{@ZBCk;Jc`D z+!ApjU9NlB4x+o~__NKJxv6~oLQ1jKNUOy%9uFAI5957Soq2JxKLAVwLWGHCOAbo{ zOBV^I8y>1l%QdI^yG5>Gtoq_OldQ7rU@GBLjxtjuH!R3Vt(`cnj|F)mT zsIv+ud`|x$2oR9Jtl0l;KmE_?|BrdE^2ssTTYUcNX!L0V`QJ9(zf^@kH%s()^HwvX zb&*m=UDdTMvUozPyEHSSRCXy1|Y*Wq< zu9oDr=Fur3j8HM+?zPjjGi~8zX%e+)FVU8+y##fg86^{OJbEVHURpKC+_#Bww~_o! znA%2Kh7!=^+8~*wf}`x6@80+=t?k}A%wzV&Q*|TV|eQ-sqCjKNir%#+s^@-+7Mk75R$c} ze{0d1b+%v{XmBC(qV=d+Voo zsko{QpR#VVl9Tdka^xjxiQ(OIB54YQStIx6-gAoMqwkRKcVWK9N|uh7AIItvHptzC zfYjmd@-IU;W0OSz4wq;}Iwx&e6-~M7dIr(O?VEP&k2QYz6(~)UUhE4RNAd=5PO8%_ z{~HaRNCXAvhA>{-JKnw~d@%h9=3lq9BT|GL$xq}g`#InL2Qc`zx&FDVyV-qu(0|%! zoBh{1|Bv-OC1G3!j2S&d;f1xJp;6n8_N4csUJYt7B``dYskx@;)fE?zkRisxdScT; z(|q;Cmx@_h7K1)eYi%!k?R6dP=KcBwatnSO6?TcmXjOb&JgA%dFtC_E@Fg!mfv6Nq z3B~)5suPNPTqt;mEVnthS`M6hCXf^W>56VubTIl|LbR-T_|Ta6*H!RVe;Uo5i1;AN zZD6=h8cS>`Hr`MOY+ZW9-3hlL5_MX>?A8FCw54Tfmo9RBn&&G3oF>nIC zU-z!rvu(2%a>Dv&e>7*y56KhRDFdh93pw3?5!z3kqUPW@N0}{?4@TRrv6A>Ad~5 z>S4dR+;O#uWdJ!9+cmlrxT-#t7(X4s3U_@kOm@OuY4r3Z{;{_k_Ljcv#4W2(FK8aky{|ypVOp@IvMQ0XU-qISJ z)PJ7I)D8V3b*J%Qs;+cbn*`WYamHH_V^c}JC{_P}^Lcnj3mJ`~;-bOEqDKD$ZD z=2FPs?12^KB8gB8IN#xXq&GbI6>8P22YPrCmBh#j3*b`8H`M7VlYa4 zpIahc7sw@$L8h3o0M_^Cn&Y)2#S=fIcDJ6&+w|U5{=^zT2O?07$#kaB*R2vt#~cG_ zYsv)#brDA8Q)*IEu!cX+bRzw#m+ia!`^o1)?e0exYOTdQ9xW%b_KWTjIK9${Crm{w zs*}B_X%&s);F+{^AhhwGM5j?b@caw;1jM2LBQYte8gu1 zOIJJ48MtQ#WO*40+HJRslF};Ipi;kvf^rxZou&I%_E>c?!~sHr0ES537`joX*e@~N zKU);tR~y}vU*U=Piwv>6(QSe55E>?7fxn*W0~uUtvHRnNc6T_;Sgals(g}kDWF6PC za$V*f=B@QARf-4b*OlZ))%4Ce^ycN*ldkFKhz?o&H}m?uqv?EbCu_VWX*>}p;m*!D z)coj<3CDkzqWvtOu(MeUKXtlSA5}MrDzQ&+l9Ozm4V5Lj5Ty`Hki5Nc%d97INv0HG`G3JRjS4r!yi#jEpiRI-O?`P^ZrJrK@Q*6@!=q#iXX%A(y# zEtG_tTF>ee8e;(FQoND{m$k0Kig&axszzqS5kXekRaM}l=99ryXK)v636Msu2kI%a zTaBnr1J0GM)@{s0TMuNhy@HTzsy+)+#KHS|2CIa2gEmM)wDQ-2^GGOj49}kjP=~pm z&JZ=pN%bGa#br~k1HEXi+&i(}t=`9O8G?Pt+EIg8juvxMCAeeIh|Npz}Uw2`$03zq>JX}1}5wZj8Gw1Ymc zsG*5M(MAmylsFghwzMhuEX~FmleZt=CpL7rk%Z|Q1Yx!6 z3T$EbrvcPb(+AYS1@n2-72)b=>H_D|?b!>m#M9x=Urn7r)pm$&(UEppuA!}g1(xV> zd2yCJN&`2wSg#;R#%;2E;q;96UmN-Ngl+wBw3>)=CReDu?*2@((GYe6w5a+LQu5Mj ztee@qA!oX^bXj6XG;n7%e{sj|5uxdBa0RiGW0MHmD403aCh&j#CW5Mvc&}ho=ZUMg zqjeW~*p63m+hE}^6~}1!-4>1OJ02)r*pN4Flaj1J!F)n0P(< zN}tO#uJ3_xVs4OSQa&f>28y}gu9C5-j<1pf^S5ceC}@kbu8ldu1he+Lm`w_s)9|Ig zVVa!{Nzd(T9{E(Z<}RvVz0+~LXmj2_+vem>v&SfScc+QQS=jqqQGljl#CF54qxoc- zJ93v-l5D{W*Da>}i5a(=%X&L9=uBU6Ir>_%N5?UlA3IYkFcUA4TvRlTZFOTrK}LnJ zV|V>n$!a;OR6|^l+mYiS;z~d%_(J*PMi;pXz$DZj$-curva(41;IM`1gow5ykB@c8 zOwF(r>Ckx! z=cj}-;Qitc^`@}O{KiA}cM|rm{CpSZUS#GIu&sXP=bZol3Ch2xCV%mGvx?~c7Yox$ zJlGB@R}f-j92+Ab!c-(&Ksp9P7SWwSmY-TP4Tb07f_+52SY6)}`mdG^Oy{sC?J~KS z3ZL>i4zq8w4%dA2R~)*!d?6IO8-vl!$?tA7kPgJgWRYvW8llLN5JqXH#_zq7Wru6- zU$LWVzn)|T#RFrytNGzX3$E#K$jnPa}%LUwJQe9;h%TUrIcAw1y|ZEd_lUE zaM4}QXdlUA30Dh{{Gq>JMGVb1ZzwK35Fqe=*eJ#~1lb9Zsnn6~h~T4p;;d|sRJ9NoCh zRdniy+gzwc`p70rg`|a5P)Skbx?|Z(W6vtdET(^~%BWO;->#-Z96#odc;>(~_+2Hf-DaiG-hfG9 zQ4~aq3HFI9kM;FYWA4nnD&`Qo|Q@ybGA-&hQ9w=t$_QDfD+5+}yhYdUVLANET z!{sw(znM5$)%Uj8Ebhss7hmcyA}A2~5kT~Nj!xTucZaQH(~y$;Mf?yEj176b4oo@Y z4V6j-0||A)^93yx%e$2%k)3Mg^NW1q4)!>MkC;4a{oc$v3(!WJNZ5P5SVq}KpOI$O zX50~b0}DE%{C$>2m$i2ZDSY`jYbb4<^(9(3heJuK2L zB`An9PVp2pai1B%Ep(8G1X9B%GwENDW;(nab{wY3NV6 zWP>XMT`7z>8Z7_sf?ETNy)k&4t&Q#c8L%iK|#2v{CO2 zBV(XbOxE^Ie$gRpYKD%x47oj)hMZ3Ij>O5mswhd3m^Usf%*un*8;0jGELTSDY1CUtqr4B$fGATyOge-FL6 zVM0&kEXZ)l$2w68OyTUX@pi_)c|RlePg)jzvLkAG_NLjDktRel8&$J!(9$yD#YmWl|cMH<0N)aLF` zU=}n3nI0!+dzj|YS3%}xzoyzrn!apvU_~0Sty{B({zUj9O38?MY45{eaHt;g@F!-V z;mdq2EwdO=FXD@4XgoSXo|_;`}cKsnZT6qZ-;5I+gd*Fb>>jN&7?a#TYQ3y=VE2Ge&LUFv6ACAsi?3nzwV z9$9@;>Fvb^9}<$@&gXXPd$uhzuDBkM47m8;jd4Snq+6G6hAohtLL;g@E_+2u-GaW3 zWj_^t5~8EtqtdZ2zndpG_hZ1=rOmB~TM{Wb-w+p&Xf7%AFITrFqN=H%NHH=%>EacB zJ&sD}NF@*iS>;xqhawVG8821C=t~hg#Fha2Wg_*;6QwqA86C`=Lm&0+rVl;B1k+mc z&17PSP0cHU57pS#+=;*9?cbv3Ep2SZ0b3^WjslAez4yX zQYM(o5}t!?@zE*$I>t2w@Eij@hIoO2wP;AnlJGd@$5}W!Ny`+@CU^%JL zDELdM`I8VO?%i2VRi(=)xo)=jz23DvX4^mQUK#{|U9oh+m@wLxHDgHN*}EGene#A3 zaTc*thPi?}7zqTfYR2~wV0e&v;$4y} zB>Bj5SCrJKF2SnuUg9>YDNeDsRBSG)h%Yj!u=WxtPcfV9(XG?-i1g&G%x}*Wm+G|4 zMW14;+aG~?Shgn7RzZ*c@=HDhWS5mFsW75r|L)k}%!=nF)lwSb3YC-)u1Cq9s2JiU zDHx5fztFs+fyPq@G)v{YDcUEwPSi#{*KadWb7?88xI33-63_vC%vz%58dZZ0x3-qKm^MkhAAeUm(sx zySNMe?!5zsfXbtMY2##TD$N-Ew4&sg-o~K>S!sw1B zLY|#(MD$SZX%G}7iilPipwdxdyrl+W{6XHsxWOMBPj*BWnPadmfv_&kSkhL@<~EK&J4Om9+zsJ{!0 z8Cdt$#XYmOO>omRXvWGK)1L2Q7y1QeZ%)U89NI(_E22(LaeSbkmqU~J52UJr(-N|` z#Ks4n4lYjTZ85vgLes7hWyrh*c5m_2a}?&h-7YGK*+@q23I}stkov>x9f>l!a0@Yr z?m34nfRpMQiv^;HhF|4G6|CVLj?i*R`yR}Nb$n0O5Ig4EALAJSI+-b>i_rDRY4 z%js1Qx~?tk?*^P9n83oHf$gy7;H(obnkvq*=6Cqpo-x0in7p>fv!7KU^9_DRjXtdes@WZ8? zdP3}WFCSreoVmp{YA^PA7&t1!bDpG(_Cu{7w;L1My*M&X`@p5LqTs{^rLqh2@ux0a zP4)OivUV5u>diNKZ>+agB$Bttello-WIbQj!VJwp`=2RI1xc(m{Te-nZmH#E=(H|T z&y2?V^6}ZG&+_T{?B`mX?|&;${wo)lT_l4q{v>b#|EY-mpU)-#FDzk-vff{cSpGV# zI(K>b`ky-<(bN*u_UHy=B$h(xfv^dDPaM*r=R@Y|=9J_C`GNq25P>JKmx4$SjxQ*1 zR_=rozuFG7NBKS8-~Rl8-$FLyjFm`%%k>>!&^9>GOBsZ%~{ zCwN6RZ@-CU0L|C-l`?ItE_VxUI){UewjYLvG}oPeL9er{O;xWoD2s5CWRnF_4UTJu z372>=q6%{+3X@(uwwx>r6ts@;Ch+w6R#43yNWhP`Ao3^U9BkZ`sy$N3c46F`h-(LR zDu!<7ulVk5dLcVuK++c!!JewnPK5R9Uhk=;jQL98DebF}MPJqQfrPG~n4b5wt_QPL zFsr_Y$;W743wZ#G>Sd`rck!2CT+)RXL_@YMU(}e;_4QiM`63w*p51WMut$<4ji}^F zTFAY78P3u|Oe{z=_*)@@O_|Lf0(zdMe*`TjoBDnHKtey10DpRdZm#E`D{Kx|pk^@Q z2Ih}r(Yct>`HLJy1DCsiQKY?6d@<^^si~F4ZwS^%BW6doMici5lyu1c6kPs(27pHkS>@J|Fa@LSxtg3B0jatC8lGQ3K!@V;jVRb~;Rx8|h zytsaq^kT&QjAX}Pv^*O49m=44+|PrL!RWqY^5lunSn8=&uuREz)g20k zkrT07XY40#*-k?zxEL|nhqB5D4P~Hut&Lx8gWa9Rb8Y4;e&nmhx1o3q2(na@v+wGQ1l5etudXvwSZ^#F! zQpewnmq!GxxYX)AXY{q0X@Jz_#@R_IaJzSF4JYYpbvxdY^9x&b0NIpR9R*NO8OZ~T zMP`aDWxJ4zBTJ8@dT6BN5&+}@2yuv%+x*hwHO(XgT5!+MU}HzrX$A!gQ5l{&)ab|~GZ%YjAS zBGS-in+6zTuUl*GA2u|DSnkGJ&E>!YPUHfO6CA6%4YVhe`gvn{UM8$2G3 zf7NafSM@H|6ZxRaY{y{;70$jlWN{VUPl1C!gn+v#LpLhD+I83IcDX_zic&fRM%RoJ z0v?Zl3>=St5Zt*~V{PHrER=nP`bmNb_0bRAT2k!`iCGJ}Y5$QgL&U72ghd`3TT_ik`PVo%J6&>8X`jzHF1baJMqqSCWfdA6Tws4+(k!y2)amaGvfIWy(>-n#Cl-W7R`k6QqflR(a)9``;#-m z82pYO**a2G*fD_oPJL}DWv59?x>p}DXg_JCX+RD&&=ST(^?4oMNPZxf(m%DM(F( z)%6!{^mi^lha8?V`eA&u*6nrgij7U5>|?c*B4T~}SmCj18}Zs?N+IcXc^ zAR-QNfS2b2szPPN3JzVsY+tMV{M~Bqe zVVRm3+I0x(IeGmsr*+<;l=(FL%cPu+j^7kz?v9Zq&3{SA)9{VB4wxBBPv$0wAw}ut z@l!y=5+(k&W{%T>vud39epi>m-vkZ@|W~;z+tU8||3mK>g?Q&^Py+z_vv!p82k&rv# z0fAEhJ^QG64Y#z}I~siymzBki6Ux<^;gANdx6?{?DBhucHx)k1Xc0m}&Wt58w?R*h z(wJs-4)kA>oTYD5lE6a*sTaAGLCd|6$hAM#ziK73tN45I(O*z2N|@c&_Y-QteL^js z|ICO#8?{@TnYey_{IhfW-!|TVQ&9d&lvU^zLJygQ02lKWRP4(?>juX~bK50Vil)sc z!+sRyO=Y$Vg9n58kkO!Ec>D5BwToWHyd<_ucX6D>y?N&jaJXcw26?E}5yHgtvOTCx zk)#eg$9IQbMni%1laSJ|@d%bvY0auxLnZDagw(6D*IMM9(3a&H>oSoMyImSP%Em^H z)mHXuEKWalS-lQfSHJneyCRiCOaGKh9rQiKzTQS9l+?u8O-}Rv$->fic2OiWIL5m2 zzFT7KLF;Ilpi=B8<7gu8hYC^*S~r7M~`}AfjZyL-2kfoQH}ejPJ)v zuyKIQe9Qw37C}|zQl#sR`KdmQ>|^sh0qkZ206|l2;|f>3gCM$K&5DVTIbg^Jp|>Xh zF~*TA=$8kScI_sYDwD;9ATEyLoe^LnGs7-9dg7cvD0@s47DA;C&4mCCfLZ*dAPUVF zW|UbsZu?IA#0iq#PjuGcNCxz0w)kkoku~Vg3~^eRl4lRf()+*Zng1G7x$Y;MtiHBUQQ|8*l#v+p z2JW)=K%sCMV-YfIk=e&DkXh!-cJ65dT{{6=z_g!FhQ1GyIG1#Ia&VAnqUk<|6D@}m z{2mX7)ef6q=C1i5z!a31rer~1y{U1iP91?lRX33Y8fv(BjrLQkgYJ0X|_^gjCV*Tw6`x^ z`|*t>p_d&ktR#~QlscnD#>^Ox7c!f<{cV%kz&MAqzoxE?G_>R1n%Pz|?qKOWnqV=h zRiN)85~>iYwMB>(ePKF@4ARd&S)9laU-wjuH_07S3s(R&rFzR?Xj^Lb=bSL2F6Cwx zSWO7s9V;-nGs9H2tNF_tWj7`V&i#bR1H#!9Mweolg= zKC(mMl`PC|zs+Hsp`m*FP4$-E_zr9)u85o zs9U3efQ)?#Q2*bQ+&?DkKPfqFA46TU6hRApkAs6odC^&SSUXW7wm9ioOx%^bj8xDN ziXupD5wAOn7U|+&W5F#+0AYO~Xk@!?(FzF?O37EM$zWt*B{6Yij1)Z$r)j+fJu?q+ zb<8REfWtP{B(Jr^9zo|WpRP;aLqGq`XMo@J(Cj4Yw6Q;lSjU~<%~KNJM(SV=yEmoS zhit&~u)^g@`m^A#m1F*xjYa9SYp`GN8E>?I?=qW#CTEP>Wnf>@DMJ9M1_|LOhE_^GOoAm<{rIjbTAj!fZm^l!RtabpB+i z+UM~CXOBIqk3419FPX))pYlu?h;q{&ly$W}ND4VZk4Zam}1;w~3NvRX>?AblQ&MtaYeJvJ{?^7W{ z0&uqQxafpS2jpOF5-7m;{{p&<721)nDw~hYc=D2E`$advWl*%q8T6|zqc+%uyQ^m= z@ms?*vUwC&6tddb_%hF;v%7e+SrxCm@aAe%<6MFUxv6`QSYeFW_)0H)83!|;8A)mb zi^$^q>|s>Zlukj8KYa>W$C~M$;WHNcuFAGBW&BWS2-_g;vtwQ+2;;}OS6$^QU}D~0 z++$Q@tU|IpJC(%NW~?r1LAMgW;HtuA&z-MP0XaErPM3;p8FA6jIy1l;u^Xpy>$Nc` zBc3*&R?j29uO;;(XbVNsoozZ7&`4g84tctJAZ<)Gzc8EMxQtS_)zv*>$@f!xe6O-< zd1Ox~=jit*2{^y9xoSi{i6Iicl6=HwqVvBx`wFNkx3y~l0V(P3?gkO1yQLdt)0=MT zmhSG7?(XhT8j&tZrMu+ce#djwt@qqB{+F@GhA~)ku6S2H>sj-8Z=l>Z8Phg3LNk?k zLR!b|fps*k(K4U&o0!v(4G&A4u#bsXmjb7x45}1(4zl^glQ;rQ zSkI{@s#^1`4@I`JUfQxL&idlLj7l5fLU*1~Gf9+IUksg@?z5j}B3M3kdz-&$JgxhR zs(K-NRZ&@yEk!Dikv6%ypAN+-dW52xn@=_3q$mWZk+P)>$3o2cbwctxOLI3Pwjk?k zJynA4Pa{GfFAtBUg{7ZpJmd&g|9G|i!6>(4_0w%qT<&VZ5_O_oy2Uw3;OfEv$Hf_G zcUqCqDt-`8OIoyqqsE{NDtC1@)=H_?8!~pK^tT`K3K)}JUTgV!h4C7d5DVR@^2Eg+ zAdRReMZ7zis`(;ynoj|t!zlv2ro6+c)EHQ#o|>Kn^S*~CH!GDN#!C0}JlQpA6U$|c z(|rpQ#~!f?)6%GckiD!qA>5OvasOmbN+b$EUu<_?{-Q@uH9xpPORCu`j=10NAvgBm zlh!ifCMbK9R>St`7M}?vcSnyE3mRVXzO-Yt)+cBrKzLq&DiADxaR{Jl` z&hl53hQBz7m@ELth8GOS_$%JP62|r$Lj>x>qyy)k11RL&un9T$pELx##y-jZvUmN++zJ7GNwmcz9*>1e@(>G{8(U z;ouYW*+PyXX@N|L^p}~weW5i4NdZ2C!@b+y&@>=o#6ewCRil$>&^rVxU6|$0*PBTb zsWQpFwn8Ru*wLhlph}zI$91cJdMND{(fMlgIcM8UrrH&s?*a42bY2cbJ_e1=6sysQ zEy@(AK^V_B7dW7O`6JR3mDsl6$axi&s?L>woZY-8-|{|Wgu9usm`^nZ4`zti{g>+6 zv5oEO4#bK#5?|KpwzX!`nW`nRVz|xds$h@YHcZ#b*IYI=T%r0B$HALuTJ^05DaXxD ztHce=n(0~buutxceWYbiD#8oQb5vz4cvW#IT-_h!*B60%`;?q~GZdeLW6`Xi67M3q z)lD0#zsV{gT7AFXCXbT%&O;G?gm9gzy@sQNuIXcf=F>Mbu6YCEjefC^c~|^MQ-mo? zAge&9+nAh2t0=bpR-zW`2PSL+uMytH2e4zz&@x(M0-Aw)yqJP7uC*!`jBd8bOp-N)Z>#F!%CAka2Fv!V_EFDg_G5cL& zrQqqwxkR~LwAOwjrQ>7u0;<6fcI?5a7@5-xi;&=jU~QAgWkiYttk73iJBW+|@$a$< zK0u;;AP8}PbepMdj}zPK{9>foW(zws=<3n-(^HP&eHk%!{)DqZs|Ul{Zi?9nkjnf8~ZcTQr;<&zX*EHI(2y zpSLGFQ+$qkHAs#vsn-PYis+i-t98Ee0atOQP+6+T#^lCh-vi0aUQDRb(N#0dt3&_U zIfdhTelc&rgg@*{o$aiS>2uMt2HfEIm;Q57xQpOAD7g|-dm2w z)^oVyaCzuS7D6r=B~7uys@5l6-5j;GmVS9z^cQd3$vM(?NZKi^0C`s9p;VskANfW4 zi9ZE&e+@?WH`x@VBhJ;>t8#Gs3}}OzR1vmc6HJB}svz#M^Ea_nA|b%Zb|z^cczA-@ z*;Uc*HjR=tg=0-aFIXvHQd@!5mtYkzrxhk^tg93@XP=#Yb~Tx!i+>JVWnWGFc1~Cs zZuglyadwqLFp2!xat{^?Cv?vjYh6Dq7nIq;F8av$f||D(xz1d`U`1)A{bJ%=7#29xOiIVGUk! z=93k#eV>aEnKQq`kaOK=kD6r9x|b(y66rXma@iF1tRg>V|1Fb?4}(j1(@y`CaC>&z zDSq%ob4^J2gk`z_Yr0q~Pt2OOC|p^V^p&!dE&gmvnqo`HxivA;A!bd2RiGk90 zP1r8bhg_2Hfn)EiRkK2b^9AP!nle_9>lBh-K{!0pbSRi6`Q$%g#d+%P^1vR?-ufH{ zFgt%rvI#l$?!~0q(PsWLk2s?2fZQqGHW|XTy~o#hrdH4HquS&mGNrbT@lR>o_Hz5# zQQj7$4-~7yu6mJGSUyF1Ce2EYSw4N8PVs6F2jyvl1Agq&NM9{Yta?jF<5gNcn@0?m zuK|@2>Dj0O&^MWlR46nJtTMw|yPBUfEKZ&A@8Z5nE%VY0O5I222~a3$$r73CtY%r< z+zl+xkdxO$7uGI8peL(l^hK-qutbq+x?gUm)ar9{!!A*6oVWt9^lBdIli#*Nqt5#` zXnQ>+koO|!auIz-ciaw_4)fI+Vq=;k*qtv~<^(n4Mt2oU-px0?bAc|oP;XO(fbF9* zDQ|HFd*Hi!D&-Rc@{M;q`Kgx{*Wv4^2S$fb$;ZQQYs5M{8CR-tE1Jp(X&O8d<;+S) z*FHb8@S+#nv2WN9rFzwREQZd)uonReD6kjl)x9YLs75u%K+9em9b)0emwA#^#Tg(? zLm*{0OJ@ZP`~WS2=l*&!)p`s`U#tN7-Q&qGl^f{62@y-gk5y~I(OyE{~#uPuxf4U7I0IIKnK1YY1T&BMiPYqU0$kH;F)N6>(ph)aT0oroRN3^GG<+;R1E-r6exBGbn_*b>IRlYLa zrMAClUrE@mWoRMHoa}(p6;*=@r8E?dynFD}6QTF17uFW^HPOV0Y%*-av(V}K$T@!b z=Of-8$U@~0IHRBxJO-X%TmpHd<9fTj`iKN>Lr&2)>%873$K;H}LNC3{BPQJtzU66! zlsF?Hc`^1P(>o#laPL&9#)wb-95F{CNpd{ZXMFs`ScBK|vAl!99i-jkh^;D~m% zLW{FELpf>H2b>0m*ecNypVQIED>JX&&t5@X4~W{K$8H}BoLFstSjurYJ*e^aD9^6M zn-dwcyhC%n9SD$sIki##3eO|a+WL4IUc00lK!dftass0{K`^Fv+TOb@aCh*a3VEVE zPtcK)hg_Ao$SjDbd2W8Y`1E~Cz#Lgz8>Otro06~g%xFZp`{%*w_7Ioz>Dg)B7@`5> zqHXlmZOzv1?Z~>fhcu<833axKdW@*h42>Uoiutti_$Vi_2bC|Z$n?bn)_d!L@OQY@ zcaIt0ws-8m9+zkdqiK&2TY;+C^Mu}8j+7LyvgU>6zRP^}jQ0|&;e4f4r?VEjZN6w_ zE}#`%x$K(e&6kmmvn&Q}VyW&krXHE&1tlVpg(aB`CnTKS`8CdEVd&PAiPY+m2ohh? zC->=JyA7-BD~=qOZ!^lGd2=PdLfwrUvL}$>es!UD9WPX&Z+J~0-YSd%%XhQFcd)K} zQ?Ltb%k8|~j&X6HCyn_*Hv3_jR`$CjoEQ#Y^HAE*&n)Nq3%)iFa9gq0NgQALAFcDH zG4(q^ZyEzy(AHIO%KKa>``mHLJ1^lf0?zeYuuf+HEkyQONjm}FWA{+MT5Htgf#EqI z(;_YCfR_E=m=*<%Kv(SlI-a-t%XCv3=lNn%0H?owCd|R!7YUq(H9!af)O>PrsNO$H)=yID ze?n|i4xCm!caO(WtTzYT)Z_M1uP^2gAr4~JiyfwNlvr`m#a|?<5mX_@FVMXnTByz? z!i)JT-8>lCdeT+j5@6*vkEy7G-gT@>uw<^8lMG8Pt_LIOq(6QZ>(JJ@tX6`Q;p#Cw zz`~*7(z|RsxteWhd6~|*E3Kr32)93NXiFG_=w22`qO1+TF&Qi^;Mh?@($X2w(d)$? z?~K1W@V_$FuG|mipEme9q}!-vadea&rL1lEpnDEAoI70`QB!a>DW;sP`=dfUiwXXI zom%bwY!#>fb2lTyC=G+ixNZQz!iV9e?Fo*DF-v@jF3QYUx|0|i%HIZz zW>#(uL|HU!g!9Nf@TRB?O^?BW&qCmkVx~N*d@m*VvP;S@s|FWdLk>C=H5CaL*#uft zeE)fLivL$!xFo=6K2(Rx1BM#y`3~(zu@l_U7}2BadVwz=n|+{|z6_3Sdole9(Js;` zOrl6LrKEPiS>w`VK#P(Xmp>QZRks5XgB4(2tOb$d(`4SMNQLH6{2_0s?KzW-%L|L&fk zv?uq?&vvq0C%(31LmET2lWs4*3gZY}L@z8T$_oz0_uk);QM#`A{l4C*f*a($6j`Ln z8WbqR-1AAyEDOk6kS13e_eHv$@#aMaar*=1%4c5mG(ZCxB#l_nr^VUXfXDGZ&Peb> zUCM7XL?!ybPD@ZASWX>*7AOh(qg(u{$Pah^rc-8>3ThR|HXiYBM-GEAd&Vw z{qy_SIvhpLb^tqKDR+8n+wxqcZ@pW8ttfT-$RZ=rQ?l@wLX#Od+*7343MKz8wRB@x z&V+z0+2#+)#2lqY9r$Gy(>nb{SEX1Nc-g)9M1GF)Ps6AoX7dPJt-I=m`O8nR&Twht zui;e4+t=xxdLH=CU{5&nWfY}~u1&VEr~t5V;ITVd5szIKA9o8m*rc!2u2D{d0;5`7 z-v};x>;z^-oGB-wqY$bAwg&*}iT%&~bx}^FKzaj&(&|Py2TXTv%QpCqnd`Kw_6t1} zP{rE~-jdLxICKfwBf7Wc?UmKWGvxj|C&pq{jWm50_SNKzfF55Ow=I!o#JBED^{44C zxvlCg$_4Fj2)8ABlYvE7Ck>=8_?e{JIR(*kZK4y(7J$@rY-phug3tuJEi?eY;h|_077@2O;okNXBIgmdeIPVt8T4C-X zPM5$Zw246FDKyLHPuB%8#I6~h>E7GZ9@fc@zbyCEP=xUbjq`R|6Du-Ry3oR8w#t{> z_vG7)y6YHE7a{P4%=uufB6-jr_cDwUk=u+x8>3k|hNr$0=v3x`f}XU6>1qyxjP?(H z-Z0-C+T*~kZ=5JQI05%gLaWEGCHmpwzPq-szgA6`Joqu-U85*@B`8!QDabMQ`S0WU z-})*4<{Yq8bx{pp6ysjD3ea7(LH>kB&F2*g8fuVj#gb;F4_WP{ZuI^7CK?kK2(nTBUjG)H#hXB+z7f+ zbOw}?@L38Y6CHYYrC97!Fp_oW(&>qd#Ag|*PI9`2cM{|37^7^4g$|8HP1!r-Re-8nv=~Te>P*J~FK(VtHyS@Kp)cB`#+sq!@;PkLubEU~@gSpSFI`S5x z!-cs1Z7_DKb5q(8r9k23@ha#T5@hk+PE|oIC7BRw8#2vfxeUNz@410RgBI^-Q)p<( zy#1MiP`$b63-s)=bti ztdv5iRp^aT{8;n&%>*@i6D2Su z&f}~SS3|%x*cu|8*Lx7W?}&*f2GOgi8L=i!akBz-{109xcT?3r1G<1t&P$ z1-(8Bwjttb_9NLooO2PL*r@KdPypZC?o8J!#Di$PJv1X!XUn^wM@s(CS|Wmd5JW*V zLr;71+4zK0EeDWrGu9Dc1}@Pe4Bg(8JD-Gw(lD{67Lf||8KQK?P}61g^h@V-nCTc| za#g=^SE;AZPY0}s#zkP~yDrs)JyCj?v3`3=8TlIXGY;0`RhEQO_&iWW_9`Rz_5}*> zMIfLKcRAf5j!-PQItSMK<-AaCRiUZ#apPHT z)0@E)XV^}GSuI@e$q?Px^IbvM=@c7H#={B0=mU>93UPv4q|%fZBzMZ#)4D3kf-_rw z`rU(>rozoO{GJLJj1={K++We=q#`4%g8>^8sB^e&{bUZ$aMHV8>uh5RrBT|;LU(x+ zk74ElwjY&WRvwX$Obie|jGx4!k13nRmw;J<|&OYd}kO9oC0*kvQvC39usYe*K`w>N-Y6Yd5SwAJ5;WU7hYD8rq4YtDt<> zTtUg8TM3gh`osZBAEu=Bf4UfT z^^ALDx!M?lG}u{;L&4ZB^2HBXNr62%Fuqp8&o%tbU#BcGqI$xQQng)X21!MVxPy+# zN53%TVo16rrE%Y+9k?xXv$x;7-9zZ2($gBq%PWBVf`pK-Su(OW{DV^@8FC`M()$=0 zsBE-6K(_+u+b=#<<*c;@!@{GvzB9K`6U?g`K2Kaa_A6BL`^-qcT?pT;_i}g@-l)kV z!KZqVLAcx{ydrdiEtf*73+<(bAjhkZ$|zd3pJNx)P_aD6P0j7LFz27pMwfo%G_qt9 zAF#s-b$;#>`-#3zf7`!%muki=Z|oIY|Hhe0^SG|6j-mwzFF;F~321GlgeT9E$efxW zLL`SGlFI9CpPb5z-O{0%JpGwIeB9J}ScxT;KO#CjrUYs5tMm)ofW|C6({X(0!lFf6 z)7!>KLY(G~T_1x97C!(qRKBSiLBO8$Al`M`BuZ6sGK2co+62)UZwZZmatWML7s<+}%M`CJI#7C^4NaheQFS<>+jnALTva4Q=^nYG88GFOCgoGVQxO+QQ)jf$#L+ER@} zP`dVDA)7ap;CIbkrT%TtSe0DXzn zAHblsv|jGix#n0cf8+<`QnP!3+ojE6*zGQf7o>mi^c>`)p|%s2hT9C12ep(7R4l&+aQd=bbTN zVPX@sk_cN$BMlwGgjJ+%JjH+`7joqgis2Q1nS=tUqIGv9mN9;XI&pII$n)4tur}6s zQhpXOnjwTWIG0wO(|{Q=jk*w(Y(yI8B1vr^p`d{82098^r;X;5=7y_NwoWnYH zZkb*eDEhQKtjYvGxs0-~!7P`^GO7CmLp2vR;k5oGa%Zp0vV$Vx=Hwy+UC|!(Lh<^k zX~wH2Qtg8&nKej_v{>|0cWz?1ag9xDMzVG`?oV*2)LJA%(M zI1P|19PRHT|4(jHV4iPb(K^!IEExVTjOv@NINOgjdsN4F!>~W&49H`^!!s@!TOi_E z&}lrowRm|6b*rEkFGS1ad!9GweA4#fF*SettK|pQ2>nk8K3WHMgxm2^3z1o;>IQFp zlxEFes-}Q^p}5vuyEbefrME-A&Fj|pNw_L?)cmQ?7!vM=I+hPf16wbmS*<*LUm^eT zB8{R36uD!PY0H4DexhDn%X8`h=(B_GaQBX0{;T(P~c7`(&AIcdrg3@-Am&X?hGrSUIvkQ0`n8;J5ypb`r*0+I9w&t=b zWZjgkO(;5cA0c4fIOoJ{5{1fCoG>Hkl?feEZb7OJCA~LiYFy|7YhG*G*`(S8lbauh z^{RQ+xU|5Bt)$k52j)=&&+YiFsU;pHNoTU3|qm{xr@e=^-Z zmNDiDFrE_}uDLE{zni!pCtf{WSj6#xGq+CNNw~4yw;Ofduii>;^=$uo_u>JNC(;@% zNq@?K(k}`%Du!gm$B$AQQ5QEsM0+y^6SbJYQPjt;nCyeUwQP?A9M|C+KR`(cjl?5> zu!uqrqrcz{Y%6M-ej-hxDyK?q>|S!bqL~Yw)rZf)l{#Zcd+~alpjg4%2u)e@!-z9^ zt*ch#1SgKLOkCB2B%j_}gsnd0GUxb=`M#-G+0+0IQ%0rGf-Zh!i}7v84x67^Eo@$H z>5ghQ6DK`m2I4VN_gIOWERci4$B;)-%=KAz49pa-39?PoXcvn)9;H_0mop@y-#uWH{rj*$%&q= zQIZ}<$Nl&AM*JpZE=CQqE%uIfhl%Tg@b)l z48qpT{2_4x$)+KfFa3SsBMR6UT!?^oUQnP&k}DpCd<-pGyxReh__iBCdcYev!WtIO zQv|t-q31ftAUTDeiX}DF-3vv@;3Cs7F%EX|gwNW<7tVcQ(=}(ByLrcn*rV<+bfBPI zMo;G@C*Q|%xjvV5MXXBgG~h?96NyascHjLvB^`Gm@AAydzC9Uc*+>X8Rk6A(l3|vJ z=YY6Oxmh#7^~=W5SN8z6FGpsefbX}j)~LeQFi~CP-|P_f`3SyT0)7gJP;IVkRXSVnPX&W_`QcT$IKKZ@f_lz8ig~MyN(p7 z8}66LoHHg`l37Fzc70|Wt9W1+@=TacokOmtB(=h;Lm>lUz6P4`xryduc31$(cq{sX zI4LfS&VJJrzIcdZBbO3cFgheBzM&qxmHS|Wc;@(rn+SU`*#MV1?noc!x~e)4bypf% zJ8KzTE<>h@htjGHNSDg$PJ`LOXYH{@BGAg24@4nz#4`zc3h720X zUaP`OqC=0fyI~ecS22c@qTAH3d~AqGZ|6Hi&)Nn*{cxYcIrZX06_fpHVtq(zyeVYyl`Lrjp-?3x6hbhjgst%VZFRWKYHUz%(Xp9GY*wHyX?jZ1 z;%kC1^aj(D7L&LR_DVeOudWa}ND1&YzRV2(xFVXusGUr+fLWpgt%wFF?PLbYrRYAh zA!0;;R$_^RZ9SgTDOgrS=iG@1ZPfHfnA=WGCVj@8e)3MtQ$0$)>OC#$Zq&K?E?J2( zJWF3r$v2+2p}ifmTVSzv8Fym%B=K6}^Dg^_ju4Qc4Usoo+3l9~F`48?lk?GD>Qz6X z>k$%F@6+Z|B_X~O>UIsXmw zM?57ByWVMBzFB%c4IUvzTG!N12P;qJEexFUy*Vd0gJJfo+&i#xZ^5?tupZCqpMzE! zLvVjIc>exM{og^>e_3dJmP1!S`6{QS{*g%@1?3bQKjsS4<_1eeQYgL ztWK3qj~YlT5Lt$!fTGWniZ2)$kXo&ksqW$(dAap2HHmvUDJd<9xBaWz&0~^aL)7$0sVICXRs-?f)7n#!B5+Og`K-VQK*XdhaU#KET% zM!;s+w=6H-ls4oQkFLv!Qm`!!E=VN|+e5Vl^=$azibaC;cHj+YyxHc~`Ve7Z-NlIUfOsQa-g7Wox# zOMwnS*=y7`kt?==mGTV&-^3@5??a#E9tH0(RN}7eM2-2=qq&)29%^@C1?Q_og#psTqs4oi?W>0jekGCLWW;n+15 zy>a*MRBG&^Pr}Yyx|h<~<|)|DYj;Cvg-smohsCq8Y`AoL>%1t}j62sHB;~zg+yL1* z2C+a4JP?8{eXrfWsn8#NSOsk#T@qt&5K-Ll_#=TVRW$2D_B_E9vWZuK3C|&18S|lE zTlUBs;(}L*_agJ8ezhb(JjgE(!fpakW*QbrTg*C9f^rU{s(|+&hXTE8qX$8vJ!^b$`;}-}ps&9|95s z3KS0e(W3`apxZMb;{Pbmg9eB156Xi*!Ee9HiYf~-O3H~b%S->7Y=2<{^P8na8T7&U z_MhLM9Pe*?$^Rsi6_k?{6ID`Xk`)6-_?7@P$^G90n&`ei--r`Izkd_#{ihV59n()K zTE3_FE}8#N2|;q4KPBAyHR1Od2){9#_!tY_>nCyHzXARZ zT=chuICzdCv`)jZK&7_^m0aW(z_0%U5PU%gTG}}|3p&`FfOK7f`aeXA!5O!{sM{5R znC3wrvR@b-L3#K?5hVXE!(aPLaJ+d5Q95XlxlA6^65mdV|9*13bwQ@&Kj48xXU!e# zK=-Z0faZpR`uc`;cCr9VfbriU3BU>T%e|X)K~;nTB4PX+9rT^!T?eB41A&??z#4RI z4`i({0vbDj^qWCK=6}w+f;%B_15|2UP&Z)t1sd@9kI>+iE&+n8$d3#01@Mvj>=){~2wuLnf#P zRQ@2G=6EwR z{}K9otBE=p>O1^LaT^>JMf%m3JrF8AC^`rzhyQtUycwI0)u0Miy8gE)NuSK% zm&FgF>CE4VetTX2sk?!nT>n6x2W?pXWgY$b92>k4;0K03s7CYtiRypMrQnBPKVTIL z{t5Q`fbkDUV&DY;H+2uJK5$#! z5B!#je}VtsEqmbg1#Y1DK_p-EpM~LnGgrt0pHG0TWu%8ZUkOEED|p-3^&kB?5&D6r0QZ0`P) z86BN*8V4{k*DDONNG?dRNJrHFTJDnEzwZmT#CJU)TBf z)j_|`ZR}0{c45EUApOh6#9rUf(&%rdzuzq8-%VZY^=)m9?EgO(2|fOuuGgg>ULOwq zKf8$kzr|Gl1d!1;vt|Zb>N_|@D6gojh+(ZE_Ogdc_yOR3(IiNFCt-1?^Km5<{E5He z*|H@OEH`(nL|~}f8-4hEwt#w&bybbyI%jcRh5D7%#zb9`M(=E?C*>|LC?P9x@`H&cm1@nZ%oyVl zM)Of<)m&LZulf7EqMQEh2{2*E_2`qv`@~=qE`^J_(e5AiTHT)+7~-@vW%?K9XHxQ9 zQ;YY%*B*pGa)68)zfjf&4!}Hsm*2#dPc1NEHoOc#548qZ3)OcAHRP;JIP7&#bZst03nIf zL6?uQ@7Qakwk{poOw;cN8+R!<(Thwlgv9U~Y{8nvo;eenIFk2Ps$55cm+O};O2!R~ zN4a&pqe&MtYh=k58|qXg#RReTR+xp5X>syrkv>fRSlgD& zld?L~Skb{+CB=RuY-&VyMr^K74C{LaS1*d}37Qrs&#znH1L~Rh$ukPe?>2+tsk5tX zrbW59YP#Zmimfc)8d-M%+(jXaCC89c{A zIcZXbw^Pz+Gv~$iyeQ(^u?x=BG9D7xk2tFa{EF`0!Ti*0(de^)muj3^=C3j884WRX zdY^Ll=2P`>48lZXXx4d6K#Z!HAvrgiic8j!dQ!%`UdGL4N|+9z{pQc+5>1v5ocdX0 z=N3=puu(%?P7$Cv@Lv3t;?L$RrbuzsJ4@X#vaq0rhF`GG7r7kyzj93oa*W02QLikQ zj8I&j_LgwFEu?i*bV=rHc~dI)4o^Pf&sSR{$AAJ-2yUxZc%P9{McLA_)0`(dP$=4M z6frleRVb%9KcT9v8Z1SG4j~0KH?_h4;|n}H~@Upg)9L!5HJ8-vi2AKIP5twU{4He2X62)nxX4K_Oh+&W!> za+)wF*jnibFs(g1^xv=8{C1Qbb02M#v!k1p0#nPsUE(E0+2w_ne0L%yoAo&*!(t6^ zUKOPQ0XBLV+p>!7ENoo~&uq_fDbBV(HZSzx6}UC~;Qw41a+6-T3n~ulv#X$ULIggl+)mshLXQ|<(3Z8C0mAZC_%G`#!ojqB{)nee#{MaX^k|W(IiVl zzE-uhFnb~??B?ZIyVW%H0Z6iN*7RG^Sk~N7U{3&FGoU5p4^_P~3#iYXv)ZgR3_z%zV zc^C)?bYut!)_)F!if#^$Mpkn6Hm`xy(agv}Lf`r|3fuoH9ID)_Vya?2gBUTpgG;v? z!C+8jvnGy}d?{^MXdoC&+#MYb0;Eero8M}*tgNZ5?4bS%%;Fz-_a!G$@mJedrITCg zH`QiaMC%?+x9yMZk6veM-?P5HxFhP}dS3$xL5Ar+bD)I<(rHppx-h_Vqff&ybz+#s$wVD1;F2$i~k#__0>3q3Ed z_!G`Fm?G6Ecmh9XB@zz-VeA(h!zxaF?NH%57trjY(Yg+0g38kCAs%}NZeLl_g8*{>k;P)6w!Y99v;wjkVeQF?FjJi70$V|8q^D`CUVZS*Csp#>PsNeJ zNZ>D9$_};$$ko(qx~pXwVGQ({W*G;@%`^kvuBIAsqN$=oIEp#N$rgPP3h5F(+!iok z4l6)Prr;9P5K#M2zEp3W(ifdB*@9O`owVF^N8a{mkLirv%}`5Z&^@hBVQKC>Z4imc z@Xe_&gd1+!nPT2~H28<;_X~XL9VaXIqVLj{S@>U;&2W1t$xF0<-lANOgRUB_dZCGz zmfy-~%?ooyaH`W>$8e8DBA}1#NO4OL2?;ZQMtF9eC)SKhFuFfwE56+gEK4SRv1K$1 zyn3IA!r}^9W>De>Ynde1|25-swrsc2KtGk?>;x1>3k3uB%M z*NfV0xxY4Zw{*lLm&QzlrjKKF-a?(N#G4wNc0HBM1qP@e}7`oHxLcNpk|AJ_Z#O&SAf_S=F9-Pr4)T%?IbUN^Gg0 z^RuuI1Yy?|p`L^u0-73&kv#Z|^D4WmP8x1Zltjo_?L9(Lz^Z{_!wvR#CWh}!jGh@V zb$PahB-C1thflG{yD>xiF~}p(6lZ^7JRsTVn&^0@YN40$$XH};Ddh{#_{(9r|>ki&B9!$$zalb zh42HCquzvnbUv68pA3xS*YTTY3m=#?gpPqA-tYftj zSJM}eZgjm>b}raFIxnggAI&Rf37qzzwNdagKg7J##%tS(*~@xayXq8V(yIf913!9} z7NlcyR^}T=dZ>TFB_lRc`Xm@N%`F?{^GP&VTP+Ib^o9+b%GppIZj3WMzTwDzd)8&W z+*;TPvEbpRf$~s^`nV-V9JvLd`c9tq?KILJejmdDDcdejgzO%RpbMzD_6$umh?rN` ziPnQjcuCm!YU+8P+^7p{__TZGO79IKN(n5EoPZdc3MyAau3Xp4up2G0b(P%O#Gd@8 zMxP&5Fte=9_2x2&PSRCeFm=1=^B+qzzQDkyDK4Hv6H+-gD&JyS#x5#Eh0YnL@-xxn zSKu1B22x`ITYfn8+V*C{*U1#GGJ@+_SMGahH>B&S}I7%oBpp@}_#pFh+ zGN?|w&0{qH%}TKi3B4zVT9`xTyPiJKPSN$U(_E6F{eVfQt4-?2O&rnY2%S}m3sl-3 z;dC_&dxpzf*8aW>LcE2MIjd5K-h?K;1Bo9-1@I=ElDZhAR)W$gynFx?={0jG^ z_Xgg?VVR_NEC)uHGm@R{!!J$D`P2|Rq5eHb#LT{1Vt&mLaj*3S^*`qbIekY{K?esT zD}#S$h6H6ZRZJ5sZ&*moess1_q&co_oNAThe0e%bOD;wkADp~xN;ia@A?frKTJyQn zx?gZ7hf&}5YeNb$=g)r0e{4G&H6#mQCfU-CGQdcnRN@YvBuwpk8x)*|F@GKs;NRFc zu|Ty7>Yk|f9CVA>=eRWJ3G)k(DO~-*#B%Ctrz#@fIdypD%Ffx;o}MCIF~K-0Q*M$t zU2{1D=~=`#>_w%bR4c>?#4lC}Mq138Zy`#jlI-)`ch!A8)TA^qwOUsT!a#)OG-i4R4N^_n=zz{eGh-2r$_T%JdTJsXjw$BA1XAS^>=*0Ip%N*3H)GV>8f`$a z7-kE$WzubC>6q^D0XD_J9T}CiI5}8LxF6n+eVl^yv-NA{^`%tS=bIK0W!g(2%Ylw) z>@(C7(*i}Zb31+M$AkZfrN;2-9ZMp20!{XyhCnS&9vJ}GJ%+u#dm&!8VXknTepY*`)jar4tiQokR;F*pdFjjjbxD2)cx~> z`=Uf#v?acc7R(-`jp+=EH$hOuNSBV9P|lSd3KL#ZRTzSZ+*P;^?nRbKv!85N$|MGH zHFq)7LSyuA>7_@i-fE1kFZLOhughE8q}=2<0maRa*bdevQDQM{i=Y^3OBPjWn`+Vnt4dtUg>{<9)kpIzv)RnS4lV#E$l1P7XJqO&$0_*YZnFNBAK-EVag zCRfpuc;GeBRG3r`KTh~hD`0&Bs?;~1_@U9V6OQ4@Lh;5{JJZU2>0-ZEV{oG({|YV7 zPw)oAfOpBry+i^udAB8667NE1wketQX6w|&SPmh4lMZxHK<4MIA`|8)ZCmsrSxF$h zT#!I&NwoQ5!`kQLIyYF$+;6}fUo29SiN;%-sp1ixwg{KtJRg@An&ws-cURP_TY`h6 z<;j-2o@4OWF9_SIIYjE2mnUC+y&(lyNs0_M#fdyZ{7VF~_FafHPTm^nY}%suSCD7Y zN4|F>%9i$JpOs=GChdrf-Pac~|4CqVPEhwjZYZ`FJ8c0XVOCkI#w~)=6~A^rRXCeI zay-zDC{mm69@D*hWh*XoMVZKEphFs%PQQ<+-ik=FWWJ5cc^;(o^bUF3i%>Ve8Gj%k z;>#y4+?NlB7s*t@?b-A?k8jpDSq_%p-pekwyvbzT7{YaJ198{8MX%=GKgAcKO{^BV z_rvPevB}6eQ6o6Tl5>g@8EepUF6pJ_K5{tc$u2$2eEn@#9uSdNlln?eys|kEWd9s- zMQmKGEp7A-|J;UqDQi1mD&u*}rjAjstf*WOI zdxWY9xd}C%nr+2wi24alh)jrxnTgWnnSY2Tql=$4o{JYvEO}e80gdf%(rQ?*Uwo|XMq@o32iWqR44%EYEl{!rPM=ZKE~VGnfgldfG## z%u6e#GdH4j4})X^W=o@d-_G!2ui({@>qbDJD5hwy1|^l0 zzV~#WdIWk z0%#pq=H7Y$pne_=)D*ZU_KiD!^~U#yHQ8Rgdsl$PVPK53x28Da?NNIv2+nc2CIiQn zjLp~lhe*Y>LaE?AR-!-qv9&U3Gm}UC#QMSamJU-U_)%vA8D!7Prq0~aho*B)iZJ4OAbLI1ZC{3Gx`D%?q6&td4P)ObW{BErS?4YWO z*#a3uB#E4VRiEjKxfb>8mhae-b^tJ&K>K1QLkX8f#<3`JMsc;jtXb@oCtLT@B>9uT z-1YM|>bdf{7Q++Az@w@=HYJ;AtZqr-Ji!p z2^9{K=1nPF>^psIU-`5doW z8!u1KG(KK;OHpBOv|=w1sSPC>kAvuQVB*-pgK%eEsdi9__x~f6-5_d zjnqgJCPfw*lElir0Qq7y^C8{>oRZXl$he_nQ|b?_T&Y9=nQ$YJ7A$Yl5G=-$V3O_S zy`eifA8#zaWg=roqHK8PP5V4$%t*fcytLE;J;pNev9c6P|4f9#wko1~V3o9jK|E!t z)0Jc@HpvJjoo&-S@XR@ zUOHyjpzu}={({uz#RXKa`EXg+6%eumuYgr?AQ-2^y4a{WJc^G)+Y+9|h5jk{yxi37 zDA!u@z)ayhQbjB7pmr=_u#3>GjL`tM3J0Yw+PMm6QcAiuf1K-dQm|U7Tw|Q=Y!C&i zv>caYgyF#>rSrgLpTFZKonk` zDgwfiK3jS;nl<9u(#WCozgAtUTs0^ zsNG;Jq+0g@PB5=@_nJb;O#wJW{NOON@W!_*}WB|`D@C?k$r&{%XO0zW+BI}HK zqI|w|&YVNJ>hbJ;_r{9KTpE9`)EvNbur;_wn7-=qsUvtmdtvAx+)NAi6vEm#cq1#iDTh1U@cNmsaLYw zdSZS3N*F}^^m%ENC13gAGs(mK8>}5`m=|6&my-pDmw1bgxJR$@U)HBt&L=K*9UFBU z{@+Xmwctcmt4y3J#=U=3mf7)luhHE#Le`7mknZ|1oC1wd+F@$Ho12z(eO;(`j?Wpz zUzED~$kU&&z1m~f+Nr)MJ!_SJmq+EeVwE1w^tcY1s@rP4=CrWozNym2<*1)f|X9DxnN6lK4jqM;5PUtiJ9b(4w{h0h=<739&G@#G+e4gk!jNWQ1o7 z+SU0TUDhWcy+Hmw0h!w`D22c7tPx)ue@y?JfP`#p9332A`+k2k{S+Pb?H&IjyERn_ zUdirAWMo-!e^)@Iycs8U>*v(`dU*?AX+Kgbt+}K$3lx$5C@V0iD|tQhf#zX3shx`@ zSy^@F_Bre+rv4Eb7hOWtj?H1b-Fsu*gyiYyY(w{rE6FE%_|0-ZGREOX8X!OrEsIX= zwdsd?%AnSl>RS3(MMjD6iOa}xD46!38wwv4+Y%@)HXWtC)k^d3ar@i zHH4D6!C(Dqw8W~`y4nvR{vBv<>zoT~9_TUSFO|WG~Ggs}MoQYn+4w)6|7|Li(Fv7EBt-R0f;*f0x zQ;hhI1bTRDG3e+zEZ&E}pu63_?};K_V-I6*&sQP(Va%1CFe;t7!kn@tp_q}HA{ErU zLOfPKK-(!8w!TSCw@4ryB#T64mT-)$Yu6@pLV$~ju7nH}=|dJUXnX)ovlT`VU=vKU zv(r~^cE8Ap$%?*f4yE9yVs^AQND%7_rypAMa$%V+VU;881TXjI7U|JTt0DU$UHD(2 zW9#-;h1$r$DH_R|tWM5A!npC$7V&g(fE56rw52`~r@0DwTHzPaXYOeJI1}~Dh&?=j z(K$o!`5CLsUadc4-wo@uyroYw(Swb+r7?Q`uq~^`ZLwV{3o}1Mg-*urox}4^@q)M= zchXxA?vL!~t{X~hq|Nz+QAQ!3~^rZbEUWQRC@Z^I|UR%kJ- z@J&-BY|OTCTD6`ZWbjQBW4;JF9GEKfK0D`mNkgMDrG=-$*B1c^{jNu?{LglXABvDZ zd-CgT>tvfGJKMQ)xO>oycj`=n{iWYzF%b2(Tq!ZY;`QOR9U5+ati~9x7?RDuz3H9B z=dB;#0sy{#mUPP>IZxb@$`s5@(CH?L9X>z?2<06b=jvuLG54pydZ@=_6iJM<+5{P3uBDNls`Xduc}J}bQmo#P>AKClvD6V&rs z?4&H?$J*h_XGIAChrg1}y*Nee+=p3^B-YA@Dvl)4r(6KaSWgN01M+f}2-g_SO1nrs zbM{3KP&@krcYzL*t8uQk*#U02^tDt2^c*{^pXx~C4TmS$nawA_@xoV~EQ)xnGsp+}RJ_>Kb%)v+!Qa6&!tcO{H-Qa4zF9>rvB-8kL8Qvn4 zQNF3riA8BZ1J5B@XMXv8U%h{<=1}|^&Q@Lz@_!C%fWI>aq7hw)-K@xfyaS6JiIrUfr|4B zeB2@RzUp{9?UFujpziQ{O%sKH8VWMCH3Rwh6crQHk0TylY*mG~0fMzp>SIU3-D+v^ zc_12v%HeY`8ie)Q)-dQwtBGz>^F zQc^a(P8FIVB;@f?!i`ooJ#Gs#3kwTX%`WEoVl$>P11iCt`3Q}&HA@T46-nHdm9hHz z`ULO&wiLryY&7&%v{BKqIQpHcoR1ZcyV@?&}4_7IEX(Du)Kd#7?9*I*iz+H z*=j=bChoQox+{|n`>Gncv4aYJzDIkez04As%Hn(y9e{mO2H_5$b3bW=zM8tq4^aD> z#zAE7WObjjps<+THAIH(c5*$5AHP%_x0de2`<2Jjll6VcJFm|7M9j7>;ZCSDSVOGg z*1XAl_~=~9r$2wYT;;f2d!#wPf1^qlKY-Cz1(k9wOf$<2)1ztmB@d{rN*^vYkluF0 zj?b}_!fF-h))!#S@I8BT^Zr6T`Y>g+he1j`s_E`6A%O2kj>hju-_!|3%zc+R9^lbi1G4>hl0 z#~&*V4W&QZF{)-WAGii03vQmW7{Xff8kIZ9GFe4S;-t?)3wFca;3jF)0I zD4aMO1XI~0@gy@wRE2xovpv{9`hD|rmf=6KL)ylztMV>>~(R~$u`2LK$r8@F+>sW2vg|wJ6HnmD*Yv5gp$a$7P?RxUbA)8f=M+^Ru zGgNQZH;SReQ>A2i+c2y8IU{5Ch$Yuuyhg=X7C4^=nFIa{JqCG~Ug?a=LEoNbk8^|r!mq|7J#s4QDiONS7) z46Y3o8dYl>P{@Q|E(mG0-24=%PubRX#=T6b&qB~;@(R<84@pX}nOWf*v-(ub*K_!6N+gnE(u&477(JvAeeB&LA8nzu6C zKtN!#z9!Oqkj#3j6G*jfP$J@7vx|(t%E;_wcDvxvPnJ89*3g9_1rxGx-Pq`ad8TG{ z(8whNo^`Sa5?055fuKauGv zBe$c}l-*x~;3%%mYs?2q9mJ+bAvDJ*Uzjz7YAB||N@H>6Cr+SHeT9V)1(A@gA1kE)vSDt8a{JPEn+UA#v?3h$%SNH4lZj$e$WS7@$W zUPK@~S8VTIAW_Dqlwmn0;Ls#rXkJ|%VvTz=%0SRzui0%lm+t|d9t1PWsl#6Tn!Zx- zox@@tKsxdCEUKuQh48(nm31LpGnIViK6ax*cc;jF976LD4f8^WIrh_QckD5_kvT-+ zi~<#Q%&>f3bTpgwQiAt&!*cslsii6wKN};9xIxXI)o_aIj+=9`S){i;`M=wj+Dggk znru?s6=oACe^!(MX;h?g)^*7d&IKa>oN>8qbKq>)i^cTHqX7v4cS~%}?p65n z>yr97jxOnhYpFJz0qAd29|6X>`^m?n$54@~<q#^WzF92 zRWu+zv%#vL>dwwnupB~Y`bh3x)`pqy26>FDD}8JzUTg#3>Bp;5jGNBpk{iGaX|!WZ z(}rrt){pVeq}ez6M|zH7J5QpueNJYnTAYQyZypa%805{r6+>i4k7IKNCy36Td2@1q zpQDzuRAe;D+x9eYvoBD=IefPMWP-I4snsAid#-7+oh&-Er?$GJw`3iE86z+2MWJz7 z>vuq~WL$u2vurSwyH&OdWC~I#^{9C?WRRwAc^g|gE9ay%!PIZoZd>T8V{Z3ab3=DjK zYjg5J=6hWu%R=~m5tyY(;@uTFODUZwH=d6NFoh}6ii>8H(gF&dQ7YvzV|D*PGCJ&o znAuNBXH)wH+;!_-j&sL1X!tijli@VJG3X;0$AuE@UQ=NVDmAspPbOaaiJz@clL&PmIa#T>cz)Qm#~Z<{I438CyX&layV z#t*Bje8P5DLjDYdC)%|}klqrE2EsToex}0#r+?k2xrlOsRzBDoZ_1=R?$YVZ>xJA^ zFc1!r3ULxh!ti)njRKO~nnpaZlrijTX*!WWa@NiLg6Dz;BoXyv$+q{dl^5E3vrp8gyN6J&fI&6u?dNc4}{gfMPyHA2aT zoLBEIb}QXl`iV~9CL0&{p**%H_$~P|dM2SO{3WmFoE5RRI*ScoWDOka3%V)*#tzSZ z(ph>>4GGE#8RXt<&X#C^K=9!-+ap#D)S&+%tCqnQkHLD0Kmm~3+n39j+t-&{PQL3vmlnT~$DRx6c`+6! zOeZMmfuOEHz^Ut7qCM1R4Z(0+K-BKshNc`9lcr%8OV+%J_9Wg{H@6jdwTUyw8$2Aj zDXccTg`|p}&8m+$dzF)K1yP6c9Na^(CkjL&a1*+MfTS&1>MitX7mhbk>?m-99|j@M-%EAY#An`~%@y_^ox2Z32w)#A6ok+&-{9r(=XFiEn@2*0}rt)=;tIC#Q32{l_fxy9bQ?=8-3p0&^1K| zs=gVkO42re_r<#J8(Ojx#I*{;)1l_vHb*?1HWy_n%9rO>$(p+$g|Skqa4PC!`xmSi zeP~bdw+~7iMJ7YMW{bgY)@X=~s`3eAN+YaYMDy*8=67uY=es3(Fiq>Coxk3j39LsD zy1Dr)Uw(A0u=p8D)~K@S#jGXyY~rqr#xhB)U{)q*c~JPSQ;a2+*|MyS#1bKBQf!+% zP`qjg>0~U3RmNI@f<)6b$-DOSnD1ICL21C-lDLR;29a8E^7xV`!fvPgH@{*8a4V}Uu)sUGxER-aRitM3F{1B2}8Rqr*No*$1 z!8WiQi8F-(2)5QsqlE#Cwb76G^Y287 z17D_l?WKX_Ydpifd|KKr&#&^8H;`CR|6L9LS|Gg+G>8+yKfeF1jsM;4cWwM1#(#`l zU%J=xzuo>rDgU1czl+%a5W4?4{#ZEkb^3?w{r~d#L-zjX_`{?7b^3?LzeMo=>G)3~ z_`e)a{_gm{lK9^NewW1m3Gm0=lD_%d%Kr=SUj*{M \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" else - JAVACMD="java" + PRG=`dirname "$PRG"`"/$link" fi -fi -if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >&- +APP_HOME="`pwd -P`" +cd "$SAVED" >&- + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." -fi -if [ -z "$JAVA_HOME" ] ; then - warn "JAVA_HOME environment variable is not set" fi # Increase the maximum file descriptors if we can. @@ -104,19 +101,18 @@ if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else - warn "Could not query businessSystem maximum file descriptor limit: $MAX_FD_LIMIT" + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi -# For Darwin, add GRADLE_APP_NAME to the JAVA_OPTS as -Xdock:name +# For Darwin, add options to specify how the application appears in the dock if $darwin; then - JAVA_OPTS="$JAVA_OPTS -Xdock:name=$GRADLE_APP_NAME" -# we may also want to set -Xdock:image + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then - JAVA_HOME=`cygpath --path --mixed "$JAVA_HOME"` + APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` # We build the pattern for arguments to be converted via cygpath @@ -143,7 +139,7 @@ if $cygwin ; then eval `echo args$i`="\"$arg\"" fi i=$((i+1)) - done + done case $i in (0) set -- ;; (1) set -- "$args0" ;; @@ -158,11 +154,11 @@ if $cygwin ; then esac fi -GRADLE_APP_BASE_NAME=`basename "$0"` +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" -exec "$JAVACMD" $JAVA_OPTS $GRADLE_OPTS \ - -classpath "$CLASSPATH" \ - -Dorg.gradle.appname="$GRADLE_APP_BASE_NAME" \ - -Dorg.gradle.wrapper.properties="$WRAPPER_PROPERTIES" \ - $STARTER_MAIN_CLASS \ - "$@" +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat index 4855abb..aec9973 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,24 +1,37 @@ @if "%DEBUG%" == "" @echo off @rem ########################################################################## -@rem ## -@rem Gradle startup script for Windows ## -@rem ## +@rem +@rem Gradle startup script for Windows +@rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal -@rem Uncomment those lines to set JVM options. GRADLE_OPTS and JAVA_OPTS can be used together. -@rem set GRADLE_OPTS=%GRADLE_OPTS% -Xmx512m -@rem set JAVA_OPTS=%JAVA_OPTS% -Xmx512m +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=.\ +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% @rem Find java.exe -set JAVA_EXE=java.exe -if not defined JAVA_HOME goto init +if defined JAVA_HOME goto findJavaFromJavaHome +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe @@ -29,14 +42,14 @@ echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. -echo. -goto end + +goto fail :init @rem Get command-line arguments, handling Windowz variants if not "%OS%" == "Windows_NT" goto win9xME_args -if "%eval[2+2]" == "4" goto 4NT_args +if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. @@ -56,27 +69,22 @@ set CMD_LINE_ARGS=%$ :execute @rem Setup the command line -set STARTER_MAIN_CLASS=org.gradle.wrapper.GradleWrapperMain -set CLASSPATH=%DIRNAME%\gradle\wrapper\gradle-wrapper.jar -set WRAPPER_PROPERTIES=%DIRNAME%\gradle\wrapper\gradle-wrapper.properties - -set GRADLE_OPTS=%JAVA_OPTS% %GRADLE_OPTS% -Dorg.gradle.wrapper.properties="%WRAPPER_PROPERTIES%" +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle -"%JAVA_EXE%" %GRADLE_OPTS% -classpath "%CLASSPATH%" %STARTER_MAIN_CLASS% %CMD_LINE_ARGS% +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd -if not "%OS%"=="Windows_NT" echo 1 > nul | choice /n /c:1 - +:fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit "%ERRORLEVEL%" -exit /b "%ERRORLEVEL%" +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal -:omega \ No newline at end of file +:omega From bbb867781deb9e8a0f073694d3ab3434426c7405 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Thu, 28 Nov 2013 08:13:57 -0500 Subject: [PATCH 06/70] upgrade to commons-pool 2 --- Makefile | 3 - pom.xml | 10 +- .../clients/jedis/BasicRedisPipeline.java | 2 - .../clients/jedis/BinaryJedisCommands.java | 32 +- .../clients/jedis/BinaryShardedJedis.java | 104 ++--- .../redis/clients/jedis/JedisFactory.java | 129 +++--- .../java/redis/clients/jedis/JedisPool.java | 73 ++-- .../redis/clients/jedis/JedisPoolConfig.java | 123 +----- .../clients/jedis/JedisSentinelPool.java | 31 +- .../redis/clients/jedis/ShardedJedisPool.java | 130 +++--- src/main/java/redis/clients/util/Pool.java | 114 +++--- .../clients/jedis/tests/JedisPoolTest.java | 197 +++++---- .../jedis/tests/JedisSentinelPoolTest.java | 67 +-- .../jedis/tests/JedisSentinelTest.java | 6 +- .../jedis/tests/ShardedJedisPipelineTest.java | 148 +++---- .../jedis/tests/ShardedJedisPoolTest.java | 257 ++++++------ .../jedis/tests/benchmark/PoolBenchmark.java | 76 ++-- .../commands/AllKindOfValuesCommandsTest.java | 13 +- .../commands/TransactionCommandsTest.java | 381 +++++++++--------- 19 files changed, 901 insertions(+), 995 deletions(-) diff --git a/Makefile b/Makefile index 761d033..3606f06 100644 --- a/Makefile +++ b/Makefile @@ -57,7 +57,6 @@ 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 can-failover mymaster yes sentinel parallel-syncs mymaster 1 pidfile /tmp/sentinel1.pid logfile /tmp/sentinel1.log @@ -69,7 +68,6 @@ daemonize yes sentinel monitor mymaster 127.0.0.1 6381 2 sentinel auth-pass mymaster foobared sentinel down-after-milliseconds mymaster 3000 -sentinel can-failover mymaster yes sentinel parallel-syncs mymaster 1 sentinel failover-timeout mymaster 900000 pidfile /tmp/sentinel2.pid @@ -82,7 +80,6 @@ daemonize yes sentinel monitor mymaster 127.0.0.1 6381 2 sentinel auth-pass mymaster foobared sentinel down-after-milliseconds mymaster 3000 -sentinel can-failover mymaster yes sentinel parallel-syncs mymaster 1 sentinel failover-timeout mymaster 900000 pidfile /tmp/sentinel3.pid diff --git a/pom.xml b/pom.xml index bb63109..8649428 100644 --- a/pom.xml +++ b/pom.xml @@ -59,9 +59,9 @@ test - commons-pool - commons-pool - 1.6 + org.apache.commons + commons-pool2 + 2.0 jar compile @@ -115,11 +115,11 @@ org.apache.maven.plugins maven-release-plugin - 2.4.1 + 2.4.2 maven-deploy-plugin - 2.7 + 2.8.1 internal.repo::default::file://${project.build.directory}/mvn-repo diff --git a/src/main/java/redis/clients/jedis/BasicRedisPipeline.java b/src/main/java/redis/clients/jedis/BasicRedisPipeline.java index 97658d8..a667ce9 100644 --- a/src/main/java/redis/clients/jedis/BasicRedisPipeline.java +++ b/src/main/java/redis/clients/jedis/BasicRedisPipeline.java @@ -1,8 +1,6 @@ package redis.clients.jedis; -import java.util.List; - /** * Pipelined responses for all of the low level, non key related commands */ diff --git a/src/main/java/redis/clients/jedis/BinaryJedisCommands.java b/src/main/java/redis/clients/jedis/BinaryJedisCommands.java index 35e1879..aed3011 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/BinaryShardedJedis.java b/src/main/java/redis/clients/jedis/BinaryShardedJedis.java index 2723aa1..da934a4 100644 --- a/src/main/java/redis/clients/jedis/BinaryShardedJedis.java +++ b/src/main/java/redis/clients/jedis/BinaryShardedJedis.java @@ -1,16 +1,15 @@ package redis.clients.jedis; -import redis.clients.jedis.BinaryClient.LIST_POSITION; -import redis.clients.util.Hashing; -import redis.clients.util.Sharded; - -import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; +import redis.clients.jedis.BinaryClient.LIST_POSITION; +import redis.clients.util.Hashing; +import redis.clients.util.Sharded; + public class BinaryShardedJedis extends Sharded implements BinaryJedisCommands { public BinaryShardedJedis(List shards) { @@ -31,10 +30,10 @@ public class BinaryShardedJedis extends Sharded } public void disconnect() { - for (Jedis jedis : getAllShards()) { - jedis.quit(); - jedis.disconnect(); - } + for (Jedis jedis : getAllShards()) { + jedis.quit(); + jedis.disconnect(); + } } protected Jedis create(JedisShardInfo shard) { @@ -102,10 +101,10 @@ public class BinaryShardedJedis extends Sharded } public Long del(byte[] key) { - Jedis j = getShard(key); - return j.del(key); + Jedis j = getShard(key); + return j.del(key); } - + public Long incrBy(byte[] key, long integer) { Jedis j = getShard(key); return j.incrBy(key, integer); @@ -197,23 +196,23 @@ public class BinaryShardedJedis extends Sharded } public Long strlen(final byte[] key) { - Jedis j = getShard(key); - return j.strlen(key); + Jedis j = getShard(key); + return j.strlen(key); } public Long lpushx(byte[] key, byte[]... string) { - Jedis j = getShard(key); - return j.lpushx(key, string); + Jedis j = getShard(key); + return j.lpushx(key, string); } public Long persist(final byte[] key) { - Jedis j = getShard(key); - return j.persist(key); + Jedis j = getShard(key); + return j.persist(key); } public Long rpushx(byte[] key, byte[]... string) { - Jedis j = getShard(key); - return j.rpushx(key, string); + Jedis j = getShard(key); + return j.rpushx(key, string); } public Long llen(byte[] key) { @@ -365,7 +364,7 @@ public class BinaryShardedJedis extends Sharded Jedis j = getShard(key); return j.zcount(key, min, max); } - + public Long zcount(byte[] key, byte[] min, byte[] max) { Jedis j = getShard(key); return j.zcount(key, min, max); @@ -394,8 +393,8 @@ public class BinaryShardedJedis extends Sharded } public Set zrangeByScore(byte[] key, byte[] min, byte[] max) { - Jedis j = getShard(key); - return j.zrangeByScore(key, min, max); + Jedis j = getShard(key); + return j.zrangeByScore(key, min, max); } public Set zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max) { @@ -404,14 +403,15 @@ public class BinaryShardedJedis extends Sharded } public Set zrangeByScoreWithScores(byte[] key, byte[] min, - byte[] max, int offset, int count) { + byte[] max, int offset, int count) { Jedis j = getShard(key); return j.zrangeByScoreWithScores(key, min, max, offset, count); } - public Set zrangeByScore(byte[] key, byte[] min, byte[] max, int offset, int count) { - Jedis j = getShard(key); - return j.zrangeByScore(key, min, max, offset, count); + public Set zrangeByScore(byte[] key, byte[] min, byte[] max, + int offset, int count) { + Jedis j = getShard(key); + return j.zrangeByScore(key, min, max, offset, count); } public Set zrevrangeByScore(byte[] key, double max, double min) { @@ -436,7 +436,7 @@ public class BinaryShardedJedis extends Sharded Jedis j = getShard(key); return j.zrevrangeByScoreWithScores(key, max, min, offset, count); } - + public Set zrevrangeByScore(byte[] key, byte[] max, byte[] min) { Jedis j = getShard(key); return j.zrevrangeByScore(key, max, min); @@ -449,13 +449,13 @@ public class BinaryShardedJedis extends Sharded } public Set zrevrangeByScoreWithScores(byte[] key, byte[] max, - byte[] min) { + byte[] min) { Jedis j = getShard(key); return j.zrevrangeByScoreWithScores(key, max, min); } public Set zrevrangeByScoreWithScores(byte[] key, byte[] max, - byte[] min, int offset, int count) { + byte[] min, int offset, int count) { Jedis j = getShard(key); return j.zrevrangeByScoreWithScores(key, max, min, offset, count); } @@ -510,57 +510,57 @@ public class BinaryShardedJedis extends Sharded } public Boolean setbit(byte[] key, long offset, boolean value) { - Jedis j = getShard(key); - return j.setbit(key, offset, value); + Jedis j = getShard(key); + return j.setbit(key, offset, value); } public Boolean setbit(byte[] key, long offset, byte[] value) { - Jedis j = getShard(key); - return j.setbit(key, offset, value); + Jedis j = getShard(key); + return j.setbit(key, offset, value); } public Boolean getbit(byte[] key, long offset) { - Jedis j = getShard(key); - return j.getbit(key, offset); + Jedis j = getShard(key); + return j.getbit(key, offset); } public Long setrange(byte[] key, long offset, byte[] value) { - Jedis j = getShard(key); - return j.setrange(key, offset, value); + Jedis j = getShard(key); + return j.setrange(key, offset, value); } public byte[] getrange(byte[] key, long startOffset, long endOffset) { - Jedis j = getShard(key); - return j.getrange(key, startOffset, endOffset); + Jedis j = getShard(key); + return j.getrange(key, startOffset, endOffset); } public Long move(byte[] key, int dbIndex) { - Jedis j = getShard(key); - return j.move(key, dbIndex); + Jedis j = getShard(key); + return j.move(key, dbIndex); } public byte[] echo(byte[] arg) { - Jedis j = getShard(arg); - return j.echo(arg); + Jedis j = getShard(arg); + return j.echo(arg); } public List brpop(byte[] arg) { - Jedis j = getShard(arg); - return j.brpop(arg); + Jedis j = getShard(arg); + return j.brpop(arg); } public List blpop(byte[] arg) { - Jedis j = getShard(arg); - return j.blpop(arg); + Jedis j = getShard(arg); + return j.blpop(arg); } public Long bitcount(byte[] key) { - Jedis j = getShard(key); - return j.bitcount(key); + Jedis j = getShard(key); + return j.bitcount(key); } public Long bitcount(byte[] key, long start, long end) { - Jedis j = getShard(key); - return j.bitcount(key, start, end); + Jedis j = getShard(key); + return j.bitcount(key, start, end); } } \ No newline at end of file diff --git a/src/main/java/redis/clients/jedis/JedisFactory.java b/src/main/java/redis/clients/jedis/JedisFactory.java index 66592fe..3597d69 100644 --- a/src/main/java/redis/clients/jedis/JedisFactory.java +++ b/src/main/java/redis/clients/jedis/JedisFactory.java @@ -1,11 +1,13 @@ package redis.clients.jedis; -import org.apache.commons.pool.BasePoolableObjectFactory; +import org.apache.commons.pool2.PooledObject; +import org.apache.commons.pool2.PooledObjectFactory; +import org.apache.commons.pool2.impl.DefaultPooledObject; /** * PoolableObjectFactory custom impl. */ -class JedisFactory extends BasePoolableObjectFactory { +class JedisFactory implements PooledObjectFactory { private final String host; private final int port; private final int timeout; @@ -13,75 +15,80 @@ class JedisFactory extends BasePoolableObjectFactory { private final int database; private final String clientName; - public JedisFactory(final String host, final int port, - final int timeout, final String password, final int database) { - this(host, port, timeout, password, database, null); - } - public JedisFactory(final String host, final int port, - final int timeout, final String password, final int database, final String clientName) { - super(); - this.host = host; - this.port = port; - this.timeout = timeout; - this.password = password; - this.database = database; - this.clientName = clientName; + public JedisFactory(final String host, final int port, final int timeout, + final String password, final int database) { + this(host, port, timeout, password, database, null); } - public Object makeObject() throws Exception { - final Jedis jedis = new Jedis(this.host, this.port, this.timeout); - - jedis.connect(); - if (null != this.password) { - jedis.auth(this.password); - } - if( database != 0 ) { - jedis.select(database); - } - if ( clientName != null ) { - jedis.clientSetname(clientName); - } - - return jedis; + public JedisFactory(final String host, final int port, final int timeout, + final String password, final int database, final String clientName) { + super(); + this.host = host; + this.port = port; + this.timeout = timeout; + this.password = password; + this.database = database; + this.clientName = clientName; } @Override - public void activateObject(Object obj) throws Exception { - if (obj instanceof Jedis) { - final Jedis jedis = (Jedis)obj; - if (jedis.getDB() != database) { - jedis.select(database); - } + public void activateObject(PooledObject pooledJedis) + throws Exception { + final BinaryJedis jedis = pooledJedis.getObject(); + if (jedis.getDB() != database) { + jedis.select(database); + } + + } + + @Override + public void destroyObject(PooledObject pooledJedis) throws Exception { + final BinaryJedis jedis = pooledJedis.getObject(); + if (jedis.isConnected()) { + try { + try { + jedis.quit(); + } catch (Exception e) { } + jedis.disconnect(); + } catch (Exception e) { + + } + } + } - public void destroyObject(final Object obj) throws Exception { - if (obj instanceof Jedis) { - final Jedis jedis = (Jedis) obj; - if (jedis.isConnected()) { - try { - try { - jedis.quit(); - } catch (Exception e) { - } - jedis.disconnect(); - } catch (Exception e) { + @Override + public PooledObject makeObject() throws Exception { + final Jedis jedis = new Jedis(this.host, this.port, this.timeout); - } - } - } + jedis.connect(); + if (null != this.password) { + jedis.auth(this.password); + } + if (database != 0) { + jedis.select(database); + } + if (clientName != null) { + jedis.clientSetname(clientName); + } + + return new DefaultPooledObject(jedis); } - public boolean validateObject(final Object obj) { - if (obj instanceof Jedis) { - final Jedis jedis = (Jedis) obj; - try { - return jedis.isConnected() && jedis.ping().equals("PONG"); - } catch (final Exception e) { - return false; - } - } else { - return false; - } + @Override + public void passivateObject(PooledObject pooledJedis) + throws Exception { + // TODO maybe should select db 0? Not sure right now. + } + + @Override + public boolean validateObject(PooledObject pooledJedis) { + final BinaryJedis jedis = pooledJedis.getObject(); + try { + return jedis.isConnected() && jedis.ping().equals("PONG"); + } catch (final Exception e) { + return false; + } } } \ No newline at end of file diff --git a/src/main/java/redis/clients/jedis/JedisPool.java b/src/main/java/redis/clients/jedis/JedisPool.java index 6e8b74d..58212ba 100644 --- a/src/main/java/redis/clients/jedis/JedisPool.java +++ b/src/main/java/redis/clients/jedis/JedisPool.java @@ -2,19 +2,21 @@ package redis.clients.jedis; import java.net.URI; -import org.apache.commons.pool.impl.GenericObjectPool; -import org.apache.commons.pool.impl.GenericObjectPool.Config; +import org.apache.commons.pool2.impl.GenericObjectPool; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import redis.clients.util.Pool; public class JedisPool extends Pool { - public JedisPool(final Config poolConfig, final String host) { - this(poolConfig, host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE, null); + public JedisPool(final GenericObjectPoolConfig poolConfig, final String host) { + this(poolConfig, host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT, + null, Protocol.DEFAULT_DATABASE, null); } public JedisPool(String host, int port) { - this(new Config(), host, port, Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE, null); + this(new GenericObjectPoolConfig(), host, port, + Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE, null); } public JedisPool(final String host) { @@ -24,12 +26,15 @@ public class JedisPool extends Pool { int port = uri.getPort(); String password = uri.getUserInfo().split(":", 2)[1]; int database = Integer.parseInt(uri.getPath().split("/", 2)[1]); - this.internalPool = new GenericObjectPool(new JedisFactory(h, port, - Protocol.DEFAULT_TIMEOUT, password, database, null), new Config()); + this.internalPool = new GenericObjectPool( + new JedisFactory(h, port, Protocol.DEFAULT_TIMEOUT, + password, database, null), + new GenericObjectPoolConfig()); } else { - this.internalPool = new GenericObjectPool(new JedisFactory(host, - Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT, null, - Protocol.DEFAULT_DATABASE, null), new Config()); + this.internalPool = new GenericObjectPool(new JedisFactory( + host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT, + null, Protocol.DEFAULT_DATABASE, null), + new GenericObjectPoolConfig()); } } @@ -38,39 +43,47 @@ public class JedisPool extends Pool { int port = uri.getPort(); String password = uri.getUserInfo().split(":", 2)[1]; int database = Integer.parseInt(uri.getPath().split("/", 2)[1]); - this.internalPool = new GenericObjectPool(new JedisFactory(h, port, - Protocol.DEFAULT_TIMEOUT, password, database, null), new Config()); + this.internalPool = new GenericObjectPool(new JedisFactory(h, + port, Protocol.DEFAULT_TIMEOUT, password, database, null), + new GenericObjectPoolConfig()); } - public JedisPool(final Config poolConfig, final String host, int port, - int timeout, final String password) { - this(poolConfig, host, port, timeout, password, Protocol.DEFAULT_DATABASE, null); + public JedisPool(final GenericObjectPoolConfig poolConfig, + final String host, int port, int timeout, final String password) { + this(poolConfig, host, port, timeout, password, + Protocol.DEFAULT_DATABASE, null); } - public JedisPool(final Config poolConfig, final String host, final int port) { - this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE, null); + public JedisPool(final GenericObjectPoolConfig poolConfig, + final String host, final int port) { + this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT, null, + Protocol.DEFAULT_DATABASE, null); } - public JedisPool(final Config poolConfig, final String host, final int port, final int timeout) { - this(poolConfig, host, port, timeout, null, Protocol.DEFAULT_DATABASE, null); + public JedisPool(final GenericObjectPoolConfig poolConfig, + final String host, final int port, final int timeout) { + this(poolConfig, host, port, timeout, null, Protocol.DEFAULT_DATABASE, + null); } - public JedisPool(final Config poolConfig, final String host, int port, int timeout, final String password, - final int database) { - this(poolConfig, host, port, timeout, password, database, null); + public JedisPool(final GenericObjectPoolConfig poolConfig, + final String host, int port, int timeout, final String password, + final int database) { + this(poolConfig, host, port, timeout, password, database, null); } - public JedisPool(final Config poolConfig, final String host, int port, int timeout, final String password, - final int database, final String clientName) { - super(poolConfig, new JedisFactory(host, port, timeout, password, database, clientName)); + public JedisPool(final GenericObjectPoolConfig poolConfig, + final String host, int port, int timeout, final String password, + final int database, final String clientName) { + super(poolConfig, new JedisFactory(host, port, timeout, password, + database, clientName)); } - - public void returnBrokenResource(final BinaryJedis resource) { - returnBrokenResourceObject(resource); + public void returnBrokenResource(final Jedis resource) { + returnBrokenResourceObject(resource); } - public void returnResource(final BinaryJedis resource) { - returnResourceObject(resource); + public void returnResource(final Jedis resource) { + returnResourceObject(resource); } } diff --git a/src/main/java/redis/clients/jedis/JedisPoolConfig.java b/src/main/java/redis/clients/jedis/JedisPoolConfig.java index b079c07..fff38d4 100644 --- a/src/main/java/redis/clients/jedis/JedisPoolConfig.java +++ b/src/main/java/redis/clients/jedis/JedisPoolConfig.java @@ -1,28 +1,8 @@ package redis.clients.jedis; -import org.apache.commons.pool.impl.GenericObjectPool.Config; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; -/** - * Subclass of org.apache.commons.pool.impl.GenericObjectPool.Config that - * includes getters/setters so it can be more easily configured by Spring and - * other IoC frameworks. - * - * Spring example: - * - * - * - * - * - * - * For information on parameters refer to: - * - * http://commons.apache.org/pool/apidocs/org/apache/commons/pool/impl/ - * GenericObjectPool.html - */ -public class JedisPoolConfig extends Config { +public class JedisPoolConfig extends GenericObjectPoolConfig { public JedisPoolConfig() { // defaults to make your life with connection pool easier :) setTestWhileIdle(true); @@ -30,103 +10,4 @@ public class JedisPoolConfig extends Config { setTimeBetweenEvictionRunsMillis(30000); setNumTestsPerEvictionRun(-1); } - - public int getMaxIdle() { - return maxIdle; - } - - public void setMaxIdle(int maxIdle) { - this.maxIdle = maxIdle; - } - - public int getMinIdle() { - return minIdle; - } - - public void setMinIdle(int minIdle) { - this.minIdle = minIdle; - } - - public int getMaxActive() { - return maxActive; - } - - public void setMaxActive(int maxActive) { - this.maxActive = maxActive; - } - - public long getMaxWait() { - return maxWait; - } - - public void setMaxWait(long maxWait) { - this.maxWait = maxWait; - } - - public byte getWhenExhaustedAction() { - return whenExhaustedAction; - } - - public void setWhenExhaustedAction(byte whenExhaustedAction) { - this.whenExhaustedAction = whenExhaustedAction; - } - - public boolean isTestOnBorrow() { - return testOnBorrow; - } - - public void setTestOnBorrow(boolean testOnBorrow) { - this.testOnBorrow = testOnBorrow; - } - - public boolean isTestOnReturn() { - return testOnReturn; - } - - public void setTestOnReturn(boolean testOnReturn) { - this.testOnReturn = testOnReturn; - } - - public boolean isTestWhileIdle() { - return testWhileIdle; - } - - public void setTestWhileIdle(boolean testWhileIdle) { - this.testWhileIdle = testWhileIdle; - } - - public long getTimeBetweenEvictionRunsMillis() { - return timeBetweenEvictionRunsMillis; - } - - public void setTimeBetweenEvictionRunsMillis( - long timeBetweenEvictionRunsMillis) { - this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; - } - - public int getNumTestsPerEvictionRun() { - return numTestsPerEvictionRun; - } - - public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) { - this.numTestsPerEvictionRun = numTestsPerEvictionRun; - } - - public long getMinEvictableIdleTimeMillis() { - return minEvictableIdleTimeMillis; - } - - public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) { - this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; - } - - public long getSoftMinEvictableIdleTimeMillis() { - return softMinEvictableIdleTimeMillis; - } - - public void setSoftMinEvictableIdleTimeMillis( - long softMinEvictableIdleTimeMillis) { - this.softMinEvictableIdleTimeMillis = softMinEvictableIdleTimeMillis; - } - } diff --git a/src/main/java/redis/clients/jedis/JedisSentinelPool.java b/src/main/java/redis/clients/jedis/JedisSentinelPool.java index 0d87bdd..2761c90 100644 --- a/src/main/java/redis/clients/jedis/JedisSentinelPool.java +++ b/src/main/java/redis/clients/jedis/JedisSentinelPool.java @@ -7,14 +7,14 @@ import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Logger; -import org.apache.commons.pool.impl.GenericObjectPool.Config; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.util.Pool; public class JedisSentinelPool extends Pool { - protected Config poolConfig; + protected GenericObjectPoolConfig poolConfig; protected int timeout = Protocol.DEFAULT_TIMEOUT; @@ -27,57 +27,58 @@ public class JedisSentinelPool extends Pool { protected Logger log = Logger.getLogger(getClass().getName()); public JedisSentinelPool(String masterName, Set sentinels, - final Config poolConfig) { + final GenericObjectPoolConfig poolConfig) { this(masterName, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE); } public JedisSentinelPool(String masterName, Set sentinels) { - this(masterName, sentinels, new Config(), Protocol.DEFAULT_TIMEOUT, - null, Protocol.DEFAULT_DATABASE); + this(masterName, sentinels, new GenericObjectPoolConfig(), + Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE); } public JedisSentinelPool(String masterName, Set sentinels, String password) { - this(masterName, sentinels, new Config(), Protocol.DEFAULT_TIMEOUT, - password); + this(masterName, sentinels, new GenericObjectPoolConfig(), + Protocol.DEFAULT_TIMEOUT, password); } public JedisSentinelPool(String masterName, Set sentinels, - final Config poolConfig, int timeout, final String password) { + final GenericObjectPoolConfig poolConfig, int timeout, + final String password) { this(masterName, sentinels, poolConfig, timeout, password, Protocol.DEFAULT_DATABASE); } public JedisSentinelPool(String masterName, Set sentinels, - final Config poolConfig, final int timeout) { + final GenericObjectPoolConfig poolConfig, final int timeout) { this(masterName, sentinels, poolConfig, timeout, null, Protocol.DEFAULT_DATABASE); } public JedisSentinelPool(String masterName, Set sentinels, - final Config poolConfig, final String password) { + final GenericObjectPoolConfig poolConfig, final String password) { this(masterName, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT, password); } public JedisSentinelPool(String masterName, Set sentinels, - final Config poolConfig, int timeout, final String password, - final int database) { + final GenericObjectPoolConfig poolConfig, int timeout, + final String password, final int database) { this.poolConfig = poolConfig; this.timeout = timeout; this.password = password; this.database = database; - + HostAndPort master = initSentinels(sentinels, masterName); initPool(master); } - public void returnBrokenResource(final BinaryJedis resource) { + public void returnBrokenResource(final Jedis resource) { returnBrokenResourceObject(resource); } - public void returnResource(final BinaryJedis resource) { + public void returnResource(final Jedis resource) { returnResourceObject(resource); } diff --git a/src/main/java/redis/clients/jedis/ShardedJedisPool.java b/src/main/java/redis/clients/jedis/ShardedJedisPool.java index ce11884..dd56ac1 100644 --- a/src/main/java/redis/clients/jedis/ShardedJedisPool.java +++ b/src/main/java/redis/clients/jedis/ShardedJedisPool.java @@ -3,83 +3,101 @@ package redis.clients.jedis; import java.util.List; import java.util.regex.Pattern; -import org.apache.commons.pool.BasePoolableObjectFactory; -import org.apache.commons.pool.impl.GenericObjectPool; +import org.apache.commons.pool2.PooledObject; +import org.apache.commons.pool2.PooledObjectFactory; +import org.apache.commons.pool2.impl.DefaultPooledObject; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import redis.clients.util.Hashing; import redis.clients.util.Pool; public class ShardedJedisPool extends Pool { - public ShardedJedisPool(final GenericObjectPool.Config poolConfig, - List shards) { - this(poolConfig, shards, Hashing.MURMUR_HASH); + public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, + List shards) { + this(poolConfig, shards, Hashing.MURMUR_HASH); } - public ShardedJedisPool(final GenericObjectPool.Config poolConfig, - List shards, Hashing algo) { - this(poolConfig, shards, algo, null); + public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, + List shards, Hashing algo) { + this(poolConfig, shards, algo, null); } - public ShardedJedisPool(final GenericObjectPool.Config poolConfig, - List shards, Pattern keyTagPattern) { - this(poolConfig, shards, Hashing.MURMUR_HASH, keyTagPattern); + public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, + List shards, Pattern keyTagPattern) { + this(poolConfig, shards, Hashing.MURMUR_HASH, keyTagPattern); } - public ShardedJedisPool(final GenericObjectPool.Config poolConfig, - List shards, Hashing algo, Pattern keyTagPattern) { - super(poolConfig, new ShardedJedisFactory(shards, algo, keyTagPattern)); + public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, + List shards, Hashing algo, Pattern keyTagPattern) { + super(poolConfig, new ShardedJedisFactory(shards, algo, keyTagPattern)); } /** * PoolableObjectFactory custom impl. */ - private static class ShardedJedisFactory extends BasePoolableObjectFactory { - private List shards; - private Hashing algo; - private Pattern keyTagPattern; + private static class ShardedJedisFactory implements + PooledObjectFactory { + private List shards; + private Hashing algo; + private Pattern keyTagPattern; - public ShardedJedisFactory(List shards, Hashing algo, - Pattern keyTagPattern) { - this.shards = shards; - this.algo = algo; - this.keyTagPattern = keyTagPattern; - } + public ShardedJedisFactory(List shards, Hashing algo, + Pattern keyTagPattern) { + this.shards = shards; + this.algo = algo; + this.keyTagPattern = keyTagPattern; + } - public Object makeObject() throws Exception { - ShardedJedis jedis = new ShardedJedis(shards, algo, keyTagPattern); - return jedis; - } + @Override + public PooledObject makeObject() throws Exception { + ShardedJedis jedis = new ShardedJedis(shards, algo, keyTagPattern); + return new DefaultPooledObject(jedis); + } - public void destroyObject(final Object obj) throws Exception { - if ((obj != null) && (obj instanceof ShardedJedis)) { - ShardedJedis shardedJedis = (ShardedJedis) obj; - for (Jedis jedis : shardedJedis.getAllShards()) { - try { - try { - jedis.quit(); - } catch (Exception e) { + @Override + public void destroyObject(PooledObject pooledShardedJedis) + throws Exception { + final ShardedJedis shardedJedis = pooledShardedJedis.getObject(); + for (Jedis jedis : shardedJedis.getAllShards()) { + try { + try { + jedis.quit(); + } catch (Exception e) { - } - jedis.disconnect(); - } catch (Exception e) { + } + jedis.disconnect(); + } catch (Exception e) { - } - } - } - } + } + } + } - public boolean validateObject(final Object obj) { - try { - ShardedJedis jedis = (ShardedJedis) obj; - for (Jedis shard : jedis.getAllShards()) { - if (!shard.ping().equals("PONG")) { - return false; - } - } - return true; - } catch (Exception ex) { - return false; - } - } + @Override + public boolean validateObject( + PooledObject pooledShardedJedis) { + try { + ShardedJedis jedis = pooledShardedJedis.getObject(); + for (Jedis shard : jedis.getAllShards()) { + if (!shard.ping().equals("PONG")) { + return false; + } + } + return true; + } catch (Exception ex) { + return false; + } + } + + @Override + public void activateObject(PooledObject p) + throws Exception { + + } + + @Override + public void passivateObject(PooledObject p) + throws Exception { + + } } } \ No newline at end of file diff --git a/src/main/java/redis/clients/util/Pool.java b/src/main/java/redis/clients/util/Pool.java index fb4fede..09d8ebb 100644 --- a/src/main/java/redis/clients/util/Pool.java +++ b/src/main/java/redis/clients/util/Pool.java @@ -1,82 +1,84 @@ package redis.clients.util; -import org.apache.commons.pool.PoolableObjectFactory; -import org.apache.commons.pool.impl.GenericObjectPool; +import org.apache.commons.pool2.PooledObjectFactory; +import org.apache.commons.pool2.impl.GenericObjectPool; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisException; public abstract class Pool { - protected GenericObjectPool internalPool; + protected GenericObjectPool internalPool; /** - * Using this constructor means you have to set - * and initialize the internalPool yourself. + * Using this constructor means you have to set and initialize the + * internalPool yourself. */ - public Pool() {} - - public Pool(final GenericObjectPool.Config poolConfig, - PoolableObjectFactory factory) { - initPool(poolConfig, factory); + public Pool() { } - - public void initPool(final GenericObjectPool.Config poolConfig, PoolableObjectFactory factory) { - - if (this.internalPool != null) { - try { - closeInternalPool(); - } catch (Exception e) { - } - } - - this.internalPool = new GenericObjectPool(factory, poolConfig); + + public Pool(final GenericObjectPoolConfig poolConfig, + PooledObjectFactory factory) { + initPool(poolConfig, factory); } - - @SuppressWarnings("unchecked") + + public void initPool(final GenericObjectPoolConfig poolConfig, + PooledObjectFactory factory) { + + if (this.internalPool != null) { + try { + closeInternalPool(); + } catch (Exception e) { + } + } + + this.internalPool = new GenericObjectPool(factory, poolConfig); + } + public T getResource() { - try { - return (T) internalPool.borrowObject(); - } catch (Exception e) { - throw new JedisConnectionException( - "Could not get a resource from the pool", e); - } + try { + return internalPool.borrowObject(); + } catch (Exception e) { + throw new JedisConnectionException( + "Could not get a resource from the pool", e); + } } - - public void returnResourceObject(final Object resource) { - try { - internalPool.returnObject(resource); - } catch (Exception e) { - throw new JedisException( - "Could not return the resource to the pool", e); - } + + public void returnResourceObject(final T resource) { + try { + internalPool.returnObject(resource); + } catch (Exception e) { + throw new JedisException( + "Could not return the resource to the pool", e); + } } - + public void returnBrokenResource(final T resource) { - returnBrokenResourceObject(resource); + returnBrokenResourceObject(resource); } - + public void returnResource(final T resource) { - returnResourceObject(resource); + returnResourceObject(resource); } - + public void destroy() { - closeInternalPool(); + closeInternalPool(); } - - protected void returnBrokenResourceObject(final Object resource) { - try { - internalPool.invalidateObject(resource); - } catch (Exception e) { - throw new JedisException( - "Could not return the resource to the pool", e); - } + + protected void returnBrokenResourceObject(final T resource) { + try { + internalPool.invalidateObject(resource); + } catch (Exception e) { + throw new JedisException( + "Could not return the resource to the pool", e); + } } protected void closeInternalPool() { - try { - internalPool.close(); - } catch (Exception e) { - throw new JedisException("Could not destroy the pool", e); - } + try { + internalPool.close(); + } catch (Exception e) { + throw new JedisException("Could not destroy the pool", e); + } } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java b/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java index 58964ff..286d681 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java @@ -3,12 +3,10 @@ package redis.clients.jedis.tests; import java.net.URI; import java.net.URISyntaxException; -import org.apache.commons.pool.impl.GenericObjectPool; -import org.apache.commons.pool.impl.GenericObjectPool.Config; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.junit.Assert; import org.junit.Test; -import redis.clients.jedis.BinaryJedis; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; @@ -20,111 +18,103 @@ public class JedisPoolTest extends Assert { @Test public void checkConnections() { - JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.host, - hnp.port, 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.host, + hnp.port, 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.host, - hnp.port); - 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.host, + hnp.port); + 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.host, - hnp.port); - Jedis jedis = pool.getResource(); - jedis.auth("foobared"); - jedis.set("foo", "0"); - pool.returnResource(jedis); + JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.host, + hnp.port); + 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.host, - hnp.port); - Jedis jedis = pool.getResource(); - jedis.auth("foobared"); - jedis.quit(); - pool.returnBrokenResource(jedis); + JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.host, + hnp.port); + 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) public void checkPoolOverflow() { - Config config = new Config(); - config.maxActive = 1; - config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL; - JedisPool pool = new JedisPool(config, hnp.host, hnp.port); - Jedis jedis = pool.getResource(); - jedis.auth("foobared"); - jedis.set("foo", "0"); + GenericObjectPoolConfig config = new GenericObjectPoolConfig(); + config.setMaxTotal(1); + config.setBlockWhenExhausted(false); + JedisPool pool = new JedisPool(config, hnp.host, hnp.port); + Jedis jedis = pool.getResource(); + jedis.auth("foobared"); + jedis.set("foo", "0"); - Jedis newJedis = pool.getResource(); - newJedis.auth("foobared"); - newJedis.incr("foo"); + Jedis newJedis = pool.getResource(); + newJedis.auth("foobared"); + newJedis.incr("foo"); } @Test public void securePool() { - JedisPoolConfig config = new JedisPoolConfig(); - config.setTestOnBorrow(true); - JedisPool pool = new JedisPool(config, hnp.host, hnp.port, 2000, "foobared"); - Jedis jedis = pool.getResource(); - jedis.set("foo", "bar"); - pool.returnResource(jedis); - pool.destroy(); + JedisPoolConfig config = new JedisPoolConfig(); + config.setTestOnBorrow(true); + JedisPool pool = new JedisPool(config, hnp.host, hnp.port, 2000, + "foobared"); + Jedis jedis = pool.getResource(); + jedis.set("foo", "bar"); + pool.returnResource(jedis); + pool.destroy(); } @Test public void nonDefaultDatabase() { - JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.host, - hnp.port, 2000, "foobared"); - Jedis jedis0 = pool0.getResource(); - jedis0.set("foo", "bar"); - assertEquals( "bar", jedis0.get("foo") ); - pool0.returnResource(jedis0); - pool0.destroy(); + JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.host, + hnp.port, 2000, "foobared"); + Jedis jedis0 = pool0.getResource(); + jedis0.set("foo", "bar"); + assertEquals("bar", jedis0.get("foo")); + pool0.returnResource(jedis0); + pool0.destroy(); - JedisPool pool1 = new JedisPool(new JedisPoolConfig(), hnp.host, - hnp.port, 2000, "foobared", 1); - Jedis jedis1 = pool1.getResource(); - assertNull( jedis1.get("foo") ); - pool1.returnResource(jedis0); - pool1.destroy(); - } - - @Test - public void returnBinary() { - JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.host, - hnp.port, 2000); - BinaryJedis jedis = pool.getResource(); - pool.returnResource(jedis); - pool.destroy(); + JedisPool pool1 = new JedisPool(new JedisPoolConfig(), hnp.host, + hnp.port, 2000, "foobared", 1); + Jedis jedis1 = pool1.getResource(); + assertNull(jedis1.get("foo")); + pool1.returnResource(jedis1); + pool1.destroy(); } @Test @@ -145,43 +135,44 @@ public class JedisPoolTest extends Assert { j.auth("foobared"); j.select(2); j.set("foo", "bar"); - JedisPool pool = new JedisPool(new URI("redis://:foobared@localhost:6380/2")); + JedisPool pool = new JedisPool(new URI( + "redis://:foobared@localhost:6380/2")); Jedis jedis = pool.getResource(); assertEquals("PONG", jedis.ping()); assertEquals("bar", jedis.get("foo")); } - @Test - public void selectDatabaseOnActivation() { - JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.host, hnp.port, 2000, "foobared"); + @Test + public void selectDatabaseOnActivation() { + JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.host, + hnp.port, 2000, "foobared"); - Jedis jedis0 = pool.getResource(); - assertEquals(0L, jedis0.getDB().longValue()); - - jedis0.select(1); - assertEquals(1L, jedis0.getDB().longValue()); + Jedis jedis0 = pool.getResource(); + assertEquals(0L, jedis0.getDB().longValue()); - pool.returnResource(jedis0); + jedis0.select(1); + assertEquals(1L, jedis0.getDB().longValue()); - Jedis jedis1 = pool.getResource(); - assertTrue("Jedis instance was not reused", jedis1 == jedis0); - assertEquals(0L, jedis1.getDB().longValue()); + pool.returnResource(jedis0); - pool.returnResource(jedis1); - pool.destroy(); - } + Jedis jedis1 = pool.getResource(); + assertTrue("Jedis instance was not reused", jedis1 == jedis0); + assertEquals(0L, jedis1.getDB().longValue()); + + pool.returnResource(jedis1); + pool.destroy(); + } @Test public void customClientName() { - JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.host, - hnp.port, 2000, "foobared", 0, "my_shiny_client_name"); + JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.host, + hnp.port, 2000, "foobared", 0, "my_shiny_client_name"); - Jedis jedis = pool0.getResource(); + Jedis jedis = pool0.getResource(); - assertEquals("my_shiny_client_name", jedis.clientGetname()); + assertEquals("my_shiny_client_name", jedis.clientGetname()); - pool0.returnResource(jedis); - pool0.destroy(); + pool0.returnResource(jedis); + pool0.destroy(); } } - diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java index 5f8e494..2487c8d 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java @@ -3,7 +3,7 @@ package redis.clients.jedis.tests; import java.util.HashSet; import java.util.Set; -import org.apache.commons.pool.impl.GenericObjectPool.Config; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.junit.Before; import org.junit.Test; @@ -19,7 +19,7 @@ public class JedisSentinelPoolTest extends JedisTestBase { protected static HostAndPort slave1 = HostAndPortUtil.getRedisServers() .get(3); protected static HostAndPort slave2 = HostAndPortUtil.getRedisServers() - .get(4); + .get(4); protected static HostAndPort sentinel1 = HostAndPortUtil .getSentinelServers().get(1); protected static HostAndPort sentinel2 = HostAndPortUtil @@ -28,7 +28,7 @@ public class JedisSentinelPoolTest extends JedisTestBase { protected static Jedis masterJedis; protected static Jedis slaveJedis1; protected static Jedis slaveJedis2; - + protected static int slaveCount = 0; protected Set sentinels = new HashSet(); @@ -45,7 +45,7 @@ public class JedisSentinelPoolTest extends JedisTestBase { slaveJedis1.auth("foobared"); slaveJedis1.slaveof(master.host, master.port); slaveCount++; - + slaveJedis2 = new Jedis(slave2.host, slave2.port); slaveJedis2.auth("foobared"); slaveJedis2.slaveof(master.host, master.port); @@ -55,44 +55,45 @@ public class JedisSentinelPoolTest extends JedisTestBase { sentinels.add(sentinel2.toString()); // FIXME: The following allows the master/slave relationship to - // be established, and let sentinels know about this relationship. + // be established, and let sentinels know about this relationship. // We can do this more elegantly. Thread.sleep(10000); } @Test public void ensureSafeTwiceFailover() throws InterruptedException { - JedisSentinelPool pool = new JedisSentinelPool("mymaster", sentinels, - new Config(), 1000, "foobared", 2); - - // perform failover - doSegFaultMaster(pool); - - // perform failover once again - doSegFaultMaster(pool); - - // you can test failover as much as possible - // but you need to prepare additional slave per failover + JedisSentinelPool pool = new JedisSentinelPool("mymaster", sentinels, + new GenericObjectPoolConfig(), 1000, "foobared", 2); + + // perform failover + doSegFaultMaster(pool); + + // perform failover once again + doSegFaultMaster(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 { - // jedis connection should be master - Jedis jedis = pool.getResource(); - assertEquals("PONG", jedis.ping()); - try { - jedis.debug(DebugParams.SEGFAULT()); - } catch (Exception e) { - } + private void doSegFaultMaster(JedisSentinelPool pool) + throws InterruptedException { + // jedis connection should be master + Jedis jedis = pool.getResource(); + assertEquals("PONG", jedis.ping()); - // wait for the sentinel to promote a master - // FIXME: we can query the sentinel and sleep - // right until the master is promoted - Thread.sleep(35000); + try { + jedis.debug(DebugParams.SEGFAULT()); + } catch (Exception e) { + } - jedis = pool.getResource(); - assertEquals("PONG", jedis.ping()); - assertEquals("foobared", jedis.configGet("requirepass").get(1)); - assertEquals(2, jedis.getDB().intValue()); + // wait for the sentinel to promote a master + // FIXME: we can query the sentinel and sleep + // right until the master is promoted + Thread.sleep(35000); + + jedis = pool.getResource(); + assertEquals("PONG", jedis.ping()); + assertEquals("foobared", jedis.configGet("requirepass").get(1)); + assertEquals(2, jedis.getDB().intValue()); } } diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java b/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java index 868527f..c2369c7 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java @@ -1,8 +1,8 @@ package redis.clients.jedis.tests; -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.assertFalse; -import static junit.framework.Assert.assertTrue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import java.util.List; import java.util.Map; diff --git a/src/test/java/redis/clients/jedis/tests/ShardedJedisPipelineTest.java b/src/test/java/redis/clients/jedis/tests/ShardedJedisPipelineTest.java index 7574f08..0f2e183 100644 --- a/src/test/java/redis/clients/jedis/tests/ShardedJedisPipelineTest.java +++ b/src/test/java/redis/clients/jedis/tests/ShardedJedisPipelineTest.java @@ -1,9 +1,9 @@ package redis.clients.jedis.tests; -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.assertNull; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import java.io.UnsupportedEncodingException; import java.util.ArrayList; @@ -25,104 +25,104 @@ import redis.clients.jedis.exceptions.JedisDataException; public class ShardedJedisPipelineTest { private static HostAndPortUtil.HostAndPort redis1 = HostAndPortUtil - .getRedisServers().get(0); + .getRedisServers().get(0); private static HostAndPortUtil.HostAndPort redis2 = HostAndPortUtil - .getRedisServers().get(1); + .getRedisServers().get(1); private ShardedJedis jedis; @Before public void setUp() throws Exception { - Jedis jedis = new Jedis(redis1.host, redis1.port); - jedis.auth("foobared"); - jedis.flushAll(); - jedis.disconnect(); - jedis = new Jedis(redis2.host, redis2.port); - jedis.auth("foobared"); - jedis.flushAll(); - jedis.disconnect(); + Jedis jedis = new Jedis(redis1.host, redis1.port); + jedis.auth("foobared"); + jedis.flushAll(); + jedis.disconnect(); + jedis = new Jedis(redis2.host, redis2.port); + jedis.auth("foobared"); + jedis.flushAll(); + jedis.disconnect(); - JedisShardInfo shardInfo1 = new JedisShardInfo(redis1.host, redis1.port); - JedisShardInfo shardInfo2 = new JedisShardInfo(redis2.host, redis2.port); - shardInfo1.setPassword("foobared"); - shardInfo2.setPassword("foobared"); - List shards = new ArrayList(); - shards.add(shardInfo1); - shards.add(shardInfo2); - this.jedis = new ShardedJedis(shards); + JedisShardInfo shardInfo1 = new JedisShardInfo(redis1.host, redis1.port); + JedisShardInfo shardInfo2 = new JedisShardInfo(redis2.host, redis2.port); + shardInfo1.setPassword("foobared"); + shardInfo2.setPassword("foobared"); + List shards = new ArrayList(); + shards.add(shardInfo1); + shards.add(shardInfo2); + this.jedis = new ShardedJedis(shards); } @Test public void pipeline() throws UnsupportedEncodingException { - ShardedJedisPipeline p = jedis.pipelined(); - p.set("foo", "bar"); - p.get("foo"); - List results = p.syncAndReturnAll(); + ShardedJedisPipeline p = jedis.pipelined(); + p.set("foo", "bar"); + p.get("foo"); + List 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"); - ShardedJedisPipeline p = jedis.pipelined(); - Response string = p.get("string"); - Response del = p.del("string"); - Response emptyString = 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(); + ShardedJedisPipeline p = jedis.pipelined(); + Response string = p.get("string"); + Response del = p.del("string"); + Response emptyString = 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(Long.valueOf(1), del.get()); - assertNull(emptyString.get()); - assertEquals("foo", list.get()); - assertEquals("bar", hash.get()); - assertEquals("foo", zset.get().iterator().next()); - assertEquals("foo", set.get()); - assertFalse(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(Long.valueOf(1), del.get()); + assertNull(emptyString.get()); + assertEquals("foo", list.get()); + assertEquals("bar", hash.get()); + assertEquals("foo", zset.get().iterator().next()); + assertEquals("foo", set.get()); + assertFalse(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(expected = JedisDataException.class) public void pipelineResponseWithinPipeline() { - jedis.set("string", "foo"); + jedis.set("string", "foo"); - ShardedJedisPipeline p = jedis.pipelined(); - Response string = p.get("string"); - string.get(); - p.sync(); + ShardedJedisPipeline p = jedis.pipelined(); + Response string = p.get("string"); + string.get(); + p.sync(); } @Test public void canRetrieveUnsetKey() { - ShardedJedisPipeline p = jedis.pipelined(); - Response shouldNotExist = p.get(UUID.randomUUID().toString()); - p.sync(); - assertNull(shouldNotExist.get()); + ShardedJedisPipeline p = jedis.pipelined(); + Response shouldNotExist = p.get(UUID.randomUUID().toString()); + p.sync(); + assertNull(shouldNotExist.get()); } } diff --git a/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolTest.java b/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolTest.java index 664e767..fbb078e 100644 --- a/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolTest.java +++ b/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolTest.java @@ -5,8 +5,7 @@ import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; -import org.apache.commons.pool.impl.GenericObjectPool; -import org.apache.commons.pool.impl.GenericObjectPool.Config; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -20,207 +19,215 @@ import redis.clients.jedis.tests.HostAndPortUtil.HostAndPort; public class ShardedJedisPoolTest extends Assert { private static HostAndPort redis1 = HostAndPortUtil.getRedisServers() - .get(0); + .get(0); private static HostAndPort redis2 = HostAndPortUtil.getRedisServers() - .get(1); + .get(1); private List shards; @Before public void startUp() { - shards = new ArrayList(); - shards.add(new JedisShardInfo(redis1.host, redis1.port)); - shards.add(new JedisShardInfo(redis2.host, redis2.port)); - shards.get(0).setPassword("foobared"); - shards.get(1).setPassword("foobared"); - Jedis j = new Jedis(shards.get(0)); - j.connect(); - j.flushAll(); - j.disconnect(); - j = new Jedis(shards.get(1)); - j.connect(); - j.flushAll(); - j.disconnect(); + shards = new ArrayList(); + shards.add(new JedisShardInfo(redis1.host, redis1.port)); + shards.add(new JedisShardInfo(redis2.host, redis2.port)); + shards.get(0).setPassword("foobared"); + shards.get(1).setPassword("foobared"); + Jedis j = new Jedis(shards.get(0)); + j.connect(); + j.flushAll(); + j.disconnect(); + j = new Jedis(shards.get(1)); + j.connect(); + j.flushAll(); + j.disconnect(); } @Test public void checkConnections() { - ShardedJedisPool pool = new ShardedJedisPool(new Config(), shards); - ShardedJedis jedis = pool.getResource(); - jedis.set("foo", "bar"); - assertEquals("bar", jedis.get("foo")); - pool.returnResource(jedis); - pool.destroy(); + ShardedJedisPool pool = new ShardedJedisPool( + new GenericObjectPoolConfig(), shards); + ShardedJedis jedis = pool.getResource(); + jedis.set("foo", "bar"); + assertEquals("bar", jedis.get("foo")); + pool.returnResource(jedis); + pool.destroy(); } @Test public void checkConnectionWithDefaultPort() { - ShardedJedisPool pool = new ShardedJedisPool(new Config(), shards); - ShardedJedis jedis = pool.getResource(); - jedis.set("foo", "bar"); - assertEquals("bar", jedis.get("foo")); - pool.returnResource(jedis); - pool.destroy(); + ShardedJedisPool pool = new ShardedJedisPool( + new GenericObjectPoolConfig(), shards); + ShardedJedis jedis = pool.getResource(); + jedis.set("foo", "bar"); + assertEquals("bar", jedis.get("foo")); + pool.returnResource(jedis); + pool.destroy(); } @Test public void checkJedisIsReusedWhenReturned() { - ShardedJedisPool pool = new ShardedJedisPool(new Config(), shards); - ShardedJedis jedis = pool.getResource(); - jedis.set("foo", "0"); - pool.returnResource(jedis); + ShardedJedisPool pool = new ShardedJedisPool( + new GenericObjectPoolConfig(), shards); + ShardedJedis jedis = pool.getResource(); + jedis.set("foo", "0"); + pool.returnResource(jedis); - jedis = pool.getResource(); - jedis.incr("foo"); - pool.returnResource(jedis); - pool.destroy(); + jedis = pool.getResource(); + jedis.incr("foo"); + pool.returnResource(jedis); + pool.destroy(); } @Test public void checkPoolRepairedWhenJedisIsBroken() { - ShardedJedisPool pool = new ShardedJedisPool(new Config(), shards); - ShardedJedis jedis = pool.getResource(); - jedis.disconnect(); - pool.returnBrokenResource(jedis); + ShardedJedisPool pool = new ShardedJedisPool( + new GenericObjectPoolConfig(), shards); + ShardedJedis jedis = pool.getResource(); + jedis.disconnect(); + pool.returnBrokenResource(jedis); - jedis = pool.getResource(); - jedis.incr("foo"); - pool.returnResource(jedis); - pool.destroy(); + jedis = pool.getResource(); + jedis.incr("foo"); + pool.returnResource(jedis); + pool.destroy(); } @Test(expected = JedisConnectionException.class) public void checkPoolOverflow() { - Config config = new Config(); - config.maxActive = 1; - config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL; + GenericObjectPoolConfig config = new GenericObjectPoolConfig(); + config.setMaxTotal(1); + config.setBlockWhenExhausted(false); + + ShardedJedisPool pool = new ShardedJedisPool(config, shards); - ShardedJedisPool pool = new ShardedJedisPool(config, shards); + ShardedJedis jedis = pool.getResource(); + jedis.set("foo", "0"); - ShardedJedis jedis = pool.getResource(); - jedis.set("foo", "0"); - - ShardedJedis newJedis = pool.getResource(); - newJedis.incr("foo"); + ShardedJedis newJedis = pool.getResource(); + newJedis.incr("foo"); } @Test public void shouldNotShareInstances() { - Config config = new Config(); - config.maxActive = 2; - config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL; + GenericObjectPoolConfig config = new GenericObjectPoolConfig(); + config.setMaxTotal(2); - ShardedJedisPool pool = new ShardedJedisPool(config, shards); + ShardedJedisPool pool = new ShardedJedisPool(config, shards); - ShardedJedis j1 = pool.getResource(); - ShardedJedis j2 = pool.getResource(); + ShardedJedis j1 = pool.getResource(); + ShardedJedis j2 = pool.getResource(); - assertNotSame(j1.getShard("foo"), j2.getShard("foo")); + assertNotSame(j1.getShard("foo"), j2.getShard("foo")); } @Test public void checkFailedJedisServer() { - ShardedJedisPool pool = new ShardedJedisPool(new Config(), shards); - ShardedJedis jedis = pool.getResource(); - jedis.incr("foo"); - pool.returnResource(jedis); - pool.destroy(); + ShardedJedisPool pool = new ShardedJedisPool( + new GenericObjectPoolConfig(), shards); + ShardedJedis jedis = pool.getResource(); + jedis.incr("foo"); + pool.returnResource(jedis); + pool.destroy(); } @Test public void shouldReturnActiveShardsWhenOneGoesOffline() { - Config redisConfig = new Config(); - redisConfig.testOnBorrow = false; - ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards); - ShardedJedis jedis = pool.getResource(); - // fill the shards - for (int i = 0; i < 1000; i++) { - jedis.set("a-test-" + i, "0"); - } - pool.returnResource(jedis); - // check quantity for each shard - Jedis j = new Jedis(shards.get(0)); - j.connect(); - Long c1 = j.dbSize(); - j.disconnect(); - j = new Jedis(shards.get(1)); - j.connect(); - Long c2 = j.dbSize(); - j.disconnect(); - // shutdown shard 2 and check thay the pool returns an instance with c1 - // items on one shard - // alter shard 1 and recreate pool - pool.destroy(); - shards.set(1, new JedisShardInfo("nohost", 1234)); - pool = new ShardedJedisPool(redisConfig, shards); - jedis = pool.getResource(); - Long actual = Long.valueOf(0); - Long fails = Long.valueOf(0); - for (int i = 0; i < 1000; i++) { - try { - jedis.get("a-test-" + i); - actual++; - } catch (RuntimeException e) { - fails++; - } - } - pool.returnResource(jedis); - pool.destroy(); - assertEquals(actual, c1); - assertEquals(fails, c2); + GenericObjectPoolConfig redisConfig = new GenericObjectPoolConfig(); + redisConfig.setTestOnBorrow(false); + ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards); + ShardedJedis jedis = pool.getResource(); + // fill the shards + for (int i = 0; i < 1000; i++) { + jedis.set("a-test-" + i, "0"); + } + pool.returnResource(jedis); + // check quantity for each shard + Jedis j = new Jedis(shards.get(0)); + j.connect(); + Long c1 = j.dbSize(); + j.disconnect(); + j = new Jedis(shards.get(1)); + j.connect(); + Long c2 = j.dbSize(); + j.disconnect(); + // shutdown shard 2 and check thay the pool returns an instance with c1 + // items on one shard + // alter shard 1 and recreate pool + pool.destroy(); + shards.set(1, new JedisShardInfo("nohost", 1234)); + pool = new ShardedJedisPool(redisConfig, shards); + jedis = pool.getResource(); + Long actual = Long.valueOf(0); + Long fails = Long.valueOf(0); + for (int i = 0; i < 1000; i++) { + try { + jedis.get("a-test-" + i); + actual++; + } catch (RuntimeException e) { + fails++; + } + } + pool.returnResource(jedis); + pool.destroy(); + assertEquals(actual, c1); + assertEquals(fails, c2); } - + @Test public void startWithUrlString() { Jedis j = new Jedis("localhost", 6380); j.auth("foobared"); j.set("foo", "bar"); - + j = new Jedis("localhost", 6379); j.auth("foobared"); j.set("foo", "bar"); - + List shards = new ArrayList(); shards.add(new JedisShardInfo("redis://:foobared@localhost:6380")); shards.add(new JedisShardInfo("redis://:foobared@localhost:6379")); - - Config redisConfig = new Config(); + + GenericObjectPoolConfig redisConfig = new GenericObjectPoolConfig(); ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards); - - Jedis[] jedises = pool.getResource().getAllShards().toArray(new Jedis[2]); - + + Jedis[] jedises = pool.getResource().getAllShards() + .toArray(new Jedis[2]); + Jedis jedis = jedises[0]; assertEquals("PONG", jedis.ping()); assertEquals("bar", jedis.get("foo")); - + jedis = jedises[1]; assertEquals("PONG", jedis.ping()); assertEquals("bar", jedis.get("foo")); } - + @Test public void startWithUrl() throws URISyntaxException { Jedis j = new Jedis("localhost", 6380); j.auth("foobared"); j.set("foo", "bar"); - + j = new Jedis("localhost", 6379); j.auth("foobared"); j.set("foo", "bar"); - + List shards = new ArrayList(); - shards.add(new JedisShardInfo(new URI("redis://:foobared@localhost:6380"))); - shards.add(new JedisShardInfo(new URI("redis://:foobared@localhost:6379"))); - - Config redisConfig = new Config(); + shards.add(new JedisShardInfo(new URI( + "redis://:foobared@localhost:6380"))); + shards.add(new JedisShardInfo(new URI( + "redis://:foobared@localhost:6379"))); + + GenericObjectPoolConfig redisConfig = new GenericObjectPoolConfig(); ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards); - - Jedis[] jedises = pool.getResource().getAllShards().toArray(new Jedis[2]); - + + Jedis[] jedises = pool.getResource().getAllShards() + .toArray(new Jedis[2]); + Jedis jedis = jedises[0]; assertEquals("PONG", jedis.ping()); assertEquals("bar", jedis.get("foo")); - + jedis = jedises[1]; assertEquals("PONG", jedis.ping()); assertEquals("bar", jedis.get("foo")); diff --git a/src/test/java/redis/clients/jedis/tests/benchmark/PoolBenchmark.java b/src/test/java/redis/clients/jedis/tests/benchmark/PoolBenchmark.java index ae1ffc3..224f004 100644 --- a/src/test/java/redis/clients/jedis/tests/benchmark/PoolBenchmark.java +++ b/src/test/java/redis/clients/jedis/tests/benchmark/PoolBenchmark.java @@ -4,7 +4,7 @@ import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; -import org.apache.commons.pool.impl.GenericObjectPool.Config; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; @@ -16,48 +16,48 @@ public class PoolBenchmark { private static final int TOTAL_OPERATIONS = 100000; public static void main(String[] args) throws Exception { - Jedis j = new Jedis(hnp.host, hnp.port); - j.connect(); - j.auth("foobared"); - j.flushAll(); - j.quit(); - j.disconnect(); - long t = System.currentTimeMillis(); - // withoutPool(); - withPool(); - long elapsed = System.currentTimeMillis() - t; - System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops"); + Jedis j = new Jedis(hnp.host, hnp.port); + j.connect(); + j.auth("foobared"); + j.flushAll(); + j.quit(); + j.disconnect(); + long t = System.currentTimeMillis(); + // withoutPool(); + withPool(); + long elapsed = System.currentTimeMillis() - t; + System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops"); } private static void withPool() throws Exception { - final JedisPool pool = new JedisPool(new Config(), hnp.host, hnp.port, - 2000, "foobared"); - List tds = new ArrayList(); + final JedisPool pool = new JedisPool(new GenericObjectPoolConfig(), + hnp.host, hnp.port, 2000, "foobared"); + List tds = new ArrayList(); - final AtomicInteger ind = new AtomicInteger(); - for (int i = 0; i < 50; i++) { - Thread hj = new Thread(new Runnable() { - public void run() { - for (int i = 0; (i = ind.getAndIncrement()) < TOTAL_OPERATIONS;) { - try { - Jedis j = pool.getResource(); - final String key = "foo" + i; - j.set(key, key); - j.get(key); - pool.returnResource(j); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - }); - tds.add(hj); - hj.start(); - } + final AtomicInteger ind = new AtomicInteger(); + for (int i = 0; i < 50; i++) { + Thread hj = new Thread(new Runnable() { + public void run() { + for (int i = 0; (i = ind.getAndIncrement()) < TOTAL_OPERATIONS;) { + try { + Jedis j = pool.getResource(); + final String key = "foo" + i; + j.set(key, key); + j.get(key); + pool.returnResource(j); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + }); + tds.add(hj); + hj.start(); + } - for (Thread t : tds) - t.join(); + for (Thread t : tds) + t.join(); - pool.destroy(); + pool.destroy(); } } \ No newline at end of file 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 f0ee6bf..b21d739 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java @@ -299,11 +299,8 @@ public class AllKindOfValuesCommandsTest extends JedisCommandTestBase { @Test public void ttl() { - // This is supposed to return -2 according to - // http://redis.io/commands/ttl - // and needs to be fixed in Redis. long ttl = jedis.ttl("foo"); - assertEquals(-1, ttl); + assertEquals(-2, ttl); jedis.set("foo", "bar"); ttl = jedis.ttl("foo"); @@ -313,13 +310,9 @@ public class AllKindOfValuesCommandsTest extends JedisCommandTestBase { ttl = jedis.ttl("foo"); assertTrue(ttl >= 0 && ttl <= 20); - // This is supposed to return -2 according to - // http://redis.io/commands/ttl - // and needs to be fixed in Redis. - // Binary long bttl = jedis.ttl(bfoo); - assertEquals(-1, bttl); + assertEquals(-2, bttl); jedis.set(bfoo, bbar); bttl = jedis.ttl(bfoo); @@ -499,7 +492,7 @@ public class AllKindOfValuesCommandsTest extends JedisCommandTestBase { @Test public void pttl() { long pttl = jedis.pttl("foo"); - assertEquals(-1, pttl); + assertEquals(-2, pttl); jedis.set("foo", "bar"); pttl = jedis.pttl("foo"); 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 5e03270..b3f6a7e 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java @@ -11,11 +11,10 @@ import org.junit.Before; import org.junit.Test; import redis.clients.jedis.Jedis; -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.Protocol.Keyword; import redis.clients.jedis.exceptions.JedisDataException; public class TransactionCommandsTest extends JedisCommandTestBase { @@ -30,269 +29,269 @@ public class TransactionCommandsTest extends JedisCommandTestBase { @Before public void setUp() throws Exception { - super.setUp(); + super.setUp(); - nj = new Jedis(hnp.host, hnp.port, 500); - nj.connect(); - nj.auth("foobared"); - nj.flushAll(); + nj = new Jedis(hnp.host, hnp.port, 500); + nj.connect(); + nj.auth("foobared"); + nj.flushAll(); } @Test public void multi() { - Transaction trans = jedis.multi(); + Transaction trans = jedis.multi(); - trans.sadd("foo", "a"); - trans.sadd("foo", "b"); - trans.scard("foo"); + trans.sadd("foo", "a"); + trans.sadd("foo", "b"); + trans.scard("foo"); - List response = trans.exec(); + List response = trans.exec(); - List expected = new ArrayList(); - expected.add(1L); - expected.add(1L); - expected.add(2L); - assertEquals(expected, response); + List expected = new ArrayList(); + expected.add(1L); + expected.add(1L); + expected.add(2L); + assertEquals(expected, response); - // Binary - trans = jedis.multi(); + // Binary + trans = jedis.multi(); - trans.sadd(bfoo, ba); - trans.sadd(bfoo, bb); - trans.scard(bfoo); + trans.sadd(bfoo, ba); + trans.sadd(bfoo, bb); + trans.scard(bfoo); - response = trans.exec(); + response = trans.exec(); - expected = new ArrayList(); - expected.add(1L); - expected.add(1L); - expected.add(2L); - assertEquals(expected, response); + expected = new ArrayList(); + expected.add(1L); + expected.add(1L); + expected.add(2L); + assertEquals(expected, response); } @Test public void multiBlock() { - List response = jedis.multi(new TransactionBlock() { - @Override - public void execute() { - sadd("foo", "a"); - sadd("foo", "b"); - scard("foo"); - } - }); + 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); + 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); - } - }); + // 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); + expected = new ArrayList(); + expected.add(1L); + expected.add(1L); + expected.add(2L); + assertEquals(expected, response); } @Test public void watch() throws UnknownHostException, IOException { - jedis.watch("mykey", "somekey"); - Transaction t = jedis.multi(); + jedis.watch("mykey", "somekey"); + Transaction t = jedis.multi(); - nj.connect(); - nj.auth("foobared"); - nj.set("mykey", "bar"); - nj.disconnect(); + nj.connect(); + nj.auth("foobared"); + nj.set("mykey", "bar"); + nj.disconnect(); - t.set("mykey", "foo"); - List resp = t.exec(); - assertEquals(null, resp); - assertEquals("bar", jedis.get("mykey")); + t.set("mykey", "foo"); + List resp = t.exec(); + assertEquals(null, resp); + assertEquals("bar", jedis.get("mykey")); - // Binary - jedis.watch(bmykey, "foobar".getBytes()); - t = jedis.multi(); + // Binary + jedis.watch(bmykey, "foobar".getBytes()); + t = jedis.multi(); - nj.connect(); - nj.auth("foobared"); - nj.set(bmykey, bbar); - nj.disconnect(); + nj.connect(); + nj.auth("foobared"); + nj.set(bmykey, bbar); + nj.disconnect(); - t.set(bmykey, bfoo); - resp = t.exec(); - assertEquals(null, resp); - assertTrue(Arrays.equals(bbar, jedis.get(bmykey))); + t.set(bmykey, bfoo); + resp = t.exec(); + assertEquals(null, resp); + assertTrue(Arrays.equals(bbar, jedis.get(bmykey))); } @Test public void unwatch() throws UnknownHostException, IOException { - jedis.watch("mykey"); - String val = jedis.get("mykey"); - val = "foo"; - String status = jedis.unwatch(); - assertEquals("OK", status); - Transaction t = jedis.multi(); + jedis.watch("mykey"); + String val = jedis.get("mykey"); + val = "foo"; + String status = jedis.unwatch(); + assertEquals("OK", status); + Transaction t = jedis.multi(); - nj.connect(); - nj.auth("foobared"); - nj.set("mykey", "bar"); - nj.disconnect(); + nj.connect(); + nj.auth("foobared"); + nj.set("mykey", "bar"); + nj.disconnect(); - t.set("mykey", val); - List resp = t.exec(); - assertEquals(1, resp.size()); - assertEquals("OK", resp.get(0)); + t.set("mykey", val); + List resp = t.exec(); + assertEquals(1, resp.size()); + assertEquals("OK", resp.get(0)); - // Binary - jedis.watch(bmykey); - byte[] bval = jedis.get(bmykey); - bval = bfoo; - status = jedis.unwatch(); - assertEquals(Keyword.OK.name(), status); - t = jedis.multi(); + // Binary + jedis.watch(bmykey); + byte[] bval = jedis.get(bmykey); + bval = bfoo; + status = jedis.unwatch(); + assertEquals(Keyword.OK.name(), status); + t = jedis.multi(); - nj.connect(); - nj.auth("foobared"); - nj.set(bmykey, bbar); - nj.disconnect(); + nj.connect(); + nj.auth("foobared"); + nj.set(bmykey, bbar); + nj.disconnect(); - t.set(bmykey, bval); - resp = t.exec(); - assertEquals(1, resp.size()); - assertEquals("OK", resp.get(0)); + t.set(bmykey, bval); + resp = t.exec(); + assertEquals(1, resp.size()); + assertEquals("OK", resp.get(0)); } @Test(expected = JedisDataException.class) public void validateWhenInMulti() { - jedis.multi(); - jedis.ping(); + jedis.multi(); + jedis.ping(); } @Test public void discard() { - Transaction t = jedis.multi(); - String status = t.discard(); - assertEquals("OK", status); + Transaction t = jedis.multi(); + String status = t.discard(); + assertEquals("OK", status); } @Test public void transactionResponse() { - 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"); - Transaction t = jedis.multi(); - Response string = t.get("string"); - Response list = t.lpop("list"); - Response hash = t.hget("hash", "foo"); - Response> zset = t.zrange("zset", 0, -1); - Response set = t.spop("set"); - t.exec(); + Transaction t = jedis.multi(); + Response string = t.get("string"); + Response list = t.lpop("list"); + Response hash = t.hget("hash", "foo"); + Response> zset = t.zrange("zset", 0, -1); + Response set = t.spop("set"); + t.exec(); - assertEquals("foo", string.get()); - assertEquals("foo", list.get()); - assertEquals("bar", hash.get()); - assertEquals("foo", zset.get().iterator().next()); - assertEquals("foo", set.get()); + assertEquals("foo", string.get()); + assertEquals("foo", list.get()); + assertEquals("bar", hash.get()); + assertEquals("foo", zset.get().iterator().next()); + assertEquals("foo", set.get()); } @Test public void transactionResponseBinary() { - 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"); - Transaction t = jedis.multi(); - Response string = t.get("string".getBytes()); - Response list = t.lpop("list".getBytes()); - Response hash = t.hget("hash".getBytes(), "foo".getBytes()); - Response> zset = t.zrange("zset".getBytes(), 0, -1); - Response set = t.spop("set".getBytes()); - t.exec(); + Transaction t = jedis.multi(); + Response string = t.get("string".getBytes()); + Response list = t.lpop("list".getBytes()); + Response hash = t.hget("hash".getBytes(), "foo".getBytes()); + Response> zset = t.zrange("zset".getBytes(), 0, -1); + Response set = t.spop("set".getBytes()); + t.exec(); - assertArrayEquals("foo".getBytes(), string.get()); - assertArrayEquals("foo".getBytes(), list.get()); - assertArrayEquals("bar".getBytes(), hash.get()); - assertArrayEquals("foo".getBytes(), zset.get().iterator().next()); - assertArrayEquals("foo".getBytes(), set.get()); + assertArrayEquals("foo".getBytes(), string.get()); + assertArrayEquals("foo".getBytes(), list.get()); + assertArrayEquals("bar".getBytes(), hash.get()); + assertArrayEquals("foo".getBytes(), zset.get().iterator().next()); + assertArrayEquals("foo".getBytes(), set.get()); } @Test(expected = JedisDataException.class) public void transactionResponseWithinPipeline() { - jedis.set("string", "foo"); + jedis.set("string", "foo"); - Transaction t = jedis.multi(); - Response string = t.get("string"); - string.get(); - t.exec(); + Transaction t = jedis.multi(); + Response string = t.get("string"); + string.get(); + t.exec(); } - + @Test public void transactionResponseWithError() { - Transaction t = jedis.multi(); - t.set("foo", "bar"); - Response> error = t.smembers("foo"); - Response r = t.get("foo"); - List l = t.exec(); - assertEquals(JedisDataException.class, l.get(1).getClass()); - try{ - error.get(); - fail("We expect exception here!"); - }catch(JedisDataException e){ - //that is fine we should be here - } - assertEquals(r.get(), "bar"); + Transaction t = jedis.multi(); + t.set("foo", "bar"); + Response> error = t.smembers("foo"); + Response r = t.get("foo"); + List l = t.exec(); + assertEquals(JedisDataException.class, l.get(1).getClass()); + try { + error.get(); + fail("We expect exception here!"); + } catch (JedisDataException e) { + // that is fine we should be here + } + assertEquals(r.get(), "bar"); } - + @Test public void execGetResponse() { - Transaction t = jedis.multi(); + Transaction t = jedis.multi(); - t.set("foo", "bar"); - t.smembers("foo"); - t.get("foo"); + t.set("foo", "bar"); + t.smembers("foo"); + t.get("foo"); - List> lr = t.execGetResponse(); - try{ - lr.get(1).get(); - fail("We expect exception here!"); - }catch(JedisDataException e){ - //that is fine we should be here - } - assertEquals("bar", lr.get(2).get()); + List> lr = t.execGetResponse(); + try { + lr.get(1).get(); + fail("We expect exception here!"); + } catch (JedisDataException e) { + // that is fine we should be here + } + assertEquals("bar", lr.get(2).get()); } - + @Test public void select() { - jedis.select(1); - jedis.set("foo", "bar"); - jedis.watch("foo"); - Transaction t = jedis.multi(); - t.select(0); - t.set("bar", "foo"); - - Jedis jedis2 = createJedis(); - jedis2.select(1); - jedis2.set("foo", "bar2"); - - List results = t.exec(); - - assertNull(results); + jedis.select(1); + jedis.set("foo", "bar"); + jedis.watch("foo"); + Transaction t = jedis.multi(); + t.select(0); + t.set("bar", "foo"); + + Jedis jedis2 = createJedis(); + jedis2.select(1); + jedis2.set("foo", "bar2"); + + List results = t.exec(); + + assertNull(results); } } \ No newline at end of file From 7cd4dd43952f9cba850c9bb499dda43b0fbfe9a6 Mon Sep 17 00:00:00 2001 From: Mathieu Boniface Date: Sat, 30 Nov 2013 19:02:40 +0100 Subject: [PATCH 07/70] Updated maven dependency template Jedis version to 2.2.1 (latest) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3b2a7db..455c273 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ Or use it as a maven dependency: redis.clients jedis - 2.0.0 + 2.2.1 jar compile From 3876bb04e3aa43d23dd633214c9c54ae2b8c1c70 Mon Sep 17 00:00:00 2001 From: Tague Griffith Date: Sun, 1 Dec 2013 14:56:23 -0800 Subject: [PATCH 08/70] Update Gradle build to use Apache Commons Pool 2.0. --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index eb73a5c..30af731 100644 --- a/build.gradle +++ b/build.gradle @@ -12,7 +12,7 @@ repositories { dependencies { testCompile 'junit:junit:4.11' - compile 'commons-pool:commons-pool:1.6' + compile 'org.apache.commons:commons-pool2:2.0' } From 15891c411734e78dafe61262f7052b0d1936e286 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Mon, 2 Dec 2013 22:11:52 +0900 Subject: [PATCH 09/70] make jedis unit tests pass to Redis 2.8.1 * increase sentinel instance to test JedisSentinelTest ** clear() called, slave promoted to master (slave of no one), New Sentinel force to restore it (demote) -> slave is not reusable * ipv6 applied at Redis 2.8 -> localhost / 127.0.0.1 / ::1 is now all same * Makefile: sleep some time for launch each sentinel (workaround to sentinel's issue) ** issue to sentinel leader vote: https://github.com/antirez/redis/issues/1419 *** sentinel may confused to vote with sentinels launched approximately same time --- Makefile | 79 ++++++------------- pom.xml | 6 +- .../java/redis/clients/jedis/HostAndPort.java | 21 +++-- .../clients/jedis/tests/HostAndPortUtil.java | 11 ++- .../jedis/tests/JedisSentinelTest.java | 19 ++--- 5 files changed, 58 insertions(+), 78 deletions(-) diff --git a/Makefile b/Makefile index 30a8b04..21eaa2b 100644 --- a/Makefile +++ b/Makefile @@ -50,6 +50,17 @@ save "" appendonly no endef +define REDIS6_CONF +daemonize yes +port 6384 +requirepass foobared +masterauth foobared +pidfile /tmp/redis6.pid +logfile /tmp/redis6.log +save "" +appendonly no +endef + define REDIS_SENTINEL1 port 26379 daemonize yes @@ -91,6 +102,7 @@ export REDIS2_CONF export REDIS3_CONF export REDIS4_CONF export REDIS5_CONF +export REDIS6_CONF export REDIS_SENTINEL1 export REDIS_SENTINEL2 export REDIS_SENTINEL3 @@ -101,8 +113,11 @@ start: echo "$$REDIS3_CONF" | redis-server - echo "$$REDIS4_CONF" | redis-server - echo "$$REDIS5_CONF" | redis-server - + echo "$$REDIS6_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 stop: @@ -112,76 +127,26 @@ stop: 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/sentinel1.pid` kill `cat /tmp/sentinel2.pid` kill `cat /tmp/sentinel3.pid` test: - echo "$$REDIS1_CONF" | redis-server - - echo "$$REDIS2_CONF" | redis-server - - echo "$$REDIS3_CONF" | redis-server - - echo "$$REDIS4_CONF" | redis-server - - echo "$$REDIS5_CONF" | redis-server - - echo "$$REDIS_SENTINEL1" | redis-server - --sentinel - echo "$$REDIS_SENTINEL2" | redis-server - --sentinel - echo "$$REDIS_SENTINEL3" | redis-server - --sentinel - + make start mvn clean compile test - - 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/sentinel1.pid` - kill `cat /tmp/sentinel2.pid` - kill `cat /tmp/sentinel3.pid` + make stop deploy: - echo "$$REDIS1_CONF" | redis-server - - echo "$$REDIS2_CONF" | redis-server - - echo "$$REDIS3_CONF" | redis-server - - echo "$$REDIS4_CONF" | redis-server - - echo "$$REDIS5_CONF" | redis-server - - echo "$$REDIS_SENTINEL1" | redis-server - --sentinel - echo "$$REDIS_SENTINEL2" | redis-server - --sentinel - echo "$$REDIS_SENTINEL3" | redis-server - --sentinel - + make start mvn clean deploy - - 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/sentinel1.pid` - kill `cat /tmp/sentinel2.pid` - kill `cat /tmp/sentinel3.pid` + make stop release: - echo "$$REDIS1_CONF" | redis-server - - echo "$$REDIS2_CONF" | redis-server - - echo "$$REDIS3_CONF" | redis-server - - echo "$$REDIS4_CONF" | redis-server - - echo "$$REDIS5_CONF" | redis-server - - echo "$$REDIS_SENTINEL1" | redis-server - --sentinel - echo "$$REDIS_SENTINEL2" | redis-server - --sentinel - echo "$$REDIS_SENTINEL3" | redis-server - --sentinel - + make start mvn release:clean mvn release:prepare mvn release:perform - - 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/sentinel1.pid` - kill `cat /tmp/sentinel2.pid` - kill `cat /tmp/sentinel3.pid` + make stop .PHONY: test diff --git a/pom.xml b/pom.xml index 8649428..9409ec9 100644 --- a/pom.xml +++ b/pom.xml @@ -45,9 +45,9 @@ - localhost:6379,localhost:6380,localhost:6381,localhost:6382,localhost:6383 - localhost:26379,localhost:26380 - github + localhost:6379,localhost:6380,localhost:6381,localhost:6382,localhost:6383,localhost:6384 + localhost:26379,localhost:26380,localhost:26381 + github diff --git a/src/main/java/redis/clients/jedis/HostAndPort.java b/src/main/java/redis/clients/jedis/HostAndPort.java index 488eac3..33d1467 100644 --- a/src/main/java/redis/clients/jedis/HostAndPort.java +++ b/src/main/java/redis/clients/jedis/HostAndPort.java @@ -1,6 +1,8 @@ package redis.clients.jedis; public class HostAndPort { + public static final String LOCALHOST_STR = "localhost"; + private String host; private int port; @@ -22,11 +24,11 @@ public class HostAndPort { if (obj instanceof HostAndPort) { HostAndPort hp = (HostAndPort) obj; - // localhost and 127.0.0.1 is same - return port == hp.port && - (host.equals(hp.host) || - (host.equals("localhost") && hp.host.equals("127.0.0.1")) || - (host.equals("127.0.0.1") && hp.host.equals("localhost")) ); + String thisHost = convertHost(host); + String hpHost = convertHost(hp.host); + return port == hp.port && + thisHost.equals(hpHost); + } return false; @@ -36,4 +38,13 @@ public class HostAndPort { 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; + + return host; + } } diff --git a/src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java b/src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java index 03e421e..be64c53 100644 --- a/src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java +++ b/src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java @@ -27,14 +27,17 @@ public class HostAndPortUtil { HostAndPort defaulthnp5 = new HostAndPort("localhost", Protocol.DEFAULT_PORT + 4); redisHostAndPortList.add(defaulthnp5); - HostAndPort defaulthnp6 = new HostAndPort("localhost", Protocol.DEFAULT_SENTINEL_PORT); - sentinelHostAndPortList.add(defaulthnp6); + HostAndPort defaulthnp6 = new HostAndPort("localhost", Protocol.DEFAULT_PORT + 5); + redisHostAndPortList.add(defaulthnp6); - HostAndPort defaulthnp7 = new HostAndPort("localhost", Protocol.DEFAULT_SENTINEL_PORT + 1); + HostAndPort defaulthnp7 = new HostAndPort("localhost", Protocol.DEFAULT_SENTINEL_PORT); sentinelHostAndPortList.add(defaulthnp7); - HostAndPort defaulthnp8 = new HostAndPort("localhost", Protocol.DEFAULT_SENTINEL_PORT + 2); + 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); String envRedisHosts = System.getProperty("redis-hosts"); String envSentinelHosts = System.getProperty("sentinel-hosts"); diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java b/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java index 3e5cfdf..8912a1c 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java @@ -17,8 +17,8 @@ public class JedisSentinelTest extends JedisTestBase { protected static HostAndPort master = HostAndPortUtil.getRedisServers() .get(0); - protected static HostAndPort slave = HostAndPortUtil.getRedisServers().get( - 1); + protected static HostAndPort slave = HostAndPortUtil.getRedisServers() + .get(5); protected static HostAndPort sentinel = HostAndPortUtil .getSentinelServers().get(0); @@ -44,14 +44,14 @@ public class JedisSentinelTest extends JedisTestBase { @After public void clear() throws InterruptedException { - Jedis j = new Jedis("localhost", 6380); - j.auth("foobared"); - j.slaveofNoOne(); + // New Sentinel (after 2.8.1) + // when slave promoted to master (slave of no one), New Sentinel force to restore it (demote) + // so, promote(slaveof) slave to master has no effect, not same to old Sentinel's behavior } @Test public void sentinel() { - Jedis j = new Jedis("localhost", 26379); + Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort()); List> masters = j.sentinelMasters(); final String masterName = masters.get(0).get("name"); @@ -59,12 +59,13 @@ public class JedisSentinelTest extends JedisTestBase { List masterHostAndPort = j .sentinelGetMasterAddrByName(masterName); - assertEquals("127.0.0.1", masterHostAndPort.get(0)); - assertEquals("6379", masterHostAndPort.get(1)); + HostAndPort masterFromSentinel = new HostAndPort(masterHostAndPort.get(0), + Integer.parseInt(masterHostAndPort.get(1))); + assertEquals(master, masterFromSentinel); List> slaves = j.sentinelSlaves(masterName); assertTrue(slaves.size() > 0); - assertEquals("6379", 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)); From e7e2bfaedf6328151f7b516fd9b9ae68d263ebef Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Mon, 2 Dec 2013 09:53:40 -0500 Subject: [PATCH 10/70] Launch 3 nodes on ports 7379 to 7381 with cluster enabled. Add command CLUSTER NODES --- Makefile | 47 +++++ pom.xml | 1 + .../redis/clients/jedis/BinaryClient.java | 5 + src/main/java/redis/clients/jedis/Client.java | 8 + src/main/java/redis/clients/jedis/Jedis.java | 6 + .../java/redis/clients/jedis/Protocol.java | 4 +- .../clients/jedis/tests/HostAndPortUtil.java | 161 ++++++++++-------- .../tests/commands/ClusterCommandsTest.java | 41 +++++ 8 files changed, 203 insertions(+), 70 deletions(-) create mode 100644 src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java diff --git a/Makefile b/Makefile index 21eaa2b..e0189f2 100644 --- a/Makefile +++ b/Makefile @@ -61,6 +61,7 @@ save "" appendonly no endef +# SENTINELS define REDIS_SENTINEL1 port 26379 daemonize yes @@ -97,6 +98,40 @@ pidfile /tmp/sentinel3.pid logfile /tmp/sentinel3.log endef +# CLUSTER REDIS NODES +define REDIS_CLUSTER_NODE1_CONF +daemonize yes +port 7379 +pidfile /tmp/redis_cluster_node1.pid +logfile /tmp/redis_cluster_node1.log +save "" +appendonly no +cluster-enabled yes +cluster-config-file /tmp/redis_cluster_node1.conf +endef + +define REDIS_CLUSTER_NODE2_CONF +daemonize yes +port 7380 +pidfile /tmp/redis_cluster_node2.pid +logfile /tmp/redis_cluster_node2.log +save "" +appendonly no +cluster-enabled yes +cluster-config-file /tmp/redis_cluster_node2.conf +endef + +define REDIS_CLUSTER_NODE3_CONF +daemonize yes +port 7381 +pidfile /tmp/redis_cluster_node3.pid +logfile /tmp/redis_cluster_node3.log +save "" +appendonly no +cluster-enabled yes +cluster-config-file /tmp/redis_cluster_node3.conf +endef + export REDIS1_CONF export REDIS2_CONF export REDIS3_CONF @@ -106,6 +141,9 @@ export REDIS6_CONF export REDIS_SENTINEL1 export REDIS_SENTINEL2 export REDIS_SENTINEL3 +export REDIS_CLUSTER_NODE1_CONF +export REDIS_CLUSTER_NODE2_CONF +export REDIS_CLUSTER_NODE3_CONF start: echo "$$REDIS1_CONF" | redis-server - @@ -119,6 +157,9 @@ start: 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 + echo "$$REDIS_CLUSTER_NODE1_CONF" | redis-server - + echo "$$REDIS_CLUSTER_NODE2_CONF" | redis-server - + echo "$$REDIS_CLUSTER_NODE3_CONF" | redis-server - stop: kill `cat /tmp/redis1.pid` @@ -131,6 +172,12 @@ 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 + rm -f /tmp/redis_cluster_node1.conf + rm -f /tmp/redis_cluster_node2.conf + rm -f /tmp/redis_cluster_node3.conf test: make start diff --git a/pom.xml b/pom.xml index 9409ec9..f6575eb 100644 --- a/pom.xml +++ b/pom.xml @@ -47,6 +47,7 @@ localhost:6379,localhost:6380,localhost:6381,localhost:6382,localhost:6383,localhost:6384 localhost:26379,localhost:26380,localhost:26381 + localhost:7379,localhost:7380,localhost:7381 github diff --git a/src/main/java/redis/clients/jedis/BinaryClient.java b/src/main/java/redis/clients/jedis/BinaryClient.java index acb120b..1b9db49 100644 --- a/src/main/java/redis/clients/jedis/BinaryClient.java +++ b/src/main/java/redis/clients/jedis/BinaryClient.java @@ -1100,4 +1100,9 @@ public class BinaryClient extends Connection { public void hincrByFloat(final byte[] key, final byte[] field, double increment) { sendCommand(HINCRBYFLOAT, key, field, toByteArray(increment)); } + + public void cluster(final byte[]... args) { + sendCommand(CLUSTER, args); + } + } diff --git a/src/main/java/redis/clients/jedis/Client.java b/src/main/java/redis/clients/jedis/Client.java index 9c97e38..b726821 100644 --- a/src/main/java/redis/clients/jedis/Client.java +++ b/src/main/java/redis/clients/jedis/Client.java @@ -807,4 +807,12 @@ public class Client extends BinaryClient implements Commands { public void hincrByFloat(final String key, final String field, double increment) { hincrByFloat(SafeEncoder.encode(key), SafeEncoder.encode(field), increment); } + + public void cluster(final String... args) { + final byte[][] arg = new byte[args.length][]; + for (int i = 0; i < arg.length; i++) { + arg[i] = SafeEncoder.encode(args[i]); + } + cluster(arg); + } } diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index 23cfd3d..d2daca5 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -3076,4 +3076,10 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand String relpy = client.getBulkReply(); return (relpy != null ? new Double(relpy) : null); } + + public String clusterNodes() { + checkIsInMulti(); + client.cluster(Protocol.CLUSTER_NODES); + return client.getBulkReply(); + } } diff --git a/src/main/java/redis/clients/jedis/Protocol.java b/src/main/java/redis/clients/jedis/Protocol.java index f85c324..e4a9126 100644 --- a/src/main/java/redis/clients/jedis/Protocol.java +++ b/src/main/java/redis/clients/jedis/Protocol.java @@ -30,6 +30,8 @@ public final class Protocol { public static final String SENTINEL_RESET = "reset"; public static final String SENTINEL_SLAVES = "slaves"; + public static final String CLUSTER_NODES = "nodes"; + private Protocol() { // this prevent the class from instantiation } @@ -155,7 +157,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; + DUMP, RESTORE, PEXPIRE, PEXPIREAT, PTTL, INCRBYFLOAT, PSETEX, CLIENT, TIME, MIGRATE, HINCRBYFLOAT, CLUSTER; public final byte[] raw; diff --git a/src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java b/src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java index be64c53..c7be599 100644 --- a/src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java +++ b/src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java @@ -9,83 +9,106 @@ import redis.clients.jedis.Protocol; public class HostAndPortUtil { private static List redisHostAndPortList = new ArrayList(); private static List sentinelHostAndPortList = new ArrayList(); + 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); + HostAndPort defaulthnp1 = new HostAndPort("localhost", + Protocol.DEFAULT_PORT); + redisHostAndPortList.add(defaulthnp1); - String envRedisHosts = System.getProperty("redis-hosts"); - String envSentinelHosts = System.getProperty("sentinel-hosts"); - - redisHostAndPortList = parseHosts(envRedisHosts, redisHostAndPortList); - sentinelHostAndPortList = parseHosts(envSentinelHosts, sentinelHostAndPortList); + 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); + + clusterHostAndPortList.add(new HostAndPort("localhost", 7379)); + clusterHostAndPortList.add(new HostAndPort("localhost", 7380)); + clusterHostAndPortList.add(new HostAndPort("localhost", 7381)); + + String envRedisHosts = System.getProperty("redis-hosts"); + String envSentinelHosts = System.getProperty("sentinel-hosts"); + String envClusterHosts = System.getProperty("cluster-hosts"); + + redisHostAndPortList = parseHosts(envRedisHosts, redisHostAndPortList); + sentinelHostAndPortList = parseHosts(envSentinelHosts, + sentinelHostAndPortList); + clusterHostAndPortList = parseHosts(envClusterHosts, + clusterHostAndPortList); } - public static List parseHosts(String envHosts, List existingHostsAndPorts) { - - if (null != envHosts && 0 < envHosts.length()) { - - String[] hostDefs = envHosts.split(","); - - if (null != hostDefs && 2 <= hostDefs.length) { - - List envHostsAndPorts = new ArrayList(hostDefs.length); - - for (String hostDef : hostDefs) { - - String[] hostAndPort = hostDef.split(":"); - - if (null != hostAndPort && 2 == hostAndPort.length) { - String host = hostAndPort[0]; - int port = Protocol.DEFAULT_PORT; - - try { - port = Integer.parseInt(hostAndPort[1]); - } catch (final NumberFormatException nfe) { - } - - envHostsAndPorts.add(new HostAndPort(host, port)); - } - } - - return envHostsAndPorts; - } - } - - return existingHostsAndPorts; + public static List parseHosts(String envHosts, + List existingHostsAndPorts) { + + if (null != envHosts && 0 < envHosts.length()) { + + String[] hostDefs = envHosts.split(","); + + if (null != hostDefs && 2 <= hostDefs.length) { + + List envHostsAndPorts = new ArrayList( + hostDefs.length); + + for (String hostDef : hostDefs) { + + String[] hostAndPort = hostDef.split(":"); + + if (null != hostAndPort && 2 == hostAndPort.length) { + String host = hostAndPort[0]; + int port = Protocol.DEFAULT_PORT; + + try { + port = Integer.parseInt(hostAndPort[1]); + } catch (final NumberFormatException nfe) { + } + + envHostsAndPorts.add(new HostAndPort(host, port)); + } + } + + return envHostsAndPorts; + } + } + + return existingHostsAndPorts; } - + public static List getRedisServers() { - return redisHostAndPortList; - } - - public static List getSentinelServers() { - return sentinelHostAndPortList; + return redisHostAndPortList; } + public static List getSentinelServers() { + return sentinelHostAndPortList; + } + + public static List getClusterServers() { + return clusterHostAndPortList; + } } diff --git a/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java new file mode 100644 index 0000000..1599b02 --- /dev/null +++ b/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java @@ -0,0 +1,41 @@ +package redis.clients.jedis.tests.commands; + +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.tests.HostAndPortUtil; +import redis.clients.jedis.tests.JedisTestBase; + +public class ClusterCommandsTest extends JedisTestBase { + private Jedis node1; + private Jedis node2; + + @Before + public void setUp() throws Exception { + HostAndPort nodeInfo1 = HostAndPortUtil.getClusterServers().get(0); + HostAndPort nodeInfo2 = HostAndPortUtil.getClusterServers().get(1); + + node1 = new Jedis(nodeInfo1.getHost(), nodeInfo1.getPort()); + node1.connect(); + node1.flushAll(); + + node2 = new Jedis(nodeInfo2.getHost(), nodeInfo2.getPort()); + node2.connect(); + node2.flushAll(); + } + + @After + public void tearDown() { + node1.disconnect(); + node2.disconnect(); + } + + @Test + public void clusterNodes() { + String nodes = node1.clusterNodes(); + assertEquals(1, nodes.split("\n").length); + } +} \ No newline at end of file From 403f2b292cb9e3f4f1cf71c2f0e46d5d014d1dd2 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Mon, 2 Dec 2013 10:01:19 -0500 Subject: [PATCH 11/70] Add CLUSTER MEET command --- src/main/java/redis/clients/jedis/Client.java | 4 ++-- src/main/java/redis/clients/jedis/Jedis.java | 6 ++++++ src/main/java/redis/clients/jedis/Protocol.java | 1 + .../jedis/tests/commands/ClusterCommandsTest.java | 13 ++++++++++--- 4 files changed, 19 insertions(+), 5 deletions(-) diff --git a/src/main/java/redis/clients/jedis/Client.java b/src/main/java/redis/clients/jedis/Client.java index b726821..c4e131e 100644 --- a/src/main/java/redis/clients/jedis/Client.java +++ b/src/main/java/redis/clients/jedis/Client.java @@ -808,10 +808,10 @@ public class Client extends BinaryClient implements Commands { hincrByFloat(SafeEncoder.encode(key), SafeEncoder.encode(field), increment); } - public void cluster(final String... args) { + public void cluster(final Object... args) { final byte[][] arg = new byte[args.length][]; for (int i = 0; i < arg.length; i++) { - arg[i] = SafeEncoder.encode(args[i]); + arg[i] = SafeEncoder.encode(args[i].toString()); } cluster(arg); } diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index d2daca5..ef952a7 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -3082,4 +3082,10 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand client.cluster(Protocol.CLUSTER_NODES); return client.getBulkReply(); } + + public String clusterMeet(final String ip, final int port) { + checkIsInMulti(); + client.cluster(Protocol.CLUSTER_MEET, ip, port); + return client.getStatusCodeReply(); + } } diff --git a/src/main/java/redis/clients/jedis/Protocol.java b/src/main/java/redis/clients/jedis/Protocol.java index e4a9126..22479a5 100644 --- a/src/main/java/redis/clients/jedis/Protocol.java +++ b/src/main/java/redis/clients/jedis/Protocol.java @@ -31,6 +31,7 @@ public final class Protocol { public static final String SENTINEL_SLAVES = "slaves"; public static final String CLUSTER_NODES = "nodes"; + public static final String CLUSTER_MEET = "meet"; private Protocol() { // this prevent the class from instantiation 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 1599b02..0fe04f1 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java @@ -13,10 +13,11 @@ public class ClusterCommandsTest extends JedisTestBase { private Jedis node1; private Jedis node2; + private HostAndPort nodeInfo1 = HostAndPortUtil.getClusterServers().get(0); + private HostAndPort nodeInfo2 = HostAndPortUtil.getClusterServers().get(1); + @Before public void setUp() throws Exception { - HostAndPort nodeInfo1 = HostAndPortUtil.getClusterServers().get(0); - HostAndPort nodeInfo2 = HostAndPortUtil.getClusterServers().get(1); node1 = new Jedis(nodeInfo1.getHost(), nodeInfo1.getPort()); node1.connect(); @@ -36,6 +37,12 @@ public class ClusterCommandsTest extends JedisTestBase { @Test public void clusterNodes() { String nodes = node1.clusterNodes(); - assertEquals(1, nodes.split("\n").length); + assertTrue(nodes.split("\n").length > 0); + } + + @Test + public void clusterMeet() { + String status = node1.clusterMeet("127.0.0.1", nodeInfo2.getPort()); + assertEquals("OK", status); } } \ No newline at end of file From dde278152f391238fb12bacbdd5ed609a06e717f Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Mon, 2 Dec 2013 11:36:55 -0500 Subject: [PATCH 12/70] Add CLUSTER ADDSLOTS and CLUSTER DELSLOTS commands --- src/main/java/redis/clients/jedis/Client.java | 26 +++++++++++++++---- src/main/java/redis/clients/jedis/Jedis.java | 14 +++++++++- .../java/redis/clients/jedis/Protocol.java | 2 ++ .../tests/commands/ClusterCommandsTest.java | 13 ++++++++++ 4 files changed, 49 insertions(+), 6 deletions(-) diff --git a/src/main/java/redis/clients/jedis/Client.java b/src/main/java/redis/clients/jedis/Client.java index c4e131e..90621f3 100644 --- a/src/main/java/redis/clients/jedis/Client.java +++ b/src/main/java/redis/clients/jedis/Client.java @@ -808,11 +808,27 @@ public class Client extends BinaryClient implements Commands { hincrByFloat(SafeEncoder.encode(key), SafeEncoder.encode(field), increment); } - public void cluster(final Object... args) { - final byte[][] arg = new byte[args.length][]; - for (int i = 0; i < arg.length; i++) { - arg[i] = SafeEncoder.encode(args[i].toString()); + public void cluster(final String subcommand, final int... args) { + final byte[][] arg = new byte[args.length+1][]; + for (int i = 1; i < arg.length; i++) { + 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][]; + for (int i = 1; i < arg.length; i++) { + 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); + } +} \ No newline at end of file diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index ef952a7..b4db590 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -3085,7 +3085,19 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand public String clusterMeet(final String ip, final int port) { checkIsInMulti(); - client.cluster(Protocol.CLUSTER_MEET, ip, port); + client.cluster(Protocol.CLUSTER_MEET, ip, String.valueOf(port)); + return client.getStatusCodeReply(); + } + + public String clusterAddSlots(final int ...slots) { + checkIsInMulti(); + client.cluster(Protocol.CLUSTER_ADDSLOTS, slots); + return client.getStatusCodeReply(); + } + + public String clusterDelSlots(final int ...slots) { + checkIsInMulti(); + client.cluster(Protocol.CLUSTER_DELSLOTS, slots); return client.getStatusCodeReply(); } } diff --git a/src/main/java/redis/clients/jedis/Protocol.java b/src/main/java/redis/clients/jedis/Protocol.java index 22479a5..1bbdc06 100644 --- a/src/main/java/redis/clients/jedis/Protocol.java +++ b/src/main/java/redis/clients/jedis/Protocol.java @@ -32,6 +32,8 @@ public final class Protocol { public static final String CLUSTER_NODES = "nodes"; public static final String CLUSTER_MEET = "meet"; + public static final String CLUSTER_ADDSLOTS = "addslots"; + public static final String CLUSTER_DELSLOTS = "delslots"; private Protocol() { // this prevent the class from instantiation 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 0fe04f1..6b11b09 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java @@ -45,4 +45,17 @@ public class ClusterCommandsTest extends JedisTestBase { String status = node1.clusterMeet("127.0.0.1", nodeInfo2.getPort()); assertEquals("OK", status); } + + @Test + public void clusterAddSlots() { + String status = node1.clusterAddSlots(1, 2, 3, 4, 5); + assertEquals("OK", status); + } + + @Test + public void clusterDelSlots() { + node1.clusterAddSlots(900); + String status = node1.clusterDelSlots(900); + assertEquals("OK", status); + } } \ No newline at end of file From 77d244b96a17b3f9a193e857b1164c2ae70d5b2a Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Mon, 2 Dec 2013 14:04:37 -0500 Subject: [PATCH 13/70] Add CLUSTER INFO, CLUSTER SETSLOT and CLUSTER GETKEYSINSLOT commands --- src/main/java/redis/clients/jedis/Jedis.java | 31 +++++++++++++ .../java/redis/clients/jedis/Protocol.java | 6 +++ .../tests/commands/ClusterCommandsTest.java | 45 ++++++++++++++++++- 3 files changed, 80 insertions(+), 2 deletions(-) diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index b4db590..6451f30 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -3100,4 +3100,35 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand client.cluster(Protocol.CLUSTER_DELSLOTS, slots); return client.getStatusCodeReply(); } + + public String clusterInfo() { + checkIsInMulti(); + client.cluster(Protocol.CLUSTER_INFO); + return client.getStatusCodeReply(); + } + + public List clusterGetKeysInSlot(final int slot, final int count) { + checkIsInMulti(); + final int[] args = new int[]{ slot, count }; + client.cluster(Protocol.CLUSTER_GETKEYSINSLOT, args); + return client.getMultiBulkReply(); + } + + public String clusterSetSlotNode(final int slot, final String nodeId) { + checkIsInMulti(); + client.cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot), Protocol.CLUSTER_SETSLOT_NODE, nodeId); + return client.getStatusCodeReply(); + } + + public String clusterSetSlotMigrating(final int slot, final String nodeId) { + checkIsInMulti(); + client.cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot), Protocol.CLUSTER_SETSLOT_MIGRATING, nodeId); + return client.getStatusCodeReply(); + } + + public String clusterSetSlotImporting(final int slot, final String nodeId) { + checkIsInMulti(); + client.cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot), Protocol.CLUSTER_SETSLOT_IMPORTING, nodeId); + return client.getStatusCodeReply(); + } } diff --git a/src/main/java/redis/clients/jedis/Protocol.java b/src/main/java/redis/clients/jedis/Protocol.java index 1bbdc06..a3eacd6 100644 --- a/src/main/java/redis/clients/jedis/Protocol.java +++ b/src/main/java/redis/clients/jedis/Protocol.java @@ -34,6 +34,12 @@ public final class Protocol { public static final String CLUSTER_MEET = "meet"; public static final String CLUSTER_ADDSLOTS = "addslots"; public static final String CLUSTER_DELSLOTS = "delslots"; + public static final String CLUSTER_INFO = "info"; + public static final String CLUSTER_GETKEYSINSLOT = "getkeysinslot"; + public static final String CLUSTER_SETSLOT = "setslot"; + 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 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 6b11b09..f4abd11 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java @@ -1,5 +1,7 @@ package redis.clients.jedis.tests.commands; +import java.util.List; + import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -45,17 +47,56 @@ public class ClusterCommandsTest extends JedisTestBase { String status = node1.clusterMeet("127.0.0.1", nodeInfo2.getPort()); assertEquals("OK", status); } - + @Test public void clusterAddSlots() { String status = node1.clusterAddSlots(1, 2, 3, 4, 5); assertEquals("OK", status); } - + @Test public void clusterDelSlots() { node1.clusterAddSlots(900); String status = node1.clusterDelSlots(900); assertEquals("OK", status); } + + @Test + public void clusterInfo() { + String info = node1.clusterInfo(); + assertNotNull(info); + } + + @Test + public void clusterGetKeysInSlot() { + node1.clusterAddSlots(500); + List keys = node1.clusterGetKeysInSlot(500, 1); + assertEquals(0, keys.size()); + } + + @Test + public void clusterSetSlotNode() { + String[] nodes = node1.clusterNodes().split("\n"); + String nodeId = nodes[0].split(" ")[0]; + String status = node1.clusterSetSlotNode(10000, nodeId); + assertEquals("OK", status); + } + + @Test + public void clusterSetSlotMigrating() { + node1.clusterAddSlots(5000); + String[] nodes = node1.clusterNodes().split("\n"); + String nodeId = nodes[0].split(" ")[0]; + String status = node1.clusterSetSlotMigrating(5000, nodeId); + 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 5b15d48803078397b3af487bdad289dc9a0ba21a Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Mon, 2 Dec 2013 14:34:05 -0500 Subject: [PATCH 14/70] Refactor to have interfaces. Add cluster pipeline commands. --- src/main/java/redis/clients/jedis/Client.java | 37 ++++++++++++++ .../redis/clients/jedis/ClusterCommands.java | 23 +++++++++ .../redis/clients/jedis/ClusterPipeline.java | 23 +++++++++ src/main/java/redis/clients/jedis/Jedis.java | 21 ++++---- .../clients/jedis/MultiKeyPipelineBase.java | 48 ++++++++++++++++++- 5 files changed, 140 insertions(+), 12 deletions(-) create mode 100644 src/main/java/redis/clients/jedis/ClusterCommands.java create mode 100644 src/main/java/redis/clients/jedis/ClusterPipeline.java diff --git a/src/main/java/redis/clients/jedis/Client.java b/src/main/java/redis/clients/jedis/Client.java index 90621f3..bbe7045 100644 --- a/src/main/java/redis/clients/jedis/Client.java +++ b/src/main/java/redis/clients/jedis/Client.java @@ -831,4 +831,41 @@ public class Client extends BinaryClient implements Commands { 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) { + cluster(Protocol.CLUSTER_ADDSLOTS, 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); + } + + public void clusterSetSlotNode(final int slot, final String 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); + } + + public void clusterSetSlotImporting(final int slot, final String nodeId) { + cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot), Protocol.CLUSTER_SETSLOT_IMPORTING, nodeId); + } } \ No newline at end of file diff --git a/src/main/java/redis/clients/jedis/ClusterCommands.java b/src/main/java/redis/clients/jedis/ClusterCommands.java new file mode 100644 index 0000000..fff4533 --- /dev/null +++ b/src/main/java/redis/clients/jedis/ClusterCommands.java @@ -0,0 +1,23 @@ +package redis.clients.jedis; + +import java.util.List; + +public interface ClusterCommands { + String clusterNodes(); + + String clusterMeet(final String ip, final int port); + + String clusterAddSlots(final int... slots); + + String clusterDelSlots(final int... slots); + + String clusterInfo(); + + List clusterGetKeysInSlot(final int slot, final int count); + + String clusterSetSlotNode(final int slot, final String nodeId); + + String clusterSetSlotMigrating(final int slot, final String nodeId); + + String clusterSetSlotImporting(final int slot, final String nodeId); +} diff --git a/src/main/java/redis/clients/jedis/ClusterPipeline.java b/src/main/java/redis/clients/jedis/ClusterPipeline.java new file mode 100644 index 0000000..73330d4 --- /dev/null +++ b/src/main/java/redis/clients/jedis/ClusterPipeline.java @@ -0,0 +1,23 @@ +package redis.clients.jedis; + +import java.util.List; + +public interface ClusterPipeline { + Response clusterNodes(); + + Response clusterMeet(final String ip, final int port); + + Response clusterAddSlots(final int... slots); + + Response clusterDelSlots(final int... slots); + + Response clusterInfo(); + + Response> clusterGetKeysInSlot(final int slot, final int count); + + Response clusterSetSlotNode(final int slot, final String nodeId); + + Response clusterSetSlotMigrating(final int slot, final String nodeId); + + Response clusterSetSlotImporting(final int slot, final String nodeId); +} diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index 6451f30..c6add77 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -7,7 +7,7 @@ import redis.clients.util.Slowlog; import java.net.URI; import java.util.*; -public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommands, AdvancedJedisCommands, ScriptingCommands { +public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommands, AdvancedJedisCommands, ScriptingCommands, ClusterCommands { public Jedis(final String host) { super(host); } @@ -3079,56 +3079,55 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand public String clusterNodes() { checkIsInMulti(); - client.cluster(Protocol.CLUSTER_NODES); + client.clusterNodes(); return client.getBulkReply(); } public String clusterMeet(final String ip, final int port) { checkIsInMulti(); - client.cluster(Protocol.CLUSTER_MEET, ip, String.valueOf(port)); + client.clusterMeet(ip, port); return client.getStatusCodeReply(); } public String clusterAddSlots(final int ...slots) { checkIsInMulti(); - client.cluster(Protocol.CLUSTER_ADDSLOTS, slots); + client.clusterAddSlots(slots); return client.getStatusCodeReply(); } public String clusterDelSlots(final int ...slots) { checkIsInMulti(); - client.cluster(Protocol.CLUSTER_DELSLOTS, slots); + client.clusterDelSlots(slots); return client.getStatusCodeReply(); } public String clusterInfo() { checkIsInMulti(); - client.cluster(Protocol.CLUSTER_INFO); + client.clusterInfo(); return client.getStatusCodeReply(); } public List clusterGetKeysInSlot(final int slot, final int count) { checkIsInMulti(); - final int[] args = new int[]{ slot, count }; - client.cluster(Protocol.CLUSTER_GETKEYSINSLOT, args); + client.clusterGetKeysInSlot(slot, count); return client.getMultiBulkReply(); } public String clusterSetSlotNode(final int slot, final String nodeId) { checkIsInMulti(); - client.cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot), Protocol.CLUSTER_SETSLOT_NODE, nodeId); + client.clusterSetSlotNode(slot, nodeId); return client.getStatusCodeReply(); } public String clusterSetSlotMigrating(final int slot, final String nodeId) { checkIsInMulti(); - client.cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot), Protocol.CLUSTER_SETSLOT_MIGRATING, nodeId); + client.clusterSetSlotMigrating(slot, nodeId); return client.getStatusCodeReply(); } public String clusterSetSlotImporting(final int slot, final String nodeId) { checkIsInMulti(); - client.cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot), Protocol.CLUSTER_SETSLOT_IMPORTING, nodeId); + client.clusterSetSlotImporting(slot, nodeId); return client.getStatusCodeReply(); } } diff --git a/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java b/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java index be9d89a..04bdc80 100644 --- a/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java +++ b/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java @@ -7,7 +7,8 @@ import java.util.Set; abstract class MultiKeyPipelineBase extends PipelineBase implements BasicRedisPipeline, MultiKeyBinaryRedisPipeline, - MultiKeyCommandsPipeline { + MultiKeyCommandsPipeline, + ClusterPipeline { protected Client client = null; @@ -398,4 +399,49 @@ abstract class MultiKeyPipelineBase extends PipelineBase implements client.bitop(op, destKey, srcKeys); return getResponse(BuilderFactory.LONG); } + + public Response clusterNodes() { + client.clusterNodes(); + return getResponse(BuilderFactory.STRING); + } + + public Response clusterMeet(final String ip, final int port) { + client.clusterMeet(ip, port); + return getResponse(BuilderFactory.STRING); + } + + public Response clusterAddSlots(final int... slots) { + client.clusterAddSlots(slots); + return getResponse(BuilderFactory.STRING); + } + + public Response clusterDelSlots(final int... slots) { + client.clusterDelSlots(slots); + return getResponse(BuilderFactory.STRING); + } + + public Response clusterInfo() { + client.clusterInfo(); + return getResponse(BuilderFactory.STRING); + } + + 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) { + client.clusterSetSlotNode(slot, nodeId); + return getResponse(BuilderFactory.STRING); + } + + 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) { + client.clusterSetSlotImporting(slot, nodeId); + return getResponse(BuilderFactory.STRING); + } } From 46966fb89f6fa9383bef7009f1949d3002594438 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Mon, 2 Dec 2013 19:27:12 -0500 Subject: [PATCH 15/70] Prepare redis cluster for testing. The cluster will always be in a deterministic state to be able to reproduce -MOVED and -ASK --- .../redis/clients/jedis/JedisCluster.java | 5 ++ .../clients/jedis/tests/JedisClusterTest.java | 70 +++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 src/main/java/redis/clients/jedis/JedisCluster.java create mode 100644 src/test/java/redis/clients/jedis/tests/JedisClusterTest.java diff --git a/src/main/java/redis/clients/jedis/JedisCluster.java b/src/main/java/redis/clients/jedis/JedisCluster.java new file mode 100644 index 0000000..7b5613b --- /dev/null +++ b/src/main/java/redis/clients/jedis/JedisCluster.java @@ -0,0 +1,5 @@ +package redis.clients.jedis; + +public class JedisCluster { + public static final int HASH_SLOTS = 16384; +} diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java new file mode 100644 index 0000000..ca90362 --- /dev/null +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java @@ -0,0 +1,70 @@ +package redis.clients.jedis.tests; + +import org.junit.After; +import org.junit.Assert; +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.Pipeline; + +public class JedisClusterTest extends Assert { + private Jedis node1; + private Jedis node2; + private Jedis node3; + + 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() { + node1 = new Jedis(nodeInfo1.getHost(), nodeInfo1.getPort()); + node1.connect(); + node1.flushAll(); + + node2 = new Jedis(nodeInfo2.getHost(), nodeInfo2.getPort()); + node2.connect(); + node2.flushAll(); + + node3 = new Jedis(nodeInfo3.getHost(), nodeInfo3.getPort()); + node3.connect(); + node3.flushAll(); + + // ---- 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()); + + // add all slots to node1 + Pipeline pipelined = node1.pipelined(); + for (int i = 0; i < JedisCluster.HASH_SLOTS; i++) { + pipelined.clusterAddSlots(i); + } + pipelined.sync(); + } + + @After + public void tearDown() { + // clear all slots of node1 + Pipeline pipelined = node1.pipelined(); + for (int i = 0; i < JedisCluster.HASH_SLOTS; i++) { + pipelined.clusterDelSlots(i); + } + pipelined.sync(); + } + + @Test + public void moved() { + //TODO: needs to implement + } + + @Test + public void ask() { + //TODO: needs to implement + } +} \ No newline at end of file From efbb710343b5ca63f679d08213e5265ffda5ee64 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Tue, 3 Dec 2013 08:31:24 -0500 Subject: [PATCH 16/70] Change string size to make test fail faster --- .../PublishSubscribeCommandsTest.java | 950 +++++++++--------- 1 file changed, 484 insertions(+), 466 deletions(-) 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 37fb2a1..de60084 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java @@ -3,6 +3,7 @@ package redis.clients.jedis.tests.commands; import java.io.IOException; import java.net.UnknownHostException; import java.util.Arrays; +import java.util.concurrent.atomic.AtomicBoolean; import org.junit.Ignore; import org.junit.Test; @@ -17,585 +18,602 @@ import redis.clients.util.SafeEncoder; public class PublishSubscribeCommandsTest extends JedisCommandTestBase { @Test public void subscribe() throws InterruptedException { - Thread t = new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - Thread.sleep(1000); - j.publish("foo", "exit"); - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }); - t.start(); - jedis.subscribe(new JedisPubSub() { - public void onMessage(String channel, String message) { - assertEquals("foo", channel); - assertEquals("exit", message); - unsubscribe(); - } + Thread t = new Thread(new Runnable() { + public void run() { + try { + Jedis j = createJedis(); + Thread.sleep(1000); + j.publish("foo", "exit"); + j.disconnect(); + } catch (Exception ex) { + fail(ex.getMessage()); + } + } + }); + t.start(); + jedis.subscribe(new JedisPubSub() { + public void onMessage(String channel, String message) { + assertEquals("foo", channel); + assertEquals("exit", message); + unsubscribe(); + } - public void onSubscribe(String channel, int subscribedChannels) { - assertEquals("foo", channel); - assertEquals(1, subscribedChannels); - } + public void onSubscribe(String channel, int subscribedChannels) { + assertEquals("foo", channel); + assertEquals(1, subscribedChannels); + } - public void onUnsubscribe(String channel, int subscribedChannels) { - assertEquals("foo", channel); - assertEquals(0, subscribedChannels); - } + public void onUnsubscribe(String channel, int subscribedChannels) { + assertEquals("foo", channel); + assertEquals(0, subscribedChannels); + } - public void onPSubscribe(String pattern, int subscribedChannels) { - } + public void onPSubscribe(String pattern, int subscribedChannels) { + } - public void onPUnsubscribe(String pattern, int subscribedChannels) { - } + public void onPUnsubscribe(String pattern, int subscribedChannels) { + } - public void onPMessage(String pattern, String channel, - String message) { - } - }, "foo"); - t.join(); + public void onPMessage(String pattern, String channel, + String message) { + } + }, "foo"); + t.join(); } @Test public void subscribeMany() throws UnknownHostException, IOException, - InterruptedException { - Thread t = new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - Thread.sleep(1000); - j.publish("foo", "exit"); - Thread.sleep(1000); - j.publish("bar", "exit"); - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }); - t.start(); - jedis.subscribe(new JedisPubSub() { - public void onMessage(String channel, String message) { - unsubscribe(channel); - } + InterruptedException { + Thread t = new Thread(new Runnable() { + public void run() { + try { + Jedis j = createJedis(); + Thread.sleep(1000); + j.publish("foo", "exit"); + Thread.sleep(1000); + j.publish("bar", "exit"); + j.disconnect(); + } catch (Exception ex) { + fail(ex.getMessage()); + } + } + }); + t.start(); + jedis.subscribe(new JedisPubSub() { + public void onMessage(String channel, String message) { + unsubscribe(channel); + } - public void onSubscribe(String channel, int subscribedChannels) { - } + public void onSubscribe(String channel, int subscribedChannels) { + } - public void onUnsubscribe(String channel, int subscribedChannels) { - } + public void onUnsubscribe(String channel, int subscribedChannels) { + } - public void onPSubscribe(String pattern, int subscribedChannels) { - } + public void onPSubscribe(String pattern, int subscribedChannels) { + } - public void onPUnsubscribe(String pattern, int subscribedChannels) { - } + public void onPUnsubscribe(String pattern, int subscribedChannels) { + } - public void onPMessage(String pattern, String channel, - String message) { - } - }, "foo", "bar"); - t.join(); + public void onPMessage(String pattern, String channel, + String message) { + } + }, "foo", "bar"); + t.join(); } @Test public void psubscribe() throws UnknownHostException, IOException, - InterruptedException { - Thread t = new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - Thread.sleep(1000); - j.publish("foo.bar", "exit"); - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }); - t.start(); - jedis.psubscribe(new JedisPubSub() { - public void onMessage(String channel, String message) { - } + InterruptedException { + Thread t = new Thread(new Runnable() { + public void run() { + try { + Jedis j = createJedis(); + Thread.sleep(1000); + j.publish("foo.bar", "exit"); + j.disconnect(); + } catch (Exception ex) { + fail(ex.getMessage()); + } + } + }); + t.start(); + jedis.psubscribe(new JedisPubSub() { + public void onMessage(String channel, String message) { + } - public void onSubscribe(String channel, int subscribedChannels) { - } + public void onSubscribe(String channel, int subscribedChannels) { + } - public void onUnsubscribe(String channel, int subscribedChannels) { - } + public void onUnsubscribe(String channel, int subscribedChannels) { + } - public void onPSubscribe(String pattern, int subscribedChannels) { - assertEquals("foo.*", pattern); - assertEquals(1, subscribedChannels); - } + public void onPSubscribe(String pattern, int subscribedChannels) { + assertEquals("foo.*", pattern); + assertEquals(1, subscribedChannels); + } - public void onPUnsubscribe(String pattern, int subscribedChannels) { - assertEquals("foo.*", pattern); - assertEquals(0, subscribedChannels); - } + public void onPUnsubscribe(String pattern, int subscribedChannels) { + assertEquals("foo.*", pattern); + assertEquals(0, subscribedChannels); + } - public void onPMessage(String pattern, String channel, - String message) { - assertEquals("foo.*", pattern); - assertEquals("foo.bar", channel); - assertEquals("exit", message); - punsubscribe(); - } - }, "foo.*"); - t.join(); + public void onPMessage(String pattern, String channel, + String message) { + assertEquals("foo.*", pattern); + assertEquals("foo.bar", channel); + assertEquals("exit", message); + punsubscribe(); + } + }, "foo.*"); + t.join(); } @Test public void psubscribeMany() throws UnknownHostException, IOException, - InterruptedException { - Thread t = new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - Thread.sleep(1000); - j.publish("foo.123", "exit"); - Thread.sleep(1000); - j.publish("bar.123", "exit"); - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }); - t.start(); - jedis.psubscribe(new JedisPubSub() { - public void onMessage(String channel, String message) { - } + InterruptedException { + Thread t = new Thread(new Runnable() { + public void run() { + try { + Jedis j = createJedis(); + Thread.sleep(1000); + j.publish("foo.123", "exit"); + Thread.sleep(1000); + j.publish("bar.123", "exit"); + j.disconnect(); + } catch (Exception ex) { + fail(ex.getMessage()); + } + } + }); + t.start(); + jedis.psubscribe(new JedisPubSub() { + public void onMessage(String channel, String message) { + } - public void onSubscribe(String channel, int subscribedChannels) { - } + public void onSubscribe(String channel, int subscribedChannels) { + } - public void onUnsubscribe(String channel, int subscribedChannels) { - } + public void onUnsubscribe(String channel, int subscribedChannels) { + } - public void onPSubscribe(String pattern, int subscribedChannels) { - } + public void onPSubscribe(String pattern, int subscribedChannels) { + } - public void onPUnsubscribe(String pattern, int subscribedChannels) { - } + public void onPUnsubscribe(String pattern, int subscribedChannels) { + } - public void onPMessage(String pattern, String channel, - String message) { - punsubscribe(pattern); - } - }, "foo.*", "bar.*"); - t.join(); + public void onPMessage(String pattern, String channel, + String message) { + punsubscribe(pattern); + } + }, "foo.*", "bar.*"); + t.join(); } @Test public void subscribeLazily() throws UnknownHostException, IOException, - InterruptedException { - final JedisPubSub pubsub = new JedisPubSub() { - public void onMessage(String channel, String message) { - unsubscribe(channel); - } + InterruptedException { + final JedisPubSub pubsub = new JedisPubSub() { + public void onMessage(String channel, String message) { + unsubscribe(channel); + } - public void onSubscribe(String channel, int subscribedChannels) { - } + public void onSubscribe(String channel, int subscribedChannels) { + } - public void onUnsubscribe(String channel, int subscribedChannels) { - } + public void onUnsubscribe(String channel, int subscribedChannels) { + } - public void onPSubscribe(String pattern, int subscribedChannels) { - } + public void onPSubscribe(String pattern, int subscribedChannels) { + } - public void onPUnsubscribe(String pattern, int subscribedChannels) { - } + public void onPUnsubscribe(String pattern, int subscribedChannels) { + } - public void onPMessage(String pattern, String channel, - String message) { - punsubscribe(pattern); - } - }; + public void onPMessage(String pattern, String channel, + String message) { + punsubscribe(pattern); + } + }; - Thread t = new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - Thread.sleep(1000); - pubsub.subscribe("bar"); - pubsub.psubscribe("bar.*"); - j.publish("foo", "exit"); - j.publish("bar", "exit"); - j.publish("bar.123", "exit"); - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }); - t.start(); - jedis.subscribe(pubsub, "foo"); - t.join(); + Thread t = new Thread(new Runnable() { + public void run() { + try { + Jedis j = createJedis(); + Thread.sleep(1000); + pubsub.subscribe("bar"); + pubsub.psubscribe("bar.*"); + j.publish("foo", "exit"); + j.publish("bar", "exit"); + j.publish("bar.123", "exit"); + j.disconnect(); + } catch (Exception ex) { + fail(ex.getMessage()); + } + } + }); + t.start(); + jedis.subscribe(pubsub, "foo"); + t.join(); } @Test public void binarySubscribe() throws UnknownHostException, IOException, - InterruptedException { - Thread t = new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - Thread.sleep(1000); - j.publish(SafeEncoder.encode("foo"), SafeEncoder - .encode("exit")); - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }); - t.start(); - jedis.subscribe(new BinaryJedisPubSub() { - public void onMessage(byte[] channel, byte[] message) { - assertTrue(Arrays.equals(SafeEncoder.encode("foo"), channel)); - assertTrue(Arrays.equals(SafeEncoder.encode("exit"), message)); - unsubscribe(); - } + InterruptedException { + Thread t = new Thread(new Runnable() { + public void run() { + try { + Jedis j = createJedis(); + Thread.sleep(1000); + j.publish(SafeEncoder.encode("foo"), + SafeEncoder.encode("exit")); + j.disconnect(); + } catch (Exception ex) { + fail(ex.getMessage()); + } + } + }); + t.start(); + jedis.subscribe(new BinaryJedisPubSub() { + public void onMessage(byte[] channel, byte[] message) { + assertTrue(Arrays.equals(SafeEncoder.encode("foo"), channel)); + assertTrue(Arrays.equals(SafeEncoder.encode("exit"), message)); + unsubscribe(); + } - public void onSubscribe(byte[] channel, int subscribedChannels) { - assertTrue(Arrays.equals(SafeEncoder.encode("foo"), channel)); - assertEquals(1, subscribedChannels); - } + public void onSubscribe(byte[] channel, int subscribedChannels) { + assertTrue(Arrays.equals(SafeEncoder.encode("foo"), channel)); + assertEquals(1, subscribedChannels); + } - public void onUnsubscribe(byte[] channel, int subscribedChannels) { - assertTrue(Arrays.equals(SafeEncoder.encode("foo"), channel)); - assertEquals(0, subscribedChannels); - } + public void onUnsubscribe(byte[] channel, int subscribedChannels) { + assertTrue(Arrays.equals(SafeEncoder.encode("foo"), channel)); + assertEquals(0, subscribedChannels); + } - public void onPSubscribe(byte[] pattern, int subscribedChannels) { - } + public void onPSubscribe(byte[] pattern, int subscribedChannels) { + } - public void onPUnsubscribe(byte[] pattern, int subscribedChannels) { - } + public void onPUnsubscribe(byte[] pattern, int subscribedChannels) { + } - public void onPMessage(byte[] pattern, byte[] channel, - byte[] message) { - } - }, SafeEncoder.encode("foo")); - t.join(); + public void onPMessage(byte[] pattern, byte[] channel, + byte[] message) { + } + }, SafeEncoder.encode("foo")); + t.join(); } @Test public void binarySubscribeMany() throws UnknownHostException, IOException, - InterruptedException { - Thread t = new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - Thread.sleep(1000); - j.publish(SafeEncoder.encode("foo"), SafeEncoder - .encode("exit")); - Thread.sleep(1000); - j.publish(SafeEncoder.encode("bar"), SafeEncoder - .encode("exit")); - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }); - t.start(); - jedis.subscribe(new BinaryJedisPubSub() { - public void onMessage(byte[] channel, byte[] message) { - unsubscribe(channel); - } + InterruptedException { + Thread t = new Thread(new Runnable() { + public void run() { + try { + Jedis j = createJedis(); + Thread.sleep(1000); + j.publish(SafeEncoder.encode("foo"), + SafeEncoder.encode("exit")); + Thread.sleep(1000); + j.publish(SafeEncoder.encode("bar"), + SafeEncoder.encode("exit")); + j.disconnect(); + } catch (Exception ex) { + fail(ex.getMessage()); + } + } + }); + t.start(); + jedis.subscribe(new BinaryJedisPubSub() { + public void onMessage(byte[] channel, byte[] message) { + unsubscribe(channel); + } - public void onSubscribe(byte[] channel, int subscribedChannels) { - } + public void onSubscribe(byte[] channel, int subscribedChannels) { + } - public void onUnsubscribe(byte[] channel, int subscribedChannels) { - } + public void onUnsubscribe(byte[] channel, int subscribedChannels) { + } - public void onPSubscribe(byte[] pattern, int subscribedChannels) { - } + public void onPSubscribe(byte[] pattern, int subscribedChannels) { + } - public void onPUnsubscribe(byte[] pattern, int subscribedChannels) { - } + public void onPUnsubscribe(byte[] pattern, int subscribedChannels) { + } - public void onPMessage(byte[] pattern, byte[] channel, - byte[] message) { - } - }, SafeEncoder.encode("foo"), SafeEncoder.encode("bar")); - t.join(); + public void onPMessage(byte[] pattern, byte[] channel, + byte[] message) { + } + }, SafeEncoder.encode("foo"), SafeEncoder.encode("bar")); + t.join(); } @Test public void binaryPsubscribe() throws UnknownHostException, IOException, - InterruptedException { - Thread t = new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - Thread.sleep(1000); - j.publish(SafeEncoder.encode("foo.bar"), SafeEncoder - .encode("exit")); - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }); - t.start(); - jedis.psubscribe(new BinaryJedisPubSub() { - public void onMessage(byte[] channel, byte[] message) { - } + InterruptedException { + Thread t = new Thread(new Runnable() { + public void run() { + try { + Jedis j = createJedis(); + Thread.sleep(1000); + j.publish(SafeEncoder.encode("foo.bar"), + SafeEncoder.encode("exit")); + j.disconnect(); + } catch (Exception ex) { + fail(ex.getMessage()); + } + } + }); + t.start(); + jedis.psubscribe(new BinaryJedisPubSub() { + public void onMessage(byte[] channel, byte[] message) { + } - public void onSubscribe(byte[] channel, int subscribedChannels) { - } + public void onSubscribe(byte[] channel, int subscribedChannels) { + } - public void onUnsubscribe(byte[] channel, int subscribedChannels) { - } + public void onUnsubscribe(byte[] channel, int subscribedChannels) { + } - public void onPSubscribe(byte[] pattern, int subscribedChannels) { - assertTrue(Arrays.equals(SafeEncoder.encode("foo.*"), pattern)); - assertEquals(1, subscribedChannels); - } + public void onPSubscribe(byte[] pattern, int subscribedChannels) { + assertTrue(Arrays.equals(SafeEncoder.encode("foo.*"), pattern)); + assertEquals(1, subscribedChannels); + } - public void onPUnsubscribe(byte[] pattern, int subscribedChannels) { - assertTrue(Arrays.equals(SafeEncoder.encode("foo.*"), pattern)); - assertEquals(0, subscribedChannels); - } + public void onPUnsubscribe(byte[] pattern, int subscribedChannels) { + assertTrue(Arrays.equals(SafeEncoder.encode("foo.*"), pattern)); + assertEquals(0, subscribedChannels); + } - public void onPMessage(byte[] pattern, byte[] channel, - byte[] message) { - assertTrue(Arrays.equals(SafeEncoder.encode("foo.*"), pattern)); - assertTrue(Arrays - .equals(SafeEncoder.encode("foo.bar"), channel)); - assertTrue(Arrays.equals(SafeEncoder.encode("exit"), message)); - punsubscribe(); - } - }, SafeEncoder.encode("foo.*")); - t.join(); + public void onPMessage(byte[] pattern, byte[] channel, + byte[] message) { + assertTrue(Arrays.equals(SafeEncoder.encode("foo.*"), pattern)); + assertTrue(Arrays + .equals(SafeEncoder.encode("foo.bar"), channel)); + assertTrue(Arrays.equals(SafeEncoder.encode("exit"), message)); + punsubscribe(); + } + }, SafeEncoder.encode("foo.*")); + t.join(); } @Test public void binaryPsubscribeMany() throws UnknownHostException, - IOException, InterruptedException { - Thread t = new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - Thread.sleep(1000); - j.publish(SafeEncoder.encode("foo.123"), SafeEncoder - .encode("exit")); - Thread.sleep(1000); - j.publish(SafeEncoder.encode("bar.123"), SafeEncoder - .encode("exit")); - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }); - t.start(); - jedis.psubscribe(new BinaryJedisPubSub() { - public void onMessage(byte[] channel, byte[] message) { - } + IOException, InterruptedException { + Thread t = new Thread(new Runnable() { + public void run() { + try { + Jedis j = createJedis(); + Thread.sleep(1000); + j.publish(SafeEncoder.encode("foo.123"), + SafeEncoder.encode("exit")); + Thread.sleep(1000); + j.publish(SafeEncoder.encode("bar.123"), + SafeEncoder.encode("exit")); + j.disconnect(); + } catch (Exception ex) { + fail(ex.getMessage()); + } + } + }); + t.start(); + jedis.psubscribe(new BinaryJedisPubSub() { + public void onMessage(byte[] channel, byte[] message) { + } - public void onSubscribe(byte[] channel, int subscribedChannels) { - } + public void onSubscribe(byte[] channel, int subscribedChannels) { + } - public void onUnsubscribe(byte[] channel, int subscribedChannels) { - } + public void onUnsubscribe(byte[] channel, int subscribedChannels) { + } - public void onPSubscribe(byte[] pattern, int subscribedChannels) { - } + public void onPSubscribe(byte[] pattern, int subscribedChannels) { + } - public void onPUnsubscribe(byte[] pattern, int subscribedChannels) { - } + public void onPUnsubscribe(byte[] pattern, int subscribedChannels) { + } - public void onPMessage(byte[] pattern, byte[] channel, - byte[] message) { - punsubscribe(pattern); - } - }, SafeEncoder.encode("foo.*"), SafeEncoder.encode("bar.*")); - t.join(); + public void onPMessage(byte[] pattern, byte[] channel, + byte[] message) { + punsubscribe(pattern); + } + }, SafeEncoder.encode("foo.*"), SafeEncoder.encode("bar.*")); + t.join(); } @Test public void binarySubscribeLazily() throws UnknownHostException, - IOException, InterruptedException { - final BinaryJedisPubSub pubsub = new BinaryJedisPubSub() { - public void onMessage(byte[] channel, byte[] message) { - unsubscribe(channel); - } + IOException, InterruptedException { + final BinaryJedisPubSub pubsub = new BinaryJedisPubSub() { + public void onMessage(byte[] channel, byte[] message) { + unsubscribe(channel); + } - public void onSubscribe(byte[] channel, int subscribedChannels) { - } + public void onSubscribe(byte[] channel, int subscribedChannels) { + } - public void onUnsubscribe(byte[] channel, int subscribedChannels) { - } + public void onUnsubscribe(byte[] channel, int subscribedChannels) { + } - public void onPSubscribe(byte[] pattern, int subscribedChannels) { - } + public void onPSubscribe(byte[] pattern, int subscribedChannels) { + } - public void onPUnsubscribe(byte[] pattern, int subscribedChannels) { - } + public void onPUnsubscribe(byte[] pattern, int subscribedChannels) { + } - public void onPMessage(byte[] pattern, byte[] channel, - byte[] message) { - punsubscribe(pattern); - } - }; + public void onPMessage(byte[] pattern, byte[] channel, + byte[] message) { + punsubscribe(pattern); + } + }; - Thread t = new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - Thread.sleep(1000); - pubsub.subscribe(SafeEncoder.encode("bar")); - pubsub.psubscribe(SafeEncoder.encode("bar.*")); - j.publish(SafeEncoder.encode("foo"), SafeEncoder - .encode("exit")); - j.publish(SafeEncoder.encode("bar"), SafeEncoder - .encode("exit")); - j.publish(SafeEncoder.encode("bar.123"), SafeEncoder - .encode("exit")); - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }); - t.start(); - jedis.subscribe(pubsub, SafeEncoder.encode("foo")); - t.join(); + Thread t = new Thread(new Runnable() { + public void run() { + try { + Jedis j = createJedis(); + Thread.sleep(1000); + pubsub.subscribe(SafeEncoder.encode("bar")); + pubsub.psubscribe(SafeEncoder.encode("bar.*")); + j.publish(SafeEncoder.encode("foo"), + SafeEncoder.encode("exit")); + j.publish(SafeEncoder.encode("bar"), + SafeEncoder.encode("exit")); + j.publish(SafeEncoder.encode("bar.123"), + SafeEncoder.encode("exit")); + j.disconnect(); + } catch (Exception ex) { + fail(ex.getMessage()); + } + } + }); + t.start(); + jedis.subscribe(pubsub, SafeEncoder.encode("foo")); + t.join(); } - @Test @Ignore + @Test + @Ignore public void subscribeWithoutConnecting() { - try { - Jedis jedis = new Jedis(hnp.getHost(), hnp.getPort()); - jedis.subscribe(new JedisPubSub() { - public void onMessage(String channel, String message) { - } + try { + Jedis jedis = new Jedis(hnp.getHost(), hnp.getPort()); + jedis.subscribe(new JedisPubSub() { + public void onMessage(String channel, String message) { + } - public void onPMessage(String pattern, String channel, - String message) { - } + public void onPMessage(String pattern, String channel, + String message) { + } - public void onSubscribe(String channel, int subscribedChannels) { - } + public void onSubscribe(String channel, int subscribedChannels) { + } - public void onUnsubscribe(String channel, int subscribedChannels) { - } + public void onUnsubscribe(String channel, int subscribedChannels) { + } - public void onPUnsubscribe(String pattern, - int subscribedChannels) { - } + public void onPUnsubscribe(String pattern, + int subscribedChannels) { + } - public void onPSubscribe(String pattern, int subscribedChannels) { - } - }, "foo"); - } catch (NullPointerException ex) { - fail(); - } catch (JedisDataException ex) { - // this is OK because we are not sending AUTH command - } + public void onPSubscribe(String pattern, int subscribedChannels) { + } + }, "foo"); + } catch (NullPointerException ex) { + fail(); + } catch (JedisDataException ex) { + // this is OK because we are not sending AUTH command + } } @Test(expected = JedisConnectionException.class) public void unsubscribeWhenNotSusbscribed() throws InterruptedException { - JedisPubSub pubsub = new JedisPubSub() { - public void onMessage(String channel, String message) { - } + JedisPubSub pubsub = new JedisPubSub() { + public void onMessage(String channel, String message) { + } - public void onPMessage(String pattern, String channel, - String message) { - } + public void onPMessage(String pattern, String channel, + String message) { + } - public void onSubscribe(String channel, int subscribedChannels) { - } + public void onSubscribe(String channel, int subscribedChannels) { + } - public void onUnsubscribe(String channel, int subscribedChannels) { - } + public void onUnsubscribe(String channel, int subscribedChannels) { + } - public void onPUnsubscribe(String pattern, int subscribedChannels) { - } + public void onPUnsubscribe(String pattern, int subscribedChannels) { + } - public void onPSubscribe(String pattern, int subscribedChannels) { - } - }; - pubsub.unsubscribe(); + public void onPSubscribe(String pattern, int subscribedChannels) { + } + }; + pubsub.unsubscribe(); } - + @Test(expected = JedisConnectionException.class) - public void handleClientOutputBufferLimitForSubscribeTooSlow() throws InterruptedException { - final Thread t = new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - - Thread.sleep(1000); - - // we already set jedis1 config to client-output-buffer-limit pubsub 256k 128k 5 - // it means if subscriber delayed to receive over 256k or 128k continuously 5 sec, - // redis disconnects subscriber - - // we publish over 10M data for making situation for exceed client-output-buffer-limit - String veryLargeString = makeLargeString(1024 * 10); - - // 10K * 1024 = 10M - for (int i = 0 ; i < 1024 ; i++) - j.publish("foo", veryLargeString); // 1k - - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }); - t.start(); - jedis.subscribe(new JedisPubSub() { - public void onMessage(String channel, String message) { - try { - // wait 0.5 secs to slow down subscribe and client-output-buffer exceed - //System.out.println("channel - " + channel + " / message - " + message); - Thread.sleep(500); - } catch (Exception e) { - try { - t.join(); - } catch (InterruptedException e1) { - } - - fail(e.getMessage()); - } - } + public void handleClientOutputBufferLimitForSubscribeTooSlow() + throws InterruptedException { + final Jedis j = createJedis(); + final AtomicBoolean exit = new AtomicBoolean(false); - public void onSubscribe(String channel, int subscribedChannels) { - } + final Thread t = new Thread(new Runnable() { + public void run() { + try { - public void onUnsubscribe(String channel, int subscribedChannels) { - } + // we already set jedis1 config to + // client-output-buffer-limit pubsub 256k 128k 5 + // it means if subscriber delayed to receive over 256k or + // 128k continuously 5 sec, + // redis disconnects subscriber - public void onPSubscribe(String pattern, int subscribedChannels) { - } + // we publish over 100M data for making situation for exceed + // client-output-buffer-limit + String veryLargeString = makeLargeString(10485760); - public void onPUnsubscribe(String pattern, int subscribedChannels) { - } + // 10M * 10 = 100M + for (int i = 0; i < 10 && !exit.get(); i++) { + j.publish("foo", veryLargeString); + } - public void onPMessage(String pattern, String channel, - String message) { - } - }, "foo"); - t.join(); + j.disconnect(); + } catch (Exception ex) { + } + } + }); + t.start(); + try { + jedis.subscribe(new JedisPubSub() { + public void onMessage(String channel, String message) { + try { + // wait 0.5 secs to slow down subscribe and + // client-output-buffer exceed + // System.out.println("channel - " + channel + + // " / message - " + message); + Thread.sleep(500); + } catch (Exception e) { + try { + t.join(); + } catch (InterruptedException e1) { + } + + fail(e.getMessage()); + } + } + + public void onSubscribe(String channel, int subscribedChannels) { + } + + public void onUnsubscribe(String channel, int subscribedChannels) { + } + + public void onPSubscribe(String pattern, int subscribedChannels) { + } + + public void onPUnsubscribe(String pattern, + int subscribedChannels) { + } + + public void onPMessage(String pattern, String channel, + String message) { + } + }, "foo"); + t.join(); + } finally { + // exit the publisher thread. if exception is thrown, thread might + // still keep publishing things. + exit.set(true); + if (t.isAlive()) { + t.wait(); + } + } } - - private String makeLargeString(int size) { - StringBuffer sb = new StringBuffer(); - for (int i = 0 ; i < size ; i++) - sb.append((char)('a' + i % 26)); - return sb.toString(); + private String makeLargeString(int size) { + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < size; i++) + sb.append((char) ('a' + i % 26)); + + return sb.toString(); } } From a27c67de663bff5a2fbf6b3803d35835ba1515d0 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Tue, 3 Dec 2013 16:55:52 -0500 Subject: [PATCH 17/70] add SCAN, HSCAN, SSCAN and ZSCAN --- .../redis/clients/jedis/BinaryClient.java | 31 + src/main/java/redis/clients/jedis/Client.java | 13 + .../java/redis/clients/jedis/Commands.java | 8 + src/main/java/redis/clients/jedis/Jedis.java | 83 ++- .../redis/clients/jedis/JedisCommands.java | 6 + .../redis/clients/jedis/MultiKeyCommands.java | 3 + .../java/redis/clients/jedis/Protocol.java | 4 +- .../java/redis/clients/jedis/ScanParams.java | 29 + .../java/redis/clients/jedis/ScanResult.java | 21 + .../redis/clients/jedis/ShardedJedis.java | 16 +- .../commands/AllKindOfValuesCommandsTest.java | 652 ++++++++++-------- .../tests/commands/HashesCommandsTest.java | 410 ++++++----- .../jedis/tests/commands/SetCommandsTest.java | 39 +- .../tests/commands/SortedSetCommandsTest.java | 44 ++ 14 files changed, 862 insertions(+), 497 deletions(-) create mode 100644 src/main/java/redis/clients/jedis/ScanParams.java create mode 100644 src/main/java/redis/clients/jedis/ScanResult.java diff --git a/src/main/java/redis/clients/jedis/BinaryClient.java b/src/main/java/redis/clients/jedis/BinaryClient.java index acb120b..428fe72 100644 --- a/src/main/java/redis/clients/jedis/BinaryClient.java +++ b/src/main/java/redis/clients/jedis/BinaryClient.java @@ -1100,4 +1100,35 @@ public class BinaryClient extends Connection { 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()][])); + } + + 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()][])); + } + + 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()][])); + } } diff --git a/src/main/java/redis/clients/jedis/Client.java b/src/main/java/redis/clients/jedis/Client.java index 9c97e38..c5a072b 100644 --- a/src/main/java/redis/clients/jedis/Client.java +++ b/src/main/java/redis/clients/jedis/Client.java @@ -9,6 +9,7 @@ import java.util.Map; import java.util.Map.Entry; import static redis.clients.jedis.Protocol.toByteArray; +import static redis.clients.jedis.Protocol.Command.HSCAN; public class Client extends BinaryClient implements Commands { public Client(final String host) { @@ -807,4 +808,16 @@ public class Client extends BinaryClient implements Commands { 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); + } + + public void sscan(final String key, int cursor, final ScanParams params) { + sscan(SafeEncoder.encode(key), cursor, params); + } + + public void zscan(final String key, int cursor, final ScanParams params) { + zscan(SafeEncoder.encode(key), cursor, params); + } } diff --git a/src/main/java/redis/clients/jedis/Commands.java b/src/main/java/redis/clients/jedis/Commands.java index 851c065..898dcdd 100644 --- a/src/main/java/redis/clients/jedis/Commands.java +++ b/src/main/java/redis/clients/jedis/Commands.java @@ -295,4 +295,12 @@ public interface Commands { public void bitcount(final String key, long start, long end); public void bitop(BitOP op, final String destKey, String... srcKeys); + + public void scan(int cursor, final ScanParams params); + + public void hscan(final String key, int cursor, final ScanParams params); + + public void sscan(final String key, int cursor, final ScanParams params); + + public void zscan(final String key, int cursor, final ScanParams params); } diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index 23cfd3d..200632a 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -1,12 +1,19 @@ 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.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 { public Jedis(final String host) { super(host); @@ -3076,4 +3083,74 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand 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))); + 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, int cursor) { + return hscan(key, cursor, new ScanParams()); + } + + 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))); + 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, int cursor) { + return sscan(key, cursor, new ScanParams()); + } + + 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))); + 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, int cursor) { + return zscan(key, cursor, new ScanParams()); + } + + 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))); + 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); + } } diff --git a/src/main/java/redis/clients/jedis/JedisCommands.java b/src/main/java/redis/clients/jedis/JedisCommands.java index a2bc07f..d027361 100644 --- a/src/main/java/redis/clients/jedis/JedisCommands.java +++ b/src/main/java/redis/clients/jedis/JedisCommands.java @@ -211,4 +211,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/MultiKeyCommands.java b/src/main/java/redis/clients/jedis/MultiKeyCommands.java index c98017f..64285de 100644 --- a/src/main/java/redis/clients/jedis/MultiKeyCommands.java +++ b/src/main/java/redis/clients/jedis/MultiKeyCommands.java @@ -2,6 +2,7 @@ package redis.clients.jedis; import java.util.List; +import java.util.Map; import java.util.Set; public interface MultiKeyCommands { @@ -70,4 +71,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/Protocol.java b/src/main/java/redis/clients/jedis/Protocol.java index 53ad1cd..5eca2c5 100644 --- a/src/main/java/redis/clients/jedis/Protocol.java +++ b/src/main/java/redis/clients/jedis/Protocol.java @@ -158,7 +158,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; + DUMP, RESTORE, PEXPIRE, PEXPIREAT, PTTL, INCRBYFLOAT, PSETEX, CLIENT, TIME, MIGRATE, HINCRBYFLOAT, SCAN, HSCAN, SSCAN, ZSCAN; public final byte[] raw; @@ -169,7 +169,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; + GETNAME, SETNAME,LIST, MATCH, COUNT; public final byte[] raw; Keyword() { diff --git a/src/main/java/redis/clients/jedis/ScanParams.java b/src/main/java/redis/clients/jedis/ScanParams.java new file mode 100644 index 0000000..874d636 --- /dev/null +++ b/src/main/java/redis/clients/jedis/ScanParams.java @@ -0,0 +1,29 @@ +package redis.clients.jedis; + +import static redis.clients.jedis.Protocol.Keyword.COUNT; +import static redis.clients.jedis.Protocol.Keyword.MATCH; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import redis.clients.util.SafeEncoder; + +public class ScanParams { + private List params = new ArrayList(); + + public void match(final String pattern) { + params.add(MATCH.raw); + params.add(SafeEncoder.encode(pattern)); + } + + public void count(final int count) { + params.add(COUNT.raw); + params.add(Protocol.toByteArray(count)); + } + + public Collection getParams() { + return Collections.unmodifiableCollection(params); + } +} diff --git a/src/main/java/redis/clients/jedis/ScanResult.java b/src/main/java/redis/clients/jedis/ScanResult.java new file mode 100644 index 0000000..d8ba7c6 --- /dev/null +++ b/src/main/java/redis/clients/jedis/ScanResult.java @@ -0,0 +1,21 @@ +package redis.clients.jedis; + +import java.util.List; + +public class ScanResult { + private int cursor; + private List results; + + public ScanResult(int cursor, List results) { + this.cursor = cursor; + this.results = results; + } + + public int getCursor() { + 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 485f83a..a63a7d0 100644 --- a/src/main/java/redis/clients/jedis/ShardedJedis.java +++ b/src/main/java/redis/clients/jedis/ShardedJedis.java @@ -5,6 +5,7 @@ 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; @@ -522,5 +523,18 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands { return j.bitcount(key, start, end); } - + public ScanResult> hscan(String key, int cursor) { + 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/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java index b21d739..8fe2675 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java @@ -6,6 +6,8 @@ import java.util.Set; import org.junit.Test; +import redis.clients.jedis.ScanParams; +import redis.clients.jedis.ScanResult; import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.util.SafeEncoder; @@ -25,482 +27,520 @@ public class AllKindOfValuesCommandsTest extends JedisCommandTestBase { @Test public void ping() { - String status = jedis.ping(); - assertEquals("PONG", status); + String status = jedis.ping(); + assertEquals("PONG", status); } @Test public void exists() { - String status = jedis.set("foo", "bar"); - assertEquals("OK", status); + String status = jedis.set("foo", "bar"); + assertEquals("OK", status); - status = jedis.set(bfoo, bbar); - assertEquals("OK", status); + status = jedis.set(bfoo, bbar); + assertEquals("OK", status); - boolean reply = jedis.exists("foo"); - assertTrue(reply); + boolean reply = jedis.exists("foo"); + assertTrue(reply); - reply = jedis.exists(bfoo); - assertTrue(reply); + reply = jedis.exists(bfoo); + assertTrue(reply); - long lreply = jedis.del("foo"); - assertEquals(1, lreply); + long lreply = jedis.del("foo"); + assertEquals(1, lreply); - lreply = jedis.del(bfoo); - assertEquals(1, lreply); + lreply = jedis.del(bfoo); + assertEquals(1, lreply); - reply = jedis.exists("foo"); - assertFalse(reply); + reply = jedis.exists("foo"); + assertFalse(reply); - reply = jedis.exists(bfoo); - assertFalse(reply); + reply = jedis.exists(bfoo); + assertFalse(reply); } @Test public void del() { - jedis.set("foo1", "bar1"); - jedis.set("foo2", "bar2"); - jedis.set("foo3", "bar3"); + jedis.set("foo1", "bar1"); + jedis.set("foo2", "bar2"); + jedis.set("foo3", "bar3"); - long reply = jedis.del("foo1", "foo2", "foo3"); - assertEquals(3, reply); + long reply = jedis.del("foo1", "foo2", "foo3"); + assertEquals(3, reply); - Boolean breply = jedis.exists("foo1"); - assertFalse(breply); - breply = jedis.exists("foo2"); - assertFalse(breply); - breply = jedis.exists("foo3"); - assertFalse(breply); + Boolean breply = jedis.exists("foo1"); + assertFalse(breply); + breply = jedis.exists("foo2"); + assertFalse(breply); + breply = jedis.exists("foo3"); + assertFalse(breply); - jedis.set("foo1", "bar1"); + jedis.set("foo1", "bar1"); - reply = jedis.del("foo1", "foo2"); - assertEquals(1, reply); + reply = jedis.del("foo1", "foo2"); + assertEquals(1, reply); - reply = jedis.del("foo1", "foo2"); - assertEquals(0, reply); + reply = jedis.del("foo1", "foo2"); + assertEquals(0, reply); - // Binary ... - jedis.set(bfoo1, bbar1); - jedis.set(bfoo2, bbar2); - jedis.set(bfoo3, bbar3); + // Binary ... + jedis.set(bfoo1, bbar1); + jedis.set(bfoo2, bbar2); + jedis.set(bfoo3, bbar3); - reply = jedis.del(bfoo1, bfoo2, bfoo3); - assertEquals(3, reply); + reply = jedis.del(bfoo1, bfoo2, bfoo3); + assertEquals(3, reply); - breply = jedis.exists(bfoo1); - assertFalse(breply); - breply = jedis.exists(bfoo2); - assertFalse(breply); - breply = jedis.exists(bfoo3); - assertFalse(breply); + breply = jedis.exists(bfoo1); + assertFalse(breply); + breply = jedis.exists(bfoo2); + assertFalse(breply); + breply = jedis.exists(bfoo3); + assertFalse(breply); - jedis.set(bfoo1, bbar1); + jedis.set(bfoo1, bbar1); - reply = jedis.del(bfoo1, bfoo2); - assertEquals(1, reply); + reply = jedis.del(bfoo1, bfoo2); + assertEquals(1, reply); - reply = jedis.del(bfoo1, bfoo2); - assertEquals(0, reply); + reply = jedis.del(bfoo1, bfoo2); + assertEquals(0, reply); } @Test public void type() { - jedis.set("foo", "bar"); - String status = jedis.type("foo"); - assertEquals("string", status); + jedis.set("foo", "bar"); + String status = jedis.type("foo"); + assertEquals("string", status); - // Binary - jedis.set(bfoo, bbar); - status = jedis.type(bfoo); - assertEquals("string", status); + // Binary + jedis.set(bfoo, bbar); + status = jedis.type(bfoo); + assertEquals("string", status); } @Test public void keys() { - jedis.set("foo", "bar"); - jedis.set("foobar", "bar"); + jedis.set("foo", "bar"); + jedis.set("foobar", "bar"); - Set keys = jedis.keys("foo*"); - Set expected = new HashSet(); - expected.add("foo"); - expected.add("foobar"); - assertEquals(expected, keys); + Set keys = jedis.keys("foo*"); + Set expected = new HashSet(); + expected.add("foo"); + expected.add("foobar"); + assertEquals(expected, keys); - expected = new HashSet(); - keys = jedis.keys("bar*"); + expected = new HashSet(); + keys = jedis.keys("bar*"); - assertEquals(expected, keys); + assertEquals(expected, keys); - // Binary - jedis.set(bfoo, bbar); - jedis.set(bfoobar, bbar); + // Binary + jedis.set(bfoo, bbar); + jedis.set(bfoobar, bbar); - Set bkeys = jedis.keys(bfoostar); - assertEquals(2, bkeys.size()); - assertTrue(setContains(bkeys, bfoo)); - assertTrue(setContains(bkeys, bfoobar)); + Set bkeys = jedis.keys(bfoostar); + assertEquals(2, bkeys.size()); + assertTrue(setContains(bkeys, bfoo)); + assertTrue(setContains(bkeys, bfoobar)); - bkeys = jedis.keys(bbarstar); + bkeys = jedis.keys(bbarstar); - assertEquals(0, bkeys.size()); + assertEquals(0, bkeys.size()); } @Test public void randomKey() { - assertEquals(null, jedis.randomKey()); + assertEquals(null, jedis.randomKey()); - jedis.set("foo", "bar"); + jedis.set("foo", "bar"); - assertEquals("foo", jedis.randomKey()); + assertEquals("foo", jedis.randomKey()); - jedis.set("bar", "foo"); + jedis.set("bar", "foo"); - String randomkey = jedis.randomKey(); - assertTrue(randomkey.equals("foo") || randomkey.equals("bar")); + String randomkey = jedis.randomKey(); + assertTrue(randomkey.equals("foo") || randomkey.equals("bar")); - // Binary - jedis.del("foo"); - jedis.del("bar"); - assertEquals(null, jedis.randomKey()); + // Binary + jedis.del("foo"); + jedis.del("bar"); + assertEquals(null, jedis.randomKey()); - jedis.set(bfoo, bbar); + jedis.set(bfoo, bbar); - assertArrayEquals(bfoo, jedis.randomBinaryKey()); + assertArrayEquals(bfoo, jedis.randomBinaryKey()); - jedis.set(bbar, bfoo); + jedis.set(bbar, bfoo); - byte[] randomBkey = jedis.randomBinaryKey(); - assertTrue(Arrays.equals(randomBkey, bfoo) - || Arrays.equals(randomBkey, bbar)); + byte[] randomBkey = jedis.randomBinaryKey(); + assertTrue(Arrays.equals(randomBkey, bfoo) + || Arrays.equals(randomBkey, bbar)); } @Test public void rename() { - jedis.set("foo", "bar"); - String status = jedis.rename("foo", "bar"); - assertEquals("OK", status); + jedis.set("foo", "bar"); + String status = jedis.rename("foo", "bar"); + assertEquals("OK", status); - String value = jedis.get("foo"); - assertEquals(null, value); + String value = jedis.get("foo"); + assertEquals(null, value); - value = jedis.get("bar"); - assertEquals("bar", value); + value = jedis.get("bar"); + assertEquals("bar", value); - // Binary - jedis.set(bfoo, bbar); - String bstatus = jedis.rename(bfoo, bbar); - assertEquals("OK", bstatus); + // Binary + jedis.set(bfoo, bbar); + String bstatus = jedis.rename(bfoo, bbar); + assertEquals("OK", bstatus); - byte[] bvalue = jedis.get(bfoo); - assertEquals(null, bvalue); + byte[] bvalue = jedis.get(bfoo); + assertEquals(null, bvalue); - bvalue = jedis.get(bbar); - assertArrayEquals(bbar, bvalue); + bvalue = jedis.get(bbar); + assertArrayEquals(bbar, bvalue); } @Test public void renameOldAndNewAreTheSame() { - try { - jedis.set("foo", "bar"); - jedis.rename("foo", "foo"); - fail("JedisDataException expected"); - } catch (final JedisDataException e) { - } + try { + jedis.set("foo", "bar"); + jedis.rename("foo", "foo"); + fail("JedisDataException expected"); + } catch (final JedisDataException e) { + } - // Binary - try { - jedis.set(bfoo, bbar); - jedis.rename(bfoo, bfoo); - fail("JedisDataException expected"); - } catch (final JedisDataException e) { - } + // Binary + try { + jedis.set(bfoo, bbar); + jedis.rename(bfoo, bfoo); + fail("JedisDataException expected"); + } catch (final JedisDataException e) { + } } @Test public void renamenx() { - jedis.set("foo", "bar"); - long status = jedis.renamenx("foo", "bar"); - assertEquals(1, status); + jedis.set("foo", "bar"); + long status = jedis.renamenx("foo", "bar"); + assertEquals(1, status); - jedis.set("foo", "bar"); - status = jedis.renamenx("foo", "bar"); - assertEquals(0, status); + jedis.set("foo", "bar"); + status = jedis.renamenx("foo", "bar"); + assertEquals(0, status); - // Binary - jedis.set(bfoo, bbar); - long bstatus = jedis.renamenx(bfoo, bbar); - assertEquals(1, bstatus); + // Binary + jedis.set(bfoo, bbar); + long bstatus = jedis.renamenx(bfoo, bbar); + assertEquals(1, bstatus); - jedis.set(bfoo, bbar); - bstatus = jedis.renamenx(bfoo, bbar); - assertEquals(0, bstatus); + jedis.set(bfoo, bbar); + bstatus = jedis.renamenx(bfoo, bbar); + assertEquals(0, bstatus); } @Test public void dbSize() { - long size = jedis.dbSize(); - assertEquals(0, size); + long size = jedis.dbSize(); + assertEquals(0, size); - jedis.set("foo", "bar"); - size = jedis.dbSize(); - assertEquals(1, size); + jedis.set("foo", "bar"); + size = jedis.dbSize(); + assertEquals(1, size); - // Binary - jedis.set(bfoo, bbar); - size = jedis.dbSize(); - assertEquals(2, size); + // Binary + jedis.set(bfoo, bbar); + size = jedis.dbSize(); + assertEquals(2, size); } @Test public void expire() { - long status = jedis.expire("foo", 20); - assertEquals(0, status); + long status = jedis.expire("foo", 20); + assertEquals(0, status); - jedis.set("foo", "bar"); - status = jedis.expire("foo", 20); - assertEquals(1, status); + jedis.set("foo", "bar"); + status = jedis.expire("foo", 20); + assertEquals(1, status); - // Binary - long bstatus = jedis.expire(bfoo, 20); - assertEquals(0, bstatus); + // Binary + long bstatus = jedis.expire(bfoo, 20); + assertEquals(0, bstatus); - jedis.set(bfoo, bbar); - bstatus = jedis.expire(bfoo, 20); - assertEquals(1, bstatus); + jedis.set(bfoo, bbar); + bstatus = jedis.expire(bfoo, 20); + assertEquals(1, bstatus); } @Test public void expireAt() { - long unixTime = (System.currentTimeMillis() / 1000L) + 20; + long unixTime = (System.currentTimeMillis() / 1000L) + 20; - long status = jedis.expireAt("foo", unixTime); - assertEquals(0, status); + long status = jedis.expireAt("foo", unixTime); + assertEquals(0, status); - jedis.set("foo", "bar"); - unixTime = (System.currentTimeMillis() / 1000L) + 20; - status = jedis.expireAt("foo", unixTime); - assertEquals(1, status); + jedis.set("foo", "bar"); + unixTime = (System.currentTimeMillis() / 1000L) + 20; + status = jedis.expireAt("foo", unixTime); + assertEquals(1, status); - // Binary - long bstatus = jedis.expireAt(bfoo, unixTime); - assertEquals(0, bstatus); + // Binary + long bstatus = jedis.expireAt(bfoo, unixTime); + assertEquals(0, bstatus); - jedis.set(bfoo, bbar); - unixTime = (System.currentTimeMillis() / 1000L) + 20; - bstatus = jedis.expireAt(bfoo, unixTime); - assertEquals(1, bstatus); + jedis.set(bfoo, bbar); + unixTime = (System.currentTimeMillis() / 1000L) + 20; + bstatus = jedis.expireAt(bfoo, unixTime); + assertEquals(1, bstatus); } @Test public void ttl() { - long ttl = jedis.ttl("foo"); - assertEquals(-2, ttl); + long ttl = jedis.ttl("foo"); + assertEquals(-2, ttl); - jedis.set("foo", "bar"); - ttl = jedis.ttl("foo"); - assertEquals(-1, ttl); + jedis.set("foo", "bar"); + ttl = jedis.ttl("foo"); + assertEquals(-1, ttl); - jedis.expire("foo", 20); - ttl = jedis.ttl("foo"); - assertTrue(ttl >= 0 && ttl <= 20); + jedis.expire("foo", 20); + ttl = jedis.ttl("foo"); + assertTrue(ttl >= 0 && ttl <= 20); - // Binary - long bttl = jedis.ttl(bfoo); - assertEquals(-2, bttl); + // Binary + long bttl = jedis.ttl(bfoo); + assertEquals(-2, bttl); - jedis.set(bfoo, bbar); - bttl = jedis.ttl(bfoo); - assertEquals(-1, bttl); + jedis.set(bfoo, bbar); + bttl = jedis.ttl(bfoo); + assertEquals(-1, bttl); - jedis.expire(bfoo, 20); - bttl = jedis.ttl(bfoo); - assertTrue(bttl >= 0 && bttl <= 20); + jedis.expire(bfoo, 20); + bttl = jedis.ttl(bfoo); + assertTrue(bttl >= 0 && bttl <= 20); } @Test public void select() { - jedis.set("foo", "bar"); - String status = jedis.select(1); - assertEquals("OK", status); - assertEquals(null, jedis.get("foo")); - status = jedis.select(0); - assertEquals("OK", status); - assertEquals("bar", jedis.get("foo")); - // Binary - jedis.set(bfoo, bbar); - String bstatus = jedis.select(1); - assertEquals("OK", bstatus); - assertEquals(null, jedis.get(bfoo)); - bstatus = jedis.select(0); - assertEquals("OK", bstatus); - assertArrayEquals(bbar, jedis.get(bfoo)); + jedis.set("foo", "bar"); + String status = jedis.select(1); + assertEquals("OK", status); + assertEquals(null, jedis.get("foo")); + status = jedis.select(0); + assertEquals("OK", status); + assertEquals("bar", jedis.get("foo")); + // Binary + jedis.set(bfoo, bbar); + String bstatus = jedis.select(1); + assertEquals("OK", bstatus); + assertEquals(null, jedis.get(bfoo)); + bstatus = jedis.select(0); + assertEquals("OK", bstatus); + assertArrayEquals(bbar, jedis.get(bfoo)); } @Test public void getDB() { - assertEquals(0, jedis.getDB().longValue()); - jedis.select(1); - assertEquals(1, jedis.getDB().longValue()); + assertEquals(0, jedis.getDB().longValue()); + jedis.select(1); + assertEquals(1, jedis.getDB().longValue()); } @Test public void move() { - long status = jedis.move("foo", 1); - assertEquals(0, status); + long status = jedis.move("foo", 1); + assertEquals(0, status); - jedis.set("foo", "bar"); - status = jedis.move("foo", 1); - assertEquals(1, status); - assertEquals(null, jedis.get("foo")); + jedis.set("foo", "bar"); + status = jedis.move("foo", 1); + assertEquals(1, status); + assertEquals(null, jedis.get("foo")); - jedis.select(1); - assertEquals("bar", jedis.get("foo")); + jedis.select(1); + assertEquals("bar", jedis.get("foo")); - // Binary - jedis.select(0); - long bstatus = jedis.move(bfoo, 1); - assertEquals(0, bstatus); + // Binary + jedis.select(0); + long bstatus = jedis.move(bfoo, 1); + assertEquals(0, bstatus); - jedis.set(bfoo, bbar); - bstatus = jedis.move(bfoo, 1); - assertEquals(1, bstatus); - assertEquals(null, jedis.get(bfoo)); + jedis.set(bfoo, bbar); + bstatus = jedis.move(bfoo, 1); + assertEquals(1, bstatus); + assertEquals(null, jedis.get(bfoo)); - jedis.select(1); - assertArrayEquals(bbar, jedis.get(bfoo)); + jedis.select(1); + assertArrayEquals(bbar, jedis.get(bfoo)); } @Test public void flushDB() { - jedis.set("foo", "bar"); - assertEquals(1, jedis.dbSize().intValue()); - jedis.set("bar", "foo"); - jedis.move("bar", 1); - String status = jedis.flushDB(); - assertEquals("OK", status); - assertEquals(0, jedis.dbSize().intValue()); - jedis.select(1); - assertEquals(1, jedis.dbSize().intValue()); - jedis.del("bar"); + jedis.set("foo", "bar"); + assertEquals(1, jedis.dbSize().intValue()); + jedis.set("bar", "foo"); + jedis.move("bar", 1); + String status = jedis.flushDB(); + assertEquals("OK", status); + assertEquals(0, jedis.dbSize().intValue()); + jedis.select(1); + assertEquals(1, jedis.dbSize().intValue()); + jedis.del("bar"); - // Binary - jedis.select(0); - jedis.set(bfoo, bbar); - assertEquals(1, jedis.dbSize().intValue()); - jedis.set(bbar, bfoo); - jedis.move(bbar, 1); - String bstatus = jedis.flushDB(); - assertEquals("OK", bstatus); - assertEquals(0, jedis.dbSize().intValue()); - jedis.select(1); - assertEquals(1, jedis.dbSize().intValue()); + // Binary + jedis.select(0); + jedis.set(bfoo, bbar); + assertEquals(1, jedis.dbSize().intValue()); + jedis.set(bbar, bfoo); + jedis.move(bbar, 1); + String bstatus = jedis.flushDB(); + assertEquals("OK", bstatus); + assertEquals(0, jedis.dbSize().intValue()); + jedis.select(1); + assertEquals(1, jedis.dbSize().intValue()); } @Test public void flushAll() { - jedis.set("foo", "bar"); - assertEquals(1, jedis.dbSize().intValue()); - jedis.set("bar", "foo"); - jedis.move("bar", 1); - String status = jedis.flushAll(); - assertEquals("OK", status); - assertEquals(0, jedis.dbSize().intValue()); - jedis.select(1); - assertEquals(0, jedis.dbSize().intValue()); + jedis.set("foo", "bar"); + assertEquals(1, jedis.dbSize().intValue()); + jedis.set("bar", "foo"); + jedis.move("bar", 1); + String status = jedis.flushAll(); + assertEquals("OK", status); + assertEquals(0, jedis.dbSize().intValue()); + jedis.select(1); + assertEquals(0, jedis.dbSize().intValue()); - // Binary - jedis.select(0); - jedis.set(bfoo, bbar); - assertEquals(1, jedis.dbSize().intValue()); - jedis.set(bbar, bfoo); - jedis.move(bbar, 1); - String bstatus = jedis.flushAll(); - assertEquals("OK", bstatus); - assertEquals(0, jedis.dbSize().intValue()); - jedis.select(1); - assertEquals(0, jedis.dbSize().intValue()); + // Binary + jedis.select(0); + jedis.set(bfoo, bbar); + assertEquals(1, jedis.dbSize().intValue()); + jedis.set(bbar, bfoo); + jedis.move(bbar, 1); + String bstatus = jedis.flushAll(); + assertEquals("OK", bstatus); + assertEquals(0, jedis.dbSize().intValue()); + jedis.select(1); + assertEquals(0, jedis.dbSize().intValue()); } @Test public void persist() { - jedis.setex("foo", 60 * 60, "bar"); - assertTrue(jedis.ttl("foo") > 0); - long status = jedis.persist("foo"); - assertEquals(1, status); - assertEquals(-1, jedis.ttl("foo").intValue()); + jedis.setex("foo", 60 * 60, "bar"); + assertTrue(jedis.ttl("foo") > 0); + long status = jedis.persist("foo"); + assertEquals(1, status); + assertEquals(-1, jedis.ttl("foo").intValue()); - // Binary - jedis.setex(bfoo, 60 * 60, bbar); - assertTrue(jedis.ttl(bfoo) > 0); - long bstatus = jedis.persist(bfoo); - assertEquals(1, bstatus); - assertEquals(-1, jedis.ttl(bfoo).intValue()); + // Binary + jedis.setex(bfoo, 60 * 60, bbar); + assertTrue(jedis.ttl(bfoo) > 0); + long bstatus = jedis.persist(bfoo); + assertEquals(1, bstatus); + assertEquals(-1, jedis.ttl(bfoo).intValue()); } @Test public void echo() { - String result = jedis.echo("hello world"); - assertEquals("hello world", result); + String result = jedis.echo("hello world"); + assertEquals("hello world", result); - // Binary - byte[] bresult = jedis.echo(SafeEncoder.encode("hello world")); - assertArrayEquals(SafeEncoder.encode("hello world"), bresult); + // Binary + byte[] bresult = jedis.echo(SafeEncoder.encode("hello world")); + assertArrayEquals(SafeEncoder.encode("hello world"), bresult); } - + @Test public void dumpAndRestore() { - jedis.set("foo1", "bar1"); - byte[] sv = jedis.dump("foo1"); - jedis.restore("foo2", 0, sv); - assertTrue(jedis.exists("foo2")); + jedis.set("foo1", "bar1"); + byte[] sv = jedis.dump("foo1"); + jedis.restore("foo2", 0, sv); + assertTrue(jedis.exists("foo2")); } - + @Test public void pexpire() { - long status = jedis.pexpire("foo", 10000); - assertEquals(0, status); + long status = jedis.pexpire("foo", 10000); + assertEquals(0, status); - jedis.set("foo", "bar"); - status = jedis.pexpire("foo", 10000); - assertEquals(1, status); + jedis.set("foo", "bar"); + status = jedis.pexpire("foo", 10000); + assertEquals(1, status); } - + @Test public void pexpireAt() { - long unixTime = (System.currentTimeMillis()) + 10000; + long unixTime = (System.currentTimeMillis()) + 10000; - long status = jedis.pexpireAt("foo", unixTime); - assertEquals(0, status); + long status = jedis.pexpireAt("foo", unixTime); + assertEquals(0, status); - jedis.set("foo", "bar"); - unixTime = (System.currentTimeMillis()) + 10000; - status = jedis.pexpireAt("foo", unixTime); - assertEquals(1, status); + jedis.set("foo", "bar"); + unixTime = (System.currentTimeMillis()) + 10000; + status = jedis.pexpireAt("foo", unixTime); + assertEquals(1, status); } - + @Test public void pttl() { - long pttl = jedis.pttl("foo"); - assertEquals(-2, pttl); + long pttl = jedis.pttl("foo"); + assertEquals(-2, pttl); - jedis.set("foo", "bar"); - pttl = jedis.pttl("foo"); - assertEquals(-1, pttl); + jedis.set("foo", "bar"); + pttl = jedis.pttl("foo"); + assertEquals(-1, pttl); - jedis.pexpire("foo", 20000); - pttl = jedis.pttl("foo"); - assertTrue(pttl >= 0 && pttl <= 20000); + jedis.pexpire("foo", 20000); + pttl = jedis.pttl("foo"); + assertTrue(pttl >= 0 && pttl <= 20000); } + @Test + public void scan() { + jedis.set("b", "b"); + jedis.set("a", "a"); + + ScanResult result = jedis.scan(0); + + assertEquals(0, result.getCursor()); + assertFalse(result.getResult().isEmpty()); + } + + @Test + public void scanMatch() { + ScanParams params = new ScanParams(); + params.match("a*"); + + jedis.set("b", "b"); + jedis.set("a", "a"); + jedis.set("aa", "aa"); + ScanResult result = jedis.scan(0, params); + + assertEquals(0, result.getCursor()); + assertFalse(result.getResult().isEmpty()); + } + + @Test + public void scanCount() { + ScanParams params = new ScanParams(); + params.count(2); + + for (int i = 0; i < 10; i++) { + jedis.set("a" + i, "a" + i); + } + + ScanResult result = jedis.scan(0, 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 fbcbca3..c7ef2c7 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java @@ -10,6 +10,9 @@ import java.util.Set; import org.junit.Test; +import redis.clients.jedis.ScanParams; +import redis.clients.jedis.ScanResult; + public class HashesCommandsTest extends JedisCommandTestBase { final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; @@ -17,273 +20,312 @@ public class HashesCommandsTest extends JedisCommandTestBase { @Test public void hset() { - long status = jedis.hset("foo", "bar", "car"); - assertEquals(1, status); - status = jedis.hset("foo", "bar", "foo"); - assertEquals(0, status); + long status = jedis.hset("foo", "bar", "car"); + assertEquals(1, status); + status = jedis.hset("foo", "bar", "foo"); + assertEquals(0, status); - // Binary - long bstatus = jedis.hset(bfoo, bbar, bcar); - assertEquals(1, bstatus); - bstatus = jedis.hset(bfoo, bbar, bfoo); - assertEquals(0, bstatus); + // Binary + long bstatus = jedis.hset(bfoo, bbar, bcar); + assertEquals(1, bstatus); + bstatus = jedis.hset(bfoo, bbar, bfoo); + assertEquals(0, bstatus); } @Test public void hget() { - jedis.hset("foo", "bar", "car"); - assertEquals(null, jedis.hget("bar", "foo")); - assertEquals(null, jedis.hget("foo", "car")); - assertEquals("car", jedis.hget("foo", "bar")); + jedis.hset("foo", "bar", "car"); + assertEquals(null, jedis.hget("bar", "foo")); + assertEquals(null, jedis.hget("foo", "car")); + assertEquals("car", jedis.hget("foo", "bar")); - // Binary - jedis.hset(bfoo, bbar, bcar); - assertEquals(null, jedis.hget(bbar, bfoo)); - assertEquals(null, jedis.hget(bfoo, bcar)); - assertArrayEquals(bcar, jedis.hget(bfoo, bbar)); + // Binary + jedis.hset(bfoo, bbar, bcar); + assertEquals(null, jedis.hget(bbar, bfoo)); + assertEquals(null, jedis.hget(bfoo, bcar)); + assertArrayEquals(bcar, jedis.hget(bfoo, bbar)); } @Test public void hsetnx() { - long status = jedis.hsetnx("foo", "bar", "car"); - assertEquals(1, status); - assertEquals("car", jedis.hget("foo", "bar")); + long status = jedis.hsetnx("foo", "bar", "car"); + assertEquals(1, status); + assertEquals("car", jedis.hget("foo", "bar")); - status = jedis.hsetnx("foo", "bar", "foo"); - assertEquals(0, status); - assertEquals("car", jedis.hget("foo", "bar")); + status = jedis.hsetnx("foo", "bar", "foo"); + assertEquals(0, status); + assertEquals("car", jedis.hget("foo", "bar")); - status = jedis.hsetnx("foo", "car", "bar"); - assertEquals(1, status); - assertEquals("bar", jedis.hget("foo", "car")); + status = jedis.hsetnx("foo", "car", "bar"); + assertEquals(1, status); + assertEquals("bar", jedis.hget("foo", "car")); - // Binary - long bstatus = jedis.hsetnx(bfoo, bbar, bcar); - assertEquals(1, bstatus); - assertArrayEquals(bcar, jedis.hget(bfoo, bbar)); + // Binary + long bstatus = jedis.hsetnx(bfoo, bbar, bcar); + assertEquals(1, bstatus); + assertArrayEquals(bcar, jedis.hget(bfoo, bbar)); - bstatus = jedis.hsetnx(bfoo, bbar, bfoo); - assertEquals(0, bstatus); - assertArrayEquals(bcar, jedis.hget(bfoo, bbar)); + bstatus = jedis.hsetnx(bfoo, bbar, bfoo); + assertEquals(0, bstatus); + assertArrayEquals(bcar, jedis.hget(bfoo, bbar)); - bstatus = jedis.hsetnx(bfoo, bcar, bbar); - assertEquals(1, bstatus); - assertArrayEquals(bbar, jedis.hget(bfoo, bcar)); + bstatus = jedis.hsetnx(bfoo, bcar, bbar); + assertEquals(1, bstatus); + assertArrayEquals(bbar, jedis.hget(bfoo, bcar)); } @Test public void hmset() { - Map hash = new HashMap(); - hash.put("bar", "car"); - hash.put("car", "bar"); - String status = jedis.hmset("foo", hash); - assertEquals("OK", status); - assertEquals("car", jedis.hget("foo", "bar")); - assertEquals("bar", jedis.hget("foo", "car")); + Map hash = new HashMap(); + hash.put("bar", "car"); + hash.put("car", "bar"); + String status = jedis.hmset("foo", hash); + assertEquals("OK", status); + assertEquals("car", jedis.hget("foo", "bar")); + assertEquals("bar", jedis.hget("foo", "car")); - // Binary - Map bhash = new HashMap(); - bhash.put(bbar, bcar); - bhash.put(bcar, bbar); - String bstatus = jedis.hmset(bfoo, bhash); - assertEquals("OK", bstatus); - assertArrayEquals(bcar, jedis.hget(bfoo, bbar)); - assertArrayEquals(bbar, jedis.hget(bfoo, bcar)); + // Binary + Map bhash = new HashMap(); + bhash.put(bbar, bcar); + bhash.put(bcar, bbar); + String bstatus = jedis.hmset(bfoo, bhash); + assertEquals("OK", bstatus); + assertArrayEquals(bcar, jedis.hget(bfoo, bbar)); + assertArrayEquals(bbar, jedis.hget(bfoo, bcar)); } @Test public void hmget() { - Map hash = new HashMap(); - hash.put("bar", "car"); - hash.put("car", "bar"); - jedis.hmset("foo", hash); + Map hash = new HashMap(); + hash.put("bar", "car"); + hash.put("car", "bar"); + jedis.hmset("foo", hash); - List values = jedis.hmget("foo", "bar", "car", "foo"); - List expected = new ArrayList(); - expected.add("car"); - expected.add("bar"); - expected.add(null); + List values = jedis.hmget("foo", "bar", "car", "foo"); + List expected = new ArrayList(); + expected.add("car"); + expected.add("bar"); + expected.add(null); - assertEquals(expected, values); + assertEquals(expected, values); - // Binary - Map bhash = new HashMap(); - bhash.put(bbar, bcar); - bhash.put(bcar, bbar); - jedis.hmset(bfoo, bhash); + // Binary + Map bhash = new HashMap(); + bhash.put(bbar, bcar); + bhash.put(bcar, bbar); + jedis.hmset(bfoo, bhash); - List bvalues = jedis.hmget(bfoo, bbar, bcar, bfoo); - List bexpected = new ArrayList(); - bexpected.add(bcar); - bexpected.add(bbar); - bexpected.add(null); + List bvalues = jedis.hmget(bfoo, bbar, bcar, bfoo); + List bexpected = new ArrayList(); + bexpected.add(bcar); + bexpected.add(bbar); + bexpected.add(null); - assertEquals(bexpected, bvalues); + assertEquals(bexpected, bvalues); } @Test public void hincrBy() { - long value = jedis.hincrBy("foo", "bar", 1); - assertEquals(1, value); - value = jedis.hincrBy("foo", "bar", -1); - assertEquals(0, value); - value = jedis.hincrBy("foo", "bar", -10); - assertEquals(-10, value); + long value = jedis.hincrBy("foo", "bar", 1); + assertEquals(1, value); + value = jedis.hincrBy("foo", "bar", -1); + assertEquals(0, value); + value = jedis.hincrBy("foo", "bar", -10); + assertEquals(-10, value); - // Binary - long bvalue = jedis.hincrBy(bfoo, bbar, 1); - assertEquals(1, bvalue); - bvalue = jedis.hincrBy(bfoo, bbar, -1); - assertEquals(0, bvalue); - bvalue = jedis.hincrBy(bfoo, bbar, -10); - assertEquals(-10, bvalue); + // Binary + long bvalue = jedis.hincrBy(bfoo, bbar, 1); + assertEquals(1, bvalue); + bvalue = jedis.hincrBy(bfoo, bbar, -1); + assertEquals(0, bvalue); + bvalue = jedis.hincrBy(bfoo, bbar, -10); + assertEquals(-10, bvalue); } @Test public void hexists() { - Map hash = new HashMap(); - hash.put("bar", "car"); - hash.put("car", "bar"); - jedis.hmset("foo", hash); + Map hash = new HashMap(); + hash.put("bar", "car"); + hash.put("car", "bar"); + jedis.hmset("foo", hash); - assertFalse(jedis.hexists("bar", "foo")); - assertFalse(jedis.hexists("foo", "foo")); - assertTrue(jedis.hexists("foo", "bar")); + assertFalse(jedis.hexists("bar", "foo")); + assertFalse(jedis.hexists("foo", "foo")); + assertTrue(jedis.hexists("foo", "bar")); - // Binary - Map bhash = new HashMap(); - bhash.put(bbar, bcar); - bhash.put(bcar, bbar); - jedis.hmset(bfoo, bhash); + // Binary + Map bhash = new HashMap(); + bhash.put(bbar, bcar); + bhash.put(bcar, bbar); + jedis.hmset(bfoo, bhash); - assertFalse(jedis.hexists(bbar, bfoo)); - assertFalse(jedis.hexists(bfoo, bfoo)); - assertTrue(jedis.hexists(bfoo, bbar)); + assertFalse(jedis.hexists(bbar, bfoo)); + assertFalse(jedis.hexists(bfoo, bfoo)); + assertTrue(jedis.hexists(bfoo, bbar)); } @Test public void hdel() { - Map hash = new HashMap(); - hash.put("bar", "car"); - hash.put("car", "bar"); - jedis.hmset("foo", hash); + Map hash = new HashMap(); + hash.put("bar", "car"); + hash.put("car", "bar"); + jedis.hmset("foo", hash); - assertEquals(0, jedis.hdel("bar", "foo").intValue()); - assertEquals(0, jedis.hdel("foo", "foo").intValue()); - assertEquals(1, jedis.hdel("foo", "bar").intValue()); - assertEquals(null, jedis.hget("foo", "bar")); + assertEquals(0, jedis.hdel("bar", "foo").intValue()); + assertEquals(0, jedis.hdel("foo", "foo").intValue()); + assertEquals(1, jedis.hdel("foo", "bar").intValue()); + assertEquals(null, jedis.hget("foo", "bar")); - // Binary - Map bhash = new HashMap(); - bhash.put(bbar, bcar); - bhash.put(bcar, bbar); - jedis.hmset(bfoo, bhash); + // Binary + Map bhash = new HashMap(); + bhash.put(bbar, bcar); + bhash.put(bcar, bbar); + jedis.hmset(bfoo, bhash); - assertEquals(0, jedis.hdel(bbar, bfoo).intValue()); - assertEquals(0, jedis.hdel(bfoo, bfoo).intValue()); - assertEquals(1, jedis.hdel(bfoo, bbar).intValue()); - assertEquals(null, jedis.hget(bfoo, bbar)); + assertEquals(0, jedis.hdel(bbar, bfoo).intValue()); + assertEquals(0, jedis.hdel(bfoo, bfoo).intValue()); + assertEquals(1, jedis.hdel(bfoo, bbar).intValue()); + assertEquals(null, jedis.hget(bfoo, bbar)); } @Test public void hlen() { - Map hash = new HashMap(); - hash.put("bar", "car"); - hash.put("car", "bar"); - jedis.hmset("foo", hash); + Map hash = new HashMap(); + hash.put("bar", "car"); + hash.put("car", "bar"); + jedis.hmset("foo", hash); - assertEquals(0, jedis.hlen("bar").intValue()); - assertEquals(2, jedis.hlen("foo").intValue()); + assertEquals(0, jedis.hlen("bar").intValue()); + assertEquals(2, jedis.hlen("foo").intValue()); - // Binary - Map bhash = new HashMap(); - bhash.put(bbar, bcar); - bhash.put(bcar, bbar); - jedis.hmset(bfoo, bhash); + // Binary + Map bhash = new HashMap(); + bhash.put(bbar, bcar); + bhash.put(bcar, bbar); + jedis.hmset(bfoo, bhash); - assertEquals(0, jedis.hlen(bbar).intValue()); - assertEquals(2, jedis.hlen(bfoo).intValue()); + assertEquals(0, jedis.hlen(bbar).intValue()); + assertEquals(2, jedis.hlen(bfoo).intValue()); } @Test public void hkeys() { - Map hash = new LinkedHashMap(); - hash.put("bar", "car"); - hash.put("car", "bar"); - jedis.hmset("foo", hash); + Map hash = new LinkedHashMap(); + hash.put("bar", "car"); + hash.put("car", "bar"); + jedis.hmset("foo", hash); - Set keys = jedis.hkeys("foo"); - Set expected = new LinkedHashSet(); - expected.add("bar"); - expected.add("car"); - assertEquals(expected, keys); + Set keys = jedis.hkeys("foo"); + Set expected = new LinkedHashSet(); + expected.add("bar"); + expected.add("car"); + assertEquals(expected, keys); - // Binary - Map bhash = new LinkedHashMap(); - bhash.put(bbar, bcar); - bhash.put(bcar, bbar); - jedis.hmset(bfoo, bhash); + // Binary + Map bhash = new LinkedHashMap(); + bhash.put(bbar, bcar); + bhash.put(bcar, bbar); + jedis.hmset(bfoo, bhash); - Set bkeys = jedis.hkeys(bfoo); - Set bexpected = new LinkedHashSet(); - bexpected.add(bbar); - bexpected.add(bcar); - assertEquals(bexpected, bkeys); + Set bkeys = jedis.hkeys(bfoo); + Set bexpected = new LinkedHashSet(); + bexpected.add(bbar); + bexpected.add(bcar); + assertEquals(bexpected, bkeys); } @Test public void hvals() { - Map hash = new LinkedHashMap(); - hash.put("bar", "car"); - hash.put("car", "bar"); - jedis.hmset("foo", hash); + Map hash = new LinkedHashMap(); + hash.put("bar", "car"); + hash.put("car", "bar"); + jedis.hmset("foo", hash); - List vals = jedis.hvals("foo"); - assertEquals(2, vals.size()); - assertTrue(vals.contains("bar")); - assertTrue(vals.contains("car")); + List vals = jedis.hvals("foo"); + assertEquals(2, vals.size()); + assertTrue(vals.contains("bar")); + assertTrue(vals.contains("car")); - // Binary - Map bhash = new LinkedHashMap(); - bhash.put(bbar, bcar); - bhash.put(bcar, bbar); - jedis.hmset(bfoo, bhash); + // Binary + Map bhash = new LinkedHashMap(); + bhash.put(bbar, bcar); + bhash.put(bcar, bbar); + jedis.hmset(bfoo, bhash); - List bvals = jedis.hvals(bfoo); + List bvals = jedis.hvals(bfoo); - assertEquals(2, bvals.size()); - assertTrue(arrayContains(bvals, bbar)); - assertTrue(arrayContains(bvals, bcar)); + assertEquals(2, bvals.size()); + assertTrue(arrayContains(bvals, bbar)); + assertTrue(arrayContains(bvals, bcar)); } @Test public void hgetAll() { - Map h = new HashMap(); - h.put("bar", "car"); - h.put("car", "bar"); - jedis.hmset("foo", h); + Map h = new HashMap(); + h.put("bar", "car"); + h.put("car", "bar"); + jedis.hmset("foo", h); - Map hash = jedis.hgetAll("foo"); - assertEquals(2, hash.size()); - assertEquals("car", hash.get("bar")); - assertEquals("bar", hash.get("car")); + Map hash = jedis.hgetAll("foo"); + assertEquals(2, hash.size()); + assertEquals("car", hash.get("bar")); + assertEquals("bar", hash.get("car")); - // Binary - Map bh = new HashMap(); - bh.put(bbar, bcar); - bh.put(bcar, bbar); - jedis.hmset(bfoo, bh); - Map bhash = jedis.hgetAll(bfoo); + // Binary + Map bh = new HashMap(); + bh.put(bbar, bcar); + bh.put(bcar, bbar); + jedis.hmset(bfoo, bh); + Map bhash = jedis.hgetAll(bfoo); - assertEquals(2, bhash.size()); - assertArrayEquals(bcar, bhash.get(bbar)); - assertArrayEquals(bbar, bhash.get(bcar)); + assertEquals(2, bhash.size()); + assertArrayEquals(bcar, bhash.get(bbar)); + assertArrayEquals(bbar, bhash.get(bcar)); + } + + @Test + public void hscan() { + jedis.hset("foo", "b", "b"); + jedis.hset("foo", "a", "a"); + + ScanResult> result = jedis.hscan("foo", 0); + + assertEquals(0, result.getCursor()); + assertFalse(result.getResult().isEmpty()); + } + + @Test + public void hscanMatch() { + ScanParams params = new ScanParams(); + params.match("a*"); + + jedis.hset("foo", "b", "b"); + jedis.hset("foo", "a", "a"); + jedis.hset("foo", "aa", "aa"); + ScanResult> result = jedis.hscan("foo", 0, params); + + assertEquals(0, result.getCursor()); + assertFalse(result.getResult().isEmpty()); + } + + @Test + public void hscanCount() { + ScanParams params = new ScanParams(); + params.count(2); + + for (int i = 0; i < 10; i++) { + jedis.hset("foo", "a" + i, "a" + i); + } + + ScanResult> result = jedis.hscan("foo", 0, 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 eff71ec..7d6930b 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/SetCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/SetCommandsTest.java @@ -2,10 +2,14 @@ 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; +import redis.clients.jedis.ScanParams; +import redis.clients.jedis.ScanResult; + public class SetCommandsTest extends JedisCommandTestBase { final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; @@ -448,7 +452,40 @@ public class SetCommandsTest extends JedisCommandTestBase { 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()); + assertFalse(result.getResult().isEmpty()); + } + + @Test + public void sscanMatch() { + ScanParams params = new ScanParams(); + params.match("a*"); + + jedis.sadd("foo", "b", "a", "aa"); + ScanResult result = jedis.sscan("foo", 0, params); + + assertEquals(0, result.getCursor()); + assertFalse(result.getResult().isEmpty()); + } + + @Test + public void sscanCount() { + ScanParams params = new ScanParams(); + params.count(2); + + jedis.sadd("foo", "a1", "a2", "a3", "a4", "a5"); + + ScanResult result = jedis.sscan("foo", 0, params); + + assertFalse(result.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 65b8155..c7d652e 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/SortedSetCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/SortedSetCommandsTest.java @@ -5,6 +5,8 @@ import java.util.Set; import org.junit.Test; +import redis.clients.jedis.ScanParams; +import redis.clients.jedis.ScanResult; import redis.clients.jedis.Tuple; import redis.clients.jedis.ZParams; import redis.clients.util.SafeEncoder; @@ -885,4 +887,46 @@ public class SortedSetCommandsTest extends JedisCommandTestBase { 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()); + assertFalse(result.getResult().isEmpty()); + } + + @Test + public void zscanMatch() { + ScanParams params = new ScanParams(); + params.match("a*"); + + jedis.zadd("foo", 2, "b"); + jedis.zadd("foo", 1, "a"); + jedis.zadd("foo", 11, "aa"); + ScanResult result = jedis.zscan("foo", 0, params); + + assertEquals(0, result.getCursor()); + assertFalse(result.getResult().isEmpty()); + } + + @Test + public void zscanCount() { + ScanParams params = new ScanParams(); + params.count(2); + + jedis.zadd("foo", 1, "a1"); + jedis.zadd("foo", 2, "a2"); + jedis.zadd("foo", 3, "a3"); + jedis.zadd("foo", 4, "a4"); + jedis.zadd("foo", 5, "a5"); + + ScanResult result = jedis.zscan("foo", 0, params); + + assertFalse(result.getResult().isEmpty()); + } } \ No newline at end of file From 58123034f5bf5ab51fce77980ab447f13bdac02e Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Tue, 3 Dec 2013 17:43:15 -0500 Subject: [PATCH 18/70] make pubsub test fast --- .../PublishSubscribeCommandsTest.java | 225 +++--------------- 1 file changed, 32 insertions(+), 193 deletions(-) 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 de60084..3ea14d5 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java @@ -16,21 +16,22 @@ import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.util.SafeEncoder; public class PublishSubscribeCommandsTest extends JedisCommandTestBase { - @Test - public void subscribe() throws InterruptedException { + private void publishOne(final String channel, final String message) { Thread t = new Thread(new Runnable() { public void run() { try { Jedis j = createJedis(); - Thread.sleep(1000); - j.publish("foo", "exit"); + j.publish(channel, message); j.disconnect(); } catch (Exception ex) { - fail(ex.getMessage()); } } }); t.start(); + } + + @Test + public void subscribe() throws InterruptedException { jedis.subscribe(new JedisPubSub() { public void onMessage(String channel, String message) { assertEquals("foo", channel); @@ -41,6 +42,9 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { public void onSubscribe(String channel, int subscribedChannels) { assertEquals("foo", channel); assertEquals(1, subscribedChannels); + + //now that I'm subscribed... publish + publishOne("foo", "exit"); } public void onUnsubscribe(String channel, int subscribedChannels) { @@ -58,33 +62,18 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { String message) { } }, "foo"); - t.join(); } @Test public void subscribeMany() throws UnknownHostException, IOException, InterruptedException { - Thread t = new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - Thread.sleep(1000); - j.publish("foo", "exit"); - Thread.sleep(1000); - j.publish("bar", "exit"); - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }); - t.start(); jedis.subscribe(new JedisPubSub() { public void onMessage(String channel, String message) { unsubscribe(channel); } public void onSubscribe(String channel, int subscribedChannels) { + publishOne(channel, "exit"); } public void onUnsubscribe(String channel, int subscribedChannels) { @@ -100,25 +89,11 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { String message) { } }, "foo", "bar"); - t.join(); } @Test public void psubscribe() throws UnknownHostException, IOException, InterruptedException { - Thread t = new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - Thread.sleep(1000); - j.publish("foo.bar", "exit"); - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }); - t.start(); jedis.psubscribe(new JedisPubSub() { public void onMessage(String channel, String message) { } @@ -132,6 +107,8 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { public void onPSubscribe(String pattern, int subscribedChannels) { assertEquals("foo.*", pattern); assertEquals(1, subscribedChannels); + publishOne("foo.bar", "exit"); + } public void onPUnsubscribe(String pattern, int subscribedChannels) { @@ -147,27 +124,11 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { punsubscribe(); } }, "foo.*"); - t.join(); } @Test public void psubscribeMany() throws UnknownHostException, IOException, InterruptedException { - Thread t = new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - Thread.sleep(1000); - j.publish("foo.123", "exit"); - Thread.sleep(1000); - j.publish("bar.123", "exit"); - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }); - t.start(); jedis.psubscribe(new JedisPubSub() { public void onMessage(String channel, String message) { } @@ -179,6 +140,7 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { } public void onPSubscribe(String pattern, int subscribedChannels) { + publishOne(pattern.replace("*", "123"), "exit"); } public void onPUnsubscribe(String pattern, int subscribedChannels) { @@ -189,7 +151,6 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { punsubscribe(pattern); } }, "foo.*", "bar.*"); - t.join(); } @Test @@ -201,12 +162,18 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { } public void onSubscribe(String channel, int subscribedChannels) { + publishOne(channel, "exit"); + if (!channel.equals("bar")) { + this.subscribe("bar"); + this.psubscribe("bar.*"); + } } public void onUnsubscribe(String channel, int subscribedChannels) { } public void onPSubscribe(String pattern, int subscribedChannels) { + publishOne(pattern.replace("*", "123"), "exit"); } public void onPUnsubscribe(String pattern, int subscribedChannels) { @@ -218,44 +185,12 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { } }; - Thread t = new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - Thread.sleep(1000); - pubsub.subscribe("bar"); - pubsub.psubscribe("bar.*"); - j.publish("foo", "exit"); - j.publish("bar", "exit"); - j.publish("bar.123", "exit"); - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }); - t.start(); jedis.subscribe(pubsub, "foo"); - t.join(); } @Test public void binarySubscribe() throws UnknownHostException, IOException, InterruptedException { - Thread t = new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - Thread.sleep(1000); - j.publish(SafeEncoder.encode("foo"), - SafeEncoder.encode("exit")); - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }); - t.start(); jedis.subscribe(new BinaryJedisPubSub() { public void onMessage(byte[] channel, byte[] message) { assertTrue(Arrays.equals(SafeEncoder.encode("foo"), channel)); @@ -266,6 +201,7 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { public void onSubscribe(byte[] channel, int subscribedChannels) { assertTrue(Arrays.equals(SafeEncoder.encode("foo"), channel)); assertEquals(1, subscribedChannels); + publishOne(SafeEncoder.encode(channel), "exit"); } public void onUnsubscribe(byte[] channel, int subscribedChannels) { @@ -283,35 +219,18 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { byte[] message) { } }, SafeEncoder.encode("foo")); - t.join(); } @Test public void binarySubscribeMany() throws UnknownHostException, IOException, InterruptedException { - Thread t = new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - Thread.sleep(1000); - j.publish(SafeEncoder.encode("foo"), - SafeEncoder.encode("exit")); - Thread.sleep(1000); - j.publish(SafeEncoder.encode("bar"), - SafeEncoder.encode("exit")); - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }); - t.start(); jedis.subscribe(new BinaryJedisPubSub() { public void onMessage(byte[] channel, byte[] message) { unsubscribe(channel); } public void onSubscribe(byte[] channel, int subscribedChannels) { + publishOne(SafeEncoder.encode(channel), "exit"); } public void onUnsubscribe(byte[] channel, int subscribedChannels) { @@ -327,26 +246,11 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { byte[] message) { } }, SafeEncoder.encode("foo"), SafeEncoder.encode("bar")); - t.join(); } @Test public void binaryPsubscribe() throws UnknownHostException, IOException, InterruptedException { - Thread t = new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - Thread.sleep(1000); - j.publish(SafeEncoder.encode("foo.bar"), - SafeEncoder.encode("exit")); - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }); - t.start(); jedis.psubscribe(new BinaryJedisPubSub() { public void onMessage(byte[] channel, byte[] message) { } @@ -360,6 +264,7 @@ 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"); } public void onPUnsubscribe(byte[] pattern, int subscribedChannels) { @@ -376,29 +281,11 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { punsubscribe(); } }, SafeEncoder.encode("foo.*")); - t.join(); } @Test public void binaryPsubscribeMany() throws UnknownHostException, IOException, InterruptedException { - Thread t = new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - Thread.sleep(1000); - j.publish(SafeEncoder.encode("foo.123"), - SafeEncoder.encode("exit")); - Thread.sleep(1000); - j.publish(SafeEncoder.encode("bar.123"), - SafeEncoder.encode("exit")); - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }); - t.start(); jedis.psubscribe(new BinaryJedisPubSub() { public void onMessage(byte[] channel, byte[] message) { } @@ -410,6 +297,7 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { } public void onPSubscribe(byte[] pattern, int subscribedChannels) { + publishOne(SafeEncoder.encode(pattern).replace("*", "123"), "exit"); } public void onPUnsubscribe(byte[] pattern, int subscribedChannels) { @@ -420,7 +308,6 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { punsubscribe(pattern); } }, SafeEncoder.encode("foo.*"), SafeEncoder.encode("bar.*")); - t.join(); } @Test @@ -432,12 +319,19 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { } public void onSubscribe(byte[] channel, int subscribedChannels) { + publishOne(SafeEncoder.encode(channel), "exit"); + + if(!SafeEncoder.encode(channel).equals("bar")) { + this.subscribe(SafeEncoder.encode("bar")); + this.psubscribe(SafeEncoder.encode("bar.*")); + } } public void onUnsubscribe(byte[] channel, int subscribedChannels) { } public void onPSubscribe(byte[] pattern, int subscribedChannels) { + publishOne(SafeEncoder.encode(pattern).replace("*", "123"), "exit"); } public void onPUnsubscribe(byte[] pattern, int subscribedChannels) { @@ -449,61 +343,7 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { } }; - Thread t = new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - Thread.sleep(1000); - pubsub.subscribe(SafeEncoder.encode("bar")); - pubsub.psubscribe(SafeEncoder.encode("bar.*")); - j.publish(SafeEncoder.encode("foo"), - SafeEncoder.encode("exit")); - j.publish(SafeEncoder.encode("bar"), - SafeEncoder.encode("exit")); - j.publish(SafeEncoder.encode("bar.123"), - SafeEncoder.encode("exit")); - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }); - t.start(); jedis.subscribe(pubsub, SafeEncoder.encode("foo")); - t.join(); - } - - @Test - @Ignore - public void subscribeWithoutConnecting() { - try { - Jedis jedis = new Jedis(hnp.getHost(), hnp.getPort()); - jedis.subscribe(new JedisPubSub() { - public void onMessage(String channel, String message) { - } - - public void onPMessage(String pattern, String channel, - String message) { - } - - public void onSubscribe(String channel, int subscribedChannels) { - } - - public void onUnsubscribe(String channel, int subscribedChannels) { - } - - public void onPUnsubscribe(String pattern, - int subscribedChannels) { - } - - public void onPSubscribe(String pattern, int subscribedChannels) { - } - }, "foo"); - } catch (NullPointerException ex) { - fail(); - } catch (JedisDataException ex) { - // this is OK because we are not sending AUTH command - } } @Test(expected = JedisConnectionException.class) @@ -570,7 +410,7 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { // client-output-buffer exceed // System.out.println("channel - " + channel + // " / message - " + message); - Thread.sleep(500); + Thread.sleep(100); } catch (Exception e) { try { t.join(); @@ -598,13 +438,12 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase { String message) { } }, "foo"); - t.join(); } finally { // exit the publisher thread. if exception is thrown, thread might // still keep publishing things. exit.set(true); if (t.isAlive()) { - t.wait(); + t.join(); } } } From ceac8123d6ea04c190891efffc8ad349a9afa69b Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Tue, 3 Dec 2013 17:54:35 -0500 Subject: [PATCH 19/70] make control command tests fast --- .../java/redis/clients/jedis/BinaryJedis.java | 1 + .../tests/commands/ControlCommandsTest.java | 21 +++---------------- 2 files changed, 4 insertions(+), 18 deletions(-) diff --git a/src/main/java/redis/clients/jedis/BinaryJedis.java b/src/main/java/redis/clients/jedis/BinaryJedis.java index 385b1c0..597e305 100644 --- a/src/main/java/redis/clients/jedis/BinaryJedis.java +++ b/src/main/java/redis/clients/jedis/BinaryJedis.java @@ -2860,6 +2860,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey */ public void monitor(final JedisMonitor jedisMonitor) { client.monitor(); + client.getStatusCodeReply(); jedisMonitor.proceed(client); } 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 4ae64df..00612bb 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ControlCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ControlCommandsTest.java @@ -45,18 +45,8 @@ public class ControlCommandsTest extends JedisCommandTestBase { @Test public void lastsave() throws InterruptedException { - long before = jedis.lastsave(); - String st = ""; - while (!st.equals("OK")) { - try { - Thread.sleep(1000); - st = jedis.save(); - } catch (JedisDataException e) { - - } - } - long after = jedis.lastsave(); - assertTrue((after - before) > 0); + long saved = jedis.lastsave(); + assertTrue(saved > 0); } @Test @@ -73,14 +63,9 @@ public class ControlCommandsTest extends JedisCommandTestBase { public void run() { Jedis j = new Jedis("localhost"); j.auth("foobared"); - for (int i = 0; i < 4; i++) { + for (int i = 0; i < 5; i++) { j.incr("foobared"); } - try { - Thread.sleep(2500); - } catch (InterruptedException e) { - } - j.incr("foobared"); j.disconnect(); } }).start(); From e17d24c7108bfcc4ece55a386df1e4720fe438d9 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Tue, 3 Dec 2013 18:20:49 -0500 Subject: [PATCH 20/70] make list command tests fast --- .../redis/clients/jedis/tests/commands/ListCommandsTest.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 5653687..079ab3f 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ListCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ListCommandsTest.java @@ -434,6 +434,8 @@ public class ListCommandsTest extends JedisCommandTestBase { }).start(); result = jedis.blpop(1, "foo"); + System.out.println("sddssddssd"); + assertNotNull(result); assertEquals(2, result.size()); assertEquals("foo", result.get(0)); @@ -594,7 +596,7 @@ public class ListCommandsTest extends JedisCommandTestBase { (new Thread(new Runnable() { public void run() { try { - Thread.sleep(2000); + Thread.sleep(100); Jedis j = createJedis(); j.lpush("foo", "a"); } catch (InterruptedException e) { From ce3497e34172509e9c341f37895a5e1e00e981b6 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Tue, 3 Dec 2013 18:28:31 -0500 Subject: [PATCH 21/70] make object command tests fast --- .../clients/jedis/tests/commands/ObjectCommandsTest.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/test/java/redis/clients/jedis/tests/commands/ObjectCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/ObjectCommandsTest.java index 0713753..1da4331 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ObjectCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ObjectCommandsTest.java @@ -36,14 +36,11 @@ public class ObjectCommandsTest extends JedisCommandTestBase { public void objectIdletime() throws InterruptedException { jedis.lpush(key, "hello world"); - // Wait a little bit more than 10 seconds so the idle time is 10 - // seconds. - Thread.sleep(10001); Long time = jedis.objectIdletime(key); - assertEquals(new Long(10), time); + assertEquals(new Long(0), time); // Binary time = jedis.objectIdletime(binaryKey); - assertEquals(new Long(10), time); + assertEquals(new Long(0), time); } } \ No newline at end of file From 20d686ec943ecc59f7c9f86741812284eb656d37 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Tue, 3 Dec 2013 18:43:34 -0500 Subject: [PATCH 22/70] make list command tests even faster --- .../tests/commands/ListCommandsTest.java | 60 +++---------------- 1 file changed, 7 insertions(+), 53 deletions(-) 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 079ab3f..d5fa0b6 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ListCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ListCommandsTest.java @@ -421,20 +421,9 @@ public class ListCommandsTest extends JedisCommandTestBase { List result = jedis.blpop(1, "foo"); assertNull(result); - new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - j.lpush("foo", "bar"); - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }).start(); - + jedis.lpush("foo", "bar"); result = jedis.blpop(1, "foo"); - System.out.println("sddssddssd"); + System.out.println("lalalala"); assertNotNull(result); assertEquals(2, result.size()); @@ -442,22 +431,10 @@ public class ListCommandsTest extends JedisCommandTestBase { assertEquals("bar", result.get(1)); // Binary + jedis.lpush(bfoo, bbar); List bresult = jedis.blpop(1, bfoo); - assertNull(bresult); + System.out.println("lalalala"); - new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - j.lpush(bfoo, bbar); - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }).start(); - - bresult = jedis.blpop(1, bfoo); assertNotNull(bresult); assertEquals(2, bresult.size()); assertArrayEquals(bfoo, bresult.get(0)); @@ -470,18 +447,8 @@ public class ListCommandsTest extends JedisCommandTestBase { List result = jedis.brpop(1, "foo"); assertNull(result); - new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - j.lpush("foo", "bar"); - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }).start(); + jedis.lpush("foo", "bar"); result = jedis.brpop(1, "foo"); assertNotNull(result); assertEquals(2, result.size()); @@ -489,22 +456,9 @@ public class ListCommandsTest extends JedisCommandTestBase { assertEquals("bar", result.get(1)); // Binary + + jedis.lpush(bfoo, bbar); List bresult = jedis.brpop(1, bfoo); - assertNull(bresult); - - new Thread(new Runnable() { - public void run() { - try { - Jedis j = createJedis(); - j.lpush(bfoo, bbar); - j.disconnect(); - } catch (Exception ex) { - fail(ex.getMessage()); - } - } - }).start(); - - bresult = jedis.brpop(1, bfoo); assertNotNull(bresult); assertEquals(2, bresult.size()); assertArrayEquals(bfoo, bresult.get(0)); From 4a4768b1d2dca39c9a31decb7206ef72c7332e4e Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Tue, 3 Dec 2013 19:03:19 -0500 Subject: [PATCH 23/70] speed up JedisSentinelTest --- Makefile | 1 + .../jedis/tests/JedisSentinelTest.java | 33 +++++++------------ .../tests/commands/ListCommandsTest.java | 2 -- 3 files changed, 13 insertions(+), 23 deletions(-) diff --git a/Makefile b/Makefile index 6df68af..da91267 100644 --- a/Makefile +++ b/Makefile @@ -60,6 +60,7 @@ pidfile /tmp/redis6.pid logfile /tmp/redis6.log save "" appendonly no +slaveof localhost 6379 endef define REDIS_SENTINEL1 diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java b/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java index 8912a1c..f8267c8 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java @@ -1,6 +1,5 @@ package redis.clients.jedis.tests; -import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -10,15 +9,14 @@ import org.junit.Test; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; -import redis.clients.jedis.tests.utils.JedisSentinelTestUtil; public class JedisSentinelTest extends JedisTestBase { private static final String MASTER_NAME = "mymaster"; 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); @@ -28,25 +26,16 @@ public class JedisSentinelTest extends JedisTestBase { @Before public void setup() throws InterruptedException { - masterJedis = new Jedis(master.getHost(), master.getPort()); - slaveJedis = new Jedis(slave.getHost(), slave.getPort()); - slaveJedis.auth("foobared"); - slaveJedis.configSet("masterauth", "foobared"); - slaveJedis.slaveof(master.getHost(), master.getPort()); - - List slaves = new ArrayList(); - slaves.add(slave); - - JedisSentinelTestUtil.waitForSentinelRecognizeRedisReplication( - sentinel, MASTER_NAME, master, slaves); } @After public void clear() throws InterruptedException { - // New Sentinel (after 2.8.1) - // when slave promoted to master (slave of no one), New Sentinel force to restore it (demote) - // so, promote(slaveof) slave to master has no effect, not same to old Sentinel's behavior + // New Sentinel (after 2.8.1) + // when slave promoted to master (slave of no one), New Sentinel force + // to restore it (demote) + // so, promote(slaveof) slave to master has no effect, not same to old + // Sentinel's behavior } @Test @@ -59,13 +48,15 @@ public class JedisSentinelTest extends JedisTestBase { List masterHostAndPort = j .sentinelGetMasterAddrByName(masterName); - HostAndPort masterFromSentinel = new HostAndPort(masterHostAndPort.get(0), - Integer.parseInt(masterHostAndPort.get(1))); + HostAndPort masterFromSentinel = new HostAndPort( + masterHostAndPort.get(0), Integer.parseInt(masterHostAndPort + .get(1))); assertEquals(master, masterFromSentinel); List> slaves = j.sentinelSlaves(masterName); 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)); 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 d5fa0b6..296877b 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ListCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ListCommandsTest.java @@ -423,7 +423,6 @@ public class ListCommandsTest extends JedisCommandTestBase { jedis.lpush("foo", "bar"); result = jedis.blpop(1, "foo"); - System.out.println("lalalala"); assertNotNull(result); assertEquals(2, result.size()); @@ -433,7 +432,6 @@ public class ListCommandsTest extends JedisCommandTestBase { // Binary jedis.lpush(bfoo, bbar); List bresult = jedis.blpop(1, bfoo); - System.out.println("lalalala"); assertNotNull(bresult); assertEquals(2, bresult.size()); From 3b7127c8111dc68b585517a2119e9a8f385c5a87 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Tue, 3 Dec 2013 19:06:53 -0500 Subject: [PATCH 24/70] make JedisTest fast --- src/test/java/redis/clients/jedis/tests/JedisTest.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/test/java/redis/clients/jedis/tests/JedisTest.java b/src/test/java/redis/clients/jedis/tests/JedisTest.java index bfa71ea..b123b05 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisTest.java @@ -52,9 +52,7 @@ public class JedisTest extends JedisCommandTestBase { jedis = new Jedis("localhost", 6379, 15000); jedis.auth("foobared"); jedis.configSet("timeout", "1"); - // we need to sleep a long time since redis check for idle connections - // every 10 seconds or so - Thread.sleep(20000); + Thread.sleep(2000); jedis.hmget("foobar", "foo"); } From 8624d1695d11ef4d7e2f526acfdae5c9f1912698 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Tue, 3 Dec 2013 19:47:15 -0500 Subject: [PATCH 25/70] make JedisSentinelPool fast --- Makefile | 2 + .../jedis/tests/JedisSentinelPoolTest.java | 97 +++++++++++-------- 2 files changed, 59 insertions(+), 40 deletions(-) diff --git a/Makefile b/Makefile index da91267..a6e9912 100644 --- a/Makefile +++ b/Makefile @@ -38,6 +38,7 @@ pidfile /tmp/redis4.pid logfile /tmp/redis4.log save "" appendonly no +slaveof localhost 6381 endef define REDIS5_CONF @@ -49,6 +50,7 @@ pidfile /tmp/redis5.pid logfile /tmp/redis5.log save "" appendonly no +slaveof localhost 6381 endef define REDIS6_CONF diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java index 97a02ed..c3a72a0 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java @@ -1,9 +1,8 @@ package redis.clients.jedis.tests; -import java.util.ArrayList; import java.util.HashSet; -import java.util.List; import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.junit.Before; @@ -12,8 +11,8 @@ 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.tests.utils.JedisSentinelTestUtil; public class JedisSentinelPoolTest extends JedisTestBase { private static final String MASTER_NAME = "mymaster"; @@ -29,43 +28,16 @@ public class JedisSentinelPoolTest extends JedisTestBase { protected static HostAndPort sentinel2 = HostAndPortUtil .getSentinelServers().get(2); - protected static Jedis masterJedis; - protected static Jedis slaveJedis1; - protected static Jedis slaveJedis2; protected static Jedis sentinelJedis1; - protected static Jedis sentinelJedis2; protected Set sentinels = new HashSet(); @Before public void setUp() throws Exception { - - // set up master and slaves - masterJedis = new Jedis(master.getHost(), master.getPort()); - masterJedis.auth("foobared"); - masterJedis.slaveofNoOne(); - - slaveJedis1 = new Jedis(slave1.getHost(), slave1.getPort()); - slaveJedis1.auth("foobared"); - slaveJedis1.slaveof(master.getHost(), master.getPort()); - - slaveJedis2 = new Jedis(slave2.getHost(), slave2.getPort()); - slaveJedis2.auth("foobared"); - slaveJedis2.slaveof(master.getHost(), master.getPort()); - sentinels.add(sentinel1.toString()); sentinels.add(sentinel2.toString()); - List slaves = new ArrayList(); - slaves.add(slave1); - slaves.add(slave2); - - JedisSentinelTestUtil.waitForSentinelRecognizeRedisReplication( - sentinel1, MASTER_NAME, master, slaves); - JedisSentinelTestUtil.waitForSentinelRecognizeRedisReplication( - sentinel2, MASTER_NAME, master, slaves); - - // No need to wait for sentinels to recognize each other + sentinelJedis1 = new Jedis(sentinel1.getHost(), sentinel1.getPort()); } @Test @@ -106,17 +78,62 @@ public class JedisSentinelPoolTest extends JedisTestBase { private void waitForFailover(JedisSentinelPool pool, HostAndPort oldMaster) throws InterruptedException { - HostAndPort newMaster = JedisSentinelTestUtil.waitForNewPromotedMaster( - sentinel1, MASTER_NAME, oldMaster); - JedisSentinelTestUtil.waitForNewPromotedMaster(sentinel2, MASTER_NAME, - oldMaster); - JedisSentinelTestUtil.waitForSentinelsRecognizeEachOthers(); - waitForJedisSentinelPoolRecognizeNewMaster(pool, newMaster); + waitForJedisSentinelPoolRecognizeNewMaster(pool); } private void waitForJedisSentinelPoolRecognizeNewMaster( - JedisSentinelPool pool, HostAndPort newMaster) - throws InterruptedException { + JedisSentinelPool pool) throws InterruptedException { + + final AtomicReference newmaster = new AtomicReference( + ""); + + sentinelJedis1.psubscribe(new JedisPubSub() { + + @Override + public void onMessage(String channel, String message) { + // TODO Auto-generated method stub + + } + + @Override + public void onPMessage(String pattern, String channel, + String message) { + if (channel.equals("+switch-master")) { + newmaster.set(message); + punsubscribe(); + } + // 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 + + } + }, "*"); + + String[] chunks = newmaster.get().split(" "); + HostAndPort newMaster = new HostAndPort(chunks[3], + Integer.parseInt(chunks[4])); while (true) { String host = pool.getCurrentHostMaster().getHost(); @@ -128,7 +145,7 @@ public class JedisSentinelPoolTest extends JedisTestBase { System.out .println("JedisSentinelPool's master is not yet changed, sleep..."); - Thread.sleep(1000); + Thread.sleep(100); } } From 46734e646ab3504c40839c84f5906a62d05e7000 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Thu, 5 Dec 2013 09:35:13 -0500 Subject: [PATCH 26/70] add WAIT command --- .../java/redis/clients/jedis/BasicCommands.java | 2 ++ .../java/redis/clients/jedis/BinaryClient.java | 4 ++++ .../java/redis/clients/jedis/BinaryJedis.java | 13 +++++++++++++ src/main/java/redis/clients/jedis/Commands.java | 17 ++++++++++------- src/main/java/redis/clients/jedis/Jedis.java | 2 +- src/main/java/redis/clients/jedis/Protocol.java | 2 +- .../tests/commands/ControlCommandsTest.java | 6 ++++++ 7 files changed, 37 insertions(+), 9 deletions(-) diff --git a/src/main/java/redis/clients/jedis/BasicCommands.java b/src/main/java/redis/clients/jedis/BasicCommands.java index 482d43b..5b7e995 100644 --- a/src/main/java/redis/clients/jedis/BasicCommands.java +++ b/src/main/java/redis/clients/jedis/BasicCommands.java @@ -39,4 +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/BinaryClient.java b/src/main/java/redis/clients/jedis/BinaryClient.java index 428fe72..dff1e76 100644 --- a/src/main/java/redis/clients/jedis/BinaryClient.java +++ b/src/main/java/redis/clients/jedis/BinaryClient.java @@ -1131,4 +1131,8 @@ public class BinaryClient extends Connection { 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/BinaryJedis.java b/src/main/java/redis/clients/jedis/BinaryJedis.java index 597e305..92a99a2 100644 --- a/src/main/java/redis/clients/jedis/BinaryJedis.java +++ b/src/main/java/redis/clients/jedis/BinaryJedis.java @@ -3366,4 +3366,17 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey return (relpy != null ? new Double(relpy) : null); } + /** + * Syncrhonous replication of Redis as described here: + * http://antirez.com/news/66 + * + * Since Java Object class has implemented "wait" method, we cannot use it, + * 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(); + } + } diff --git a/src/main/java/redis/clients/jedis/Commands.java b/src/main/java/redis/clients/jedis/Commands.java index 898dcdd..e4e22ec 100644 --- a/src/main/java/redis/clients/jedis/Commands.java +++ b/src/main/java/redis/clients/jedis/Commands.java @@ -1,14 +1,15 @@ package redis.clients.jedis; -import redis.clients.jedis.BinaryClient.LIST_POSITION; - import java.util.Map; +import redis.clients.jedis.BinaryClient.LIST_POSITION; + public interface Commands { public void set(final String key, final String value); - public void set(final String key, final String value, final String nxxx, final String expx, final long time); + public void set(final String key, final String value, final String nxxx, + final String expx, final long time); public void get(final String key); @@ -295,12 +296,14 @@ public interface Commands { public void bitcount(final String key, long start, long end); public void bitop(BitOP op, final String destKey, String... srcKeys); - + public void scan(int cursor, final ScanParams params); - + public void hscan(final String key, int cursor, final ScanParams params); - + public void sscan(final String key, int cursor, final ScanParams params); - + public void zscan(final String key, int 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 200632a..4ef5c4f 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -14,7 +14,7 @@ import redis.clients.jedis.BinaryClient.LIST_POSITION; import redis.clients.util.SafeEncoder; import redis.clients.util.Slowlog; -public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommands, AdvancedJedisCommands, ScriptingCommands { +public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommands, AdvancedJedisCommands, ScriptingCommands, BasicCommands { public Jedis(final String host) { super(host); } diff --git a/src/main/java/redis/clients/jedis/Protocol.java b/src/main/java/redis/clients/jedis/Protocol.java index 5eca2c5..354d158 100644 --- a/src/main/java/redis/clients/jedis/Protocol.java +++ b/src/main/java/redis/clients/jedis/Protocol.java @@ -158,7 +158,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; + DUMP, RESTORE, PEXPIRE, PEXPIREAT, PTTL, INCRBYFLOAT, PSETEX, CLIENT, TIME, MIGRATE, HINCRBYFLOAT, SCAN, HSCAN, SSCAN, ZSCAN, WAIT; public final byte[] raw; 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 00612bb..832cd6c 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ControlCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ControlCommandsTest.java @@ -112,4 +112,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()); + } } \ No newline at end of file From a8987ed865e1034f83d1e6a3ef681582ccb8a614 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Sat, 7 Dec 2013 17:55:17 -0300 Subject: [PATCH 27/70] Add first test to thorw MovedDataException when receiving MOVED from a cluster node --- Makefile | 2 +- .../java/redis/clients/jedis/BinaryJedis.java | 2 +- .../redis/clients/jedis/JedisCluster.java | 738 +++++++++++++++++- .../java/redis/clients/jedis/JedisPool.java | 2 +- .../java/redis/clients/jedis/Protocol.java | 12 +- .../exceptions/JedisMovedDataException.java | 17 + .../clients/jedis/tests/JedisClusterTest.java | 15 +- 7 files changed, 775 insertions(+), 13 deletions(-) create mode 100644 src/main/java/redis/clients/jedis/exceptions/JedisMovedDataException.java diff --git a/Makefile b/Makefile index e0189f2..8e45570 100644 --- a/Makefile +++ b/Makefile @@ -181,7 +181,7 @@ stop: test: make start - mvn clean compile test + mvn -Dtest=${TEST} clean compile test make stop deploy: diff --git a/src/main/java/redis/clients/jedis/BinaryJedis.java b/src/main/java/redis/clients/jedis/BinaryJedis.java index 385b1c0..2d8dead 100644 --- a/src/main/java/redis/clients/jedis/BinaryJedis.java +++ b/src/main/java/redis/clients/jedis/BinaryJedis.java @@ -1697,7 +1697,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."); } } diff --git a/src/main/java/redis/clients/jedis/JedisCluster.java b/src/main/java/redis/clients/jedis/JedisCluster.java index 7b5613b..4586b8f 100644 --- a/src/main/java/redis/clients/jedis/JedisCluster.java +++ b/src/main/java/redis/clients/jedis/JedisCluster.java @@ -1,5 +1,739 @@ package redis.clients.jedis; -public class JedisCluster { - public static final int HASH_SLOTS = 16384; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.Set; + +import redis.clients.jedis.BinaryClient.LIST_POSITION; +import redis.clients.util.Pool; + +public class JedisCluster implements JedisCommands, BasicCommands { + + public static final short HASHSLOTS = 16384; + private static final int DEFAULT_TIMEOUT = 1; + + private Map nodes = new HashMap(); + + public JedisCluster(Set nodes, int timeout) { + initializeSlotsCache(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); + } + + } + + public JedisCluster(Set nodes) { + this(nodes, DEFAULT_TIMEOUT); + } + + + @Override + public String set(String key, String value) { + return getRandomConnection().set(key, value); + } + + @Override + public String get(String key) { + return getRandomConnection().get(key); + } + + @Override + public Boolean exists(String key) { + return getRandomConnection().exists(key); + } + + @Override + public Long persist(String key) { + return getRandomConnection().persist(key); + } + + @Override + public String type(String key) { + return getRandomConnection().type(key); + } + + @Override + public Long expire(String key, int seconds) { + return getRandomConnection().expire(key, seconds); + } + + @Override + public Long expireAt(String key, long unixTime) { + return getRandomConnection().expireAt(key, unixTime); + } + + @Override + public Long ttl(String key) { + return getRandomConnection().ttl(key); + } + + @Override + public Boolean setbit(String key, long offset, boolean value) { + return getRandomConnection().setbit(key, offset, value); + } + + @Override + public Boolean setbit(String key, long offset, String value) { + return getRandomConnection().setbit(key, offset, value); + } + + @Override + public Boolean getbit(String key, long offset) { + return getRandomConnection().getbit(key, offset); + } + + @Override + public Long setrange(String key, long offset, String value) { + return getRandomConnection().setrange(key, offset, value); + } + + @Override + public String getrange(String key, long startOffset, long endOffset) { + return getRandomConnection().getrange(key, startOffset, endOffset); + } + + @Override + public String getSet(String key, String value) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long setnx(String key, String value) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String setex(String key, int seconds, String value) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long decrBy(String key, long integer) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long decr(String key) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long incrBy(String key, long integer) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long incr(String key) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long append(String key, String value) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String substr(String key, int start, int end) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long hset(String key, String field, String value) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String hget(String key, String field) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long hsetnx(String key, String field, String value) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String hmset(String key, Map hash) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List hmget(String key, String... fields) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long hincrBy(String key, String field, long value) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Boolean hexists(String key, String field) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long hdel(String key, String... field) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long hlen(String key) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set hkeys(String key) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List hvals(String key) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Map hgetAll(String key) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long rpush(String key, String... string) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long lpush(String key, String... string) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long llen(String key) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List lrange(String key, long start, long end) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String ltrim(String key, long start, long end) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String lindex(String key, long index) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String lset(String key, long index, String value) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long lrem(String key, long count, String value) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String lpop(String key) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String rpop(String key) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long sadd(String key, String... member) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set smembers(String key) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long srem(String key, String... member) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String spop(String key) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long scard(String key) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Boolean sismember(String key, String member) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String srandmember(String key) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long strlen(String key) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long zadd(String key, double score, String member) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long zadd(String key, Map scoreMembers) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set zrange(String key, long start, long end) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long zrem(String key, String... member) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Double zincrby(String key, double score, String member) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long zrank(String key, String member) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long zrevrank(String key, String member) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set zrevrange(String key, long start, long end) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set zrangeWithScores(String key, long start, long end) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set zrevrangeWithScores(String key, long start, long end) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long zcard(String key) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Double zscore(String key, String member) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List sort(String key) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List sort(String key, SortingParams sortingParameters) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long zcount(String key, double min, double max) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long zcount(String key, String min, String max) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set zrangeByScore(String key, double min, double max) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set zrangeByScore(String key, String min, String max) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set zrevrangeByScore(String key, double max, double min) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set zrangeByScore(String key, double min, double max, + int offset, int count) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set zrevrangeByScore(String key, String max, String min) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set zrangeByScore(String key, String min, String max, + int offset, int count) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set zrevrangeByScore(String key, double max, double min, + int offset, int count) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set zrangeByScoreWithScores(String key, double min, double max) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set zrevrangeByScoreWithScores(String key, double max, + double min) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set zrangeByScoreWithScores(String key, double min, + double max, int offset, int count) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set zrevrangeByScore(String key, String max, String min, + int offset, int count) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set zrangeByScoreWithScores(String key, String min, String max) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set zrevrangeByScoreWithScores(String key, String max, + String min) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set zrangeByScoreWithScores(String key, String min, + String max, int offset, int count) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set zrevrangeByScoreWithScores(String key, double max, + double min, int offset, int count) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set zrevrangeByScoreWithScores(String key, String max, + String min, int offset, int count) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long zremrangeByRank(String key, long start, long end) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long zremrangeByScore(String key, double start, double end) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long zremrangeByScore(String key, String start, String end) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long linsert(String key, LIST_POSITION where, String pivot, + String value) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long lpushx(String key, String... string) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long rpushx(String key, String... string) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List blpop(String arg) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List brpop(String arg) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long del(String key) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String echo(String string) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long move(String key, int dbIndex) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long bitcount(String key) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long bitcount(String key, long start, long end) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String ping() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String quit() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String flushDB() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long dbSize() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String select(int index) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String flushAll() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String auth(String password) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String save() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String bgsave() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String bgrewriteaof() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long lastsave() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String shutdown() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String info() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String info(String section) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String slaveof(String host, int port) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String slaveofNoOne() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Long getDB() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String debug(DebugParams params) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String configResetStat() { + // TODO Auto-generated method stub + return null; + } + + + @SuppressWarnings("unchecked") + private Jedis getRandomConnection() { + Object[] nodeArray = nodes.values().toArray(); + return ((Pool) nodeArray[new Random().nextInt(nodeArray.length)]).getResource(); + } + + + } diff --git a/src/main/java/redis/clients/jedis/JedisPool.java b/src/main/java/redis/clients/jedis/JedisPool.java index 58212ba..6511207 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")) { diff --git a/src/main/java/redis/clients/jedis/Protocol.java b/src/main/java/redis/clients/jedis/Protocol.java index a3eacd6..123edc4 100644 --- a/src/main/java/redis/clients/jedis/Protocol.java +++ b/src/main/java/redis/clients/jedis/Protocol.java @@ -6,13 +6,15 @@ import java.util.List; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.exceptions.JedisMovedDataException; import redis.clients.util.RedisInputStream; import redis.clients.util.RedisOutputStream; import redis.clients.util.SafeEncoder; public final class Protocol { - public static final int DEFAULT_PORT = 6379; + private static final String MOVED_RESPONSE = "MOVED"; + 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; @@ -72,8 +74,12 @@ public final class Protocol { } private static void processError(final RedisInputStream is) { - String message = is.readLine(); - throw new JedisDataException(message); + String message = is.readLine(); + //TODO: Read only first 5 bytes? + if (message.contains(MOVED_RESPONSE)) { + throw new JedisMovedDataException(message); + } + throw new JedisDataException(message); } private static Object process(final RedisInputStream is) { diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisMovedDataException.java b/src/main/java/redis/clients/jedis/exceptions/JedisMovedDataException.java new file mode 100644 index 0000000..78e0a4b --- /dev/null +++ b/src/main/java/redis/clients/jedis/exceptions/JedisMovedDataException.java @@ -0,0 +1,17 @@ +package redis.clients.jedis.exceptions; + +public class JedisMovedDataException extends JedisDataException { + private static final long serialVersionUID = 3878126572474819403L; + + public JedisMovedDataException(String message) { + super(message); + } + + public JedisMovedDataException(Throwable cause) { + super(cause); + } + + public JedisMovedDataException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java index ca90362..68ad4eb 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java @@ -1,5 +1,7 @@ package redis.clients.jedis.tests; +import java.util.HashSet; + import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -9,6 +11,7 @@ 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.JedisMovedDataException; public class JedisClusterTest extends Assert { private Jedis node1; @@ -42,7 +45,7 @@ public class JedisClusterTest extends Assert { // add all slots to node1 Pipeline pipelined = node1.pipelined(); - for (int i = 0; i < JedisCluster.HASH_SLOTS; i++) { + for (int i = 0; i < JedisCluster.HASHSLOTS; i++) { pipelined.clusterAddSlots(i); } pipelined.sync(); @@ -52,15 +55,17 @@ public class JedisClusterTest extends Assert { public void tearDown() { // clear all slots of node1 Pipeline pipelined = node1.pipelined(); - for (int i = 0; i < JedisCluster.HASH_SLOTS; i++) { + for (int i = 0; i < JedisCluster.HASHSLOTS; i++) { pipelined.clusterDelSlots(i); } pipelined.sync(); } - @Test - public void moved() { - //TODO: needs to implement + @Test(expected=JedisMovedDataException.class) + public void throwMovedExceptionTest() { + JedisCluster jc = new JedisCluster(new HashSet(HostAndPortUtil.getClusterServers())); + jc.set("foo", "bar"); + jc.get("foo"); } @Test From 726c3151b67c194d84c22e2e80fd3099249eecb7 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Sun, 8 Dec 2013 01:08:14 -0300 Subject: [PATCH 28/70] Add RedisSlot helper to calculate key slot --- .../clients/jedis/tests/JedisClusterTest.java | 21 +++++++++++++--- .../clients/jedis/tests/utils/RedisSlot.java | 25 +++++++++++++++++++ 2 files changed, 43 insertions(+), 3 deletions(-) create mode 100644 src/test/java/redis/clients/jedis/tests/utils/RedisSlot.java diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java index 68ad4eb..6e4a7cf 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java @@ -12,6 +12,7 @@ import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisCluster; import redis.clients.jedis.Pipeline; import redis.clients.jedis.exceptions.JedisMovedDataException; +import redis.clients.jedis.tests.utils.RedisSlot; public class JedisClusterTest extends Assert { private Jedis node1; @@ -68,8 +69,22 @@ public class JedisClusterTest extends Assert { jc.get("foo"); } - @Test - public void ask() { - //TODO: needs to implement +// @Test +// public void ask() { +// JedisCluster jc = new JedisCluster(new HashSet(HostAndPortUtil.getClusterServers())); +// jc.set("foo", "bar"); +// int keySlot = RedisSlot.getSlot("foo"); +// String node2Id = getNodeId(node2.clusterNodes()); +// node1.clusterSetSlotMigrating(keySlot, node2Id); +// node1.get("foo"); +// } + + private String getNodeId(String infoOutput) { + for (String infoLine : infoOutput.split("\n")) { + if (infoLine.contains("myself")) { + return infoLine.split(" ")[0]; + } + } + return ""; } } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/utils/RedisSlot.java b/src/test/java/redis/clients/jedis/tests/utils/RedisSlot.java new file mode 100644 index 0000000..1dd76c3 --- /dev/null +++ b/src/test/java/redis/clients/jedis/tests/utils/RedisSlot.java @@ -0,0 +1,25 @@ +package redis.clients.jedis.tests.utils; + +public class RedisSlot { + public final static int polynomial = 0x1021; // Represents x^16+x^12+x^5+1 + static int crc; + + public RedisSlot(){ + crc = 0x0000; + } + + public static int getSlot(String key) { + 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 From 10c131bbf0629d5a1a30c7968926b9bee99cc949 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Mon, 9 Dec 2013 10:54:53 +0900 Subject: [PATCH 29/70] 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 0ebbf02c944308fdb367dfd4e0373534b0975838 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Mon, 9 Dec 2013 15:17:13 -0300 Subject: [PATCH 30/70] Change Moved cluster test and add confirmation for jedis cluster tests --- .../exceptions/JedisAskDataException.java | 17 ++++ .../clients/jedis/tests/JedisClusterTest.java | 85 ++++++++++--------- 2 files changed, 62 insertions(+), 40 deletions(-) create mode 100644 src/main/java/redis/clients/jedis/exceptions/JedisAskDataException.java diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisAskDataException.java b/src/main/java/redis/clients/jedis/exceptions/JedisAskDataException.java new file mode 100644 index 0000000..158256d --- /dev/null +++ b/src/main/java/redis/clients/jedis/exceptions/JedisAskDataException.java @@ -0,0 +1,17 @@ +package redis.clients.jedis.exceptions; + +public class JedisAskDataException extends JedisDataException { + private static final long serialVersionUID = 3878126572474819403L; + + public JedisAskDataException(String message) { + super(message); + } + + public JedisAskDataException(Throwable cause) { + super(cause); + } + + public JedisAskDataException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java index 6e4a7cf..b465be8 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java @@ -1,7 +1,5 @@ package redis.clients.jedis.tests; -import java.util.HashSet; - import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -11,6 +9,7 @@ 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.JedisMovedDataException; import redis.clients.jedis.tests.utils.RedisSlot; @@ -24,55 +23,61 @@ public class JedisClusterTest extends Assert { private HostAndPort nodeInfo3 = HostAndPortUtil.getClusterServers().get(2); @Before - public void setUp() { - node1 = new Jedis(nodeInfo1.getHost(), nodeInfo1.getPort()); - node1.connect(); - node1.flushAll(); - - node2 = new Jedis(nodeInfo2.getHost(), nodeInfo2.getPort()); - node2.connect(); - node2.flushAll(); - - node3 = new Jedis(nodeInfo3.getHost(), nodeInfo3.getPort()); - node3.connect(); - node3.flushAll(); - - // ---- 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()); - - // add all slots to node1 - Pipeline pipelined = node1.pipelined(); - for (int i = 0; i < JedisCluster.HASHSLOTS; i++) { - pipelined.clusterAddSlots(i); - } - pipelined.sync(); + public void setUp() throws InterruptedException { + node1 = new Jedis(nodeInfo1.getHost(), nodeInfo1.getPort()); + node1.connect(); + node1.flushAll(); + + node2 = new Jedis(nodeInfo2.getHost(), nodeInfo2.getPort()); + node2.connect(); + node2.flushAll(); + + node3 = new Jedis(nodeInfo3.getHost(), nodeInfo3.getPort()); + node3.connect(); + node3.flushAll(); + + // ---- 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()); + + // add all slots to node1 + Pipeline pipelined = node1.pipelined(); + for (int i = 0; i < JedisCluster.HASHSLOTS; i++) { + pipelined.clusterAddSlots(i); + } + pipelined.sync(); + + boolean clusterOk = false; + while (!clusterOk) { + if (node1.clusterInfo().split("\n")[0].contains("ok")) { + clusterOk = true; + } + Thread.sleep(100); + } } @After public void tearDown() { - // clear all slots of node1 - Pipeline pipelined = node1.pipelined(); - for (int i = 0; i < JedisCluster.HASHSLOTS; i++) { - pipelined.clusterDelSlots(i); - } - pipelined.sync(); + // clear all slots of node1 + Pipeline pipelined = node1.pipelined(); + for (int i = 0; i < JedisCluster.HASHSLOTS; i++) { + pipelined.clusterDelSlots(i); + } + pipelined.sync(); } @Test(expected=JedisMovedDataException.class) public void throwMovedExceptionTest() { - JedisCluster jc = new JedisCluster(new HashSet(HostAndPortUtil.getClusterServers())); - jc.set("foo", "bar"); - jc.get("foo"); + node1.set("foo", "bar"); + node2.get("foo"); } -// @Test +// @Test(expected=JedisAskDataException.class) // public void ask() { -// JedisCluster jc = new JedisCluster(new HashSet(HostAndPortUtil.getClusterServers())); -// jc.set("foo", "bar"); +// node1.set("foo", "bar"); // int keySlot = RedisSlot.getSlot("foo"); // String node2Id = getNodeId(node2.clusterNodes()); // node1.clusterSetSlotMigrating(keySlot, node2Id); From c00807004592abf6868b4cc61f1ccaa690c0fe13 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Tue, 10 Dec 2013 10:25:41 -0300 Subject: [PATCH 31/70] Add JedisClusterCommand and updated code to use it respectively --- .../redis/clients/jedis/JedisCluster.java | 140 ++++++++++++------ .../clients/jedis/JedisClusterCommand.java | 23 +++ .../jedis/JedisClusterConnectionHandler.java | 33 +++++ .../clients/jedis/tests/JedisClusterTest.java | 4 +- 4 files changed, 156 insertions(+), 44 deletions(-) create mode 100644 src/main/java/redis/clients/jedis/JedisClusterCommand.java create mode 100644 src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java diff --git a/src/main/java/redis/clients/jedis/JedisCluster.java b/src/main/java/redis/clients/jedis/JedisCluster.java index 4586b8f..a3b6f22 100644 --- a/src/main/java/redis/clients/jedis/JedisCluster.java +++ b/src/main/java/redis/clients/jedis/JedisCluster.java @@ -1,32 +1,25 @@ package redis.clients.jedis; -import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Random; import java.util.Set; import redis.clients.jedis.BinaryClient.LIST_POSITION; -import redis.clients.util.Pool; public class JedisCluster implements JedisCommands, BasicCommands { public static final short HASHSLOTS = 16384; private static final int DEFAULT_TIMEOUT = 1; - private Map nodes = new HashMap(); + + private JedisClusterConnectionHandler connectionHandler; public JedisCluster(Set nodes, int timeout) { - initializeSlotsCache(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); - } + connectionHandler = new JedisClusterConnectionHandler(nodes); } + + public JedisCluster(Set nodes) { this(nodes, DEFAULT_TIMEOUT); @@ -34,68 +27,133 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override - public String set(String key, String value) { - return getRandomConnection().set(key, value); + public String set(final String key, final String value) { + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getRandomConnection().set(key, value); + } + }.run(); } @Override - public String get(String key) { - return getRandomConnection().get(key); + public String get(final String key) { + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getRandomConnection().get(key); + } + }.run(); } @Override - public Boolean exists(String key) { - return getRandomConnection().exists(key); + public Boolean exists(final String key) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Boolean execute() { + return connectionHandler.getRandomConnection().exists(key); + } + }.run(); } @Override - public Long persist(String key) { - return getRandomConnection().persist(key); + public Long persist(final String key) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getRandomConnection().persist(key); + } + }.run(); } @Override - public String type(String key) { - return getRandomConnection().type(key); + public String type(final String key) { + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getRandomConnection().type(key); + } + }.run(); } @Override - public Long expire(String key, int seconds) { - return getRandomConnection().expire(key, seconds); + public Long expire(final String key, final int seconds) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getRandomConnection().expire(key, seconds); + } + }.run(); } @Override - public Long expireAt(String key, long unixTime) { - return getRandomConnection().expireAt(key, unixTime); + public Long expireAt(final String key, final long unixTime) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getRandomConnection().expireAt(key, unixTime); + } + }.run(); } @Override - public Long ttl(String key) { - return getRandomConnection().ttl(key); + public Long ttl(final String key) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getRandomConnection().ttl(key); + } + }.run(); } @Override - public Boolean setbit(String key, long offset, boolean value) { - return getRandomConnection().setbit(key, offset, value); + public Boolean setbit(final String key, final long offset, final boolean value) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Boolean execute() { + return connectionHandler.getRandomConnection().setbit(key, offset, value); + } + }.run(); } @Override - public Boolean setbit(String key, long offset, String value) { - return getRandomConnection().setbit(key, offset, value); + public Boolean setbit(final String key, final long offset, final String value) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Boolean execute() { + return connectionHandler.getRandomConnection().setbit(key, offset, value); + } + }.run(); } @Override - public Boolean getbit(String key, long offset) { - return getRandomConnection().getbit(key, offset); + public Boolean getbit(final String key, final long offset) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Boolean execute() { + return connectionHandler.getRandomConnection().getbit(key, offset); + } + }.run(); } @Override - public Long setrange(String key, long offset, String value) { - return getRandomConnection().setrange(key, offset, value); + public Long setrange(final String key, final long offset, final String value) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getRandomConnection().setrange(key, offset, value); + } + }.run(); } @Override - public String getrange(String key, long startOffset, long endOffset) { - return getRandomConnection().getrange(key, startOffset, endOffset); + public String getrange(final String key, final long startOffset, final long endOffset) { + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getRandomConnection().getrange(key, startOffset, endOffset); + } + }.run(); } @Override @@ -728,11 +786,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { } - @SuppressWarnings("unchecked") - private Jedis getRandomConnection() { - Object[] nodeArray = nodes.values().toArray(); - return ((Pool) nodeArray[new Random().nextInt(nodeArray.length)]).getResource(); - } + diff --git a/src/main/java/redis/clients/jedis/JedisClusterCommand.java b/src/main/java/redis/clients/jedis/JedisClusterCommand.java new file mode 100644 index 0000000..55c9f29 --- /dev/null +++ b/src/main/java/redis/clients/jedis/JedisClusterCommand.java @@ -0,0 +1,23 @@ +package redis.clients.jedis; + +import redis.clients.jedis.exceptions.JedisMovedDataException; + +public abstract class JedisClusterCommand { + + private JedisClusterConnectionHandler connectionHandler; + + public JedisClusterCommand(JedisClusterConnectionHandler connectionHandler) { + this.connectionHandler = connectionHandler; + } + + public abstract T execute(); + + public T run() { + try { + return execute(); + } catch (JedisMovedDataException e) { + //TODO: Retry here + } + return null; + } +} diff --git a/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java new file mode 100644 index 0000000..d942723 --- /dev/null +++ b/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java @@ -0,0 +1,33 @@ +package redis.clients.jedis; + +import java.util.HashMap; +import java.util.Map; +import java.util.Random; +import java.util.Set; + +import redis.clients.util.Pool; + +public class JedisClusterConnectionHandler { + + private Map nodes = new HashMap(); + + public JedisClusterConnectionHandler(Set nodes) { + initializeSlotsCache(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); + } + + } + + @SuppressWarnings("unchecked") + public Jedis getRandomConnection() { + Object[] nodeArray = nodes.values().toArray(); + return ((Pool) nodeArray[new Random().nextInt(nodeArray.length)]).getResource(); + } + +} diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java index b465be8..204b4f8 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java @@ -52,7 +52,9 @@ public class JedisClusterTest extends Assert { boolean clusterOk = false; while (!clusterOk) { - if (node1.clusterInfo().split("\n")[0].contains("ok")) { + if (node1.clusterInfo().split("\n")[0].contains("ok") && + node2.clusterInfo().split("\n")[0].contains("ok") && + node3.clusterInfo().split("\n")[0].contains("ok") ) { clusterOk = true; } Thread.sleep(100); From 3073f778b4edab3205b922c22f29cfed490c494e Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Sat, 21 Dec 2013 01:33:46 +0900 Subject: [PATCH 32/70] 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 0bc27ac3a298b34d72aabe1afa985fd816a71fa0 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Fri, 20 Dec 2013 15:28:32 -0300 Subject: [PATCH 33/70] Refactor redis cluster connection handler and add JedisAskDataException handling --- .../redis/clients/jedis/JedisCluster.java | 28 ++++++++-------- .../jedis/JedisClusterConnectionHandler.java | 29 ++-------------- .../jedis/JedisRandomConnectionHandler.java | 33 +++++++++++++++++++ .../java/redis/clients/jedis/Protocol.java | 7 +++- .../clients/jedis/tests/JedisClusterTest.java | 15 ++++----- .../clients/jedis/tests/utils/RedisSlot.java | 4 +++ 6 files changed, 66 insertions(+), 50 deletions(-) create mode 100644 src/main/java/redis/clients/jedis/JedisRandomConnectionHandler.java diff --git a/src/main/java/redis/clients/jedis/JedisCluster.java b/src/main/java/redis/clients/jedis/JedisCluster.java index a3b6f22..3c82d8c 100644 --- a/src/main/java/redis/clients/jedis/JedisCluster.java +++ b/src/main/java/redis/clients/jedis/JedisCluster.java @@ -15,7 +15,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { private JedisClusterConnectionHandler connectionHandler; public JedisCluster(Set nodes, int timeout) { - connectionHandler = new JedisClusterConnectionHandler(nodes); + connectionHandler = new JedisRandomConnectionHandler(nodes); } @@ -31,7 +31,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getRandomConnection().set(key, value); + return connectionHandler.getConnection().set(key, value); } }.run(); } @@ -41,7 +41,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getRandomConnection().get(key); + return connectionHandler.getConnection().get(key); } }.run(); } @@ -51,7 +51,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Boolean execute() { - return connectionHandler.getRandomConnection().exists(key); + return connectionHandler.getConnection().exists(key); } }.run(); } @@ -61,7 +61,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getRandomConnection().persist(key); + return connectionHandler.getConnection().persist(key); } }.run(); } @@ -71,7 +71,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getRandomConnection().type(key); + return connectionHandler.getConnection().type(key); } }.run(); } @@ -81,7 +81,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getRandomConnection().expire(key, seconds); + return connectionHandler.getConnection().expire(key, seconds); } }.run(); } @@ -91,7 +91,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getRandomConnection().expireAt(key, unixTime); + return connectionHandler.getConnection().expireAt(key, unixTime); } }.run(); } @@ -101,7 +101,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getRandomConnection().ttl(key); + return connectionHandler.getConnection().ttl(key); } }.run(); } @@ -111,7 +111,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Boolean execute() { - return connectionHandler.getRandomConnection().setbit(key, offset, value); + return connectionHandler.getConnection().setbit(key, offset, value); } }.run(); } @@ -121,7 +121,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Boolean execute() { - return connectionHandler.getRandomConnection().setbit(key, offset, value); + return connectionHandler.getConnection().setbit(key, offset, value); } }.run(); } @@ -131,7 +131,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Boolean execute() { - return connectionHandler.getRandomConnection().getbit(key, offset); + return connectionHandler.getConnection().getbit(key, offset); } }.run(); } @@ -141,7 +141,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getRandomConnection().setrange(key, offset, value); + return connectionHandler.getConnection().setrange(key, offset, value); } }.run(); } @@ -151,7 +151,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getRandomConnection().getrange(key, startOffset, endOffset); + return connectionHandler.getConnection().getrange(key, startOffset, endOffset); } }.run(); } diff --git a/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java index d942723..d5aaf51 100644 --- a/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java +++ b/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java @@ -1,33 +1,8 @@ package redis.clients.jedis; -import java.util.HashMap; -import java.util.Map; -import java.util.Random; -import java.util.Set; -import redis.clients.util.Pool; - -public class JedisClusterConnectionHandler { - - private Map nodes = new HashMap(); +public interface JedisClusterConnectionHandler { - public JedisClusterConnectionHandler(Set nodes) { - initializeSlotsCache(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); - } - - } - - @SuppressWarnings("unchecked") - public Jedis getRandomConnection() { - Object[] nodeArray = nodes.values().toArray(); - return ((Pool) nodeArray[new Random().nextInt(nodeArray.length)]).getResource(); - } + Jedis getConnection(); } diff --git a/src/main/java/redis/clients/jedis/JedisRandomConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisRandomConnectionHandler.java new file mode 100644 index 0000000..f3da675 --- /dev/null +++ b/src/main/java/redis/clients/jedis/JedisRandomConnectionHandler.java @@ -0,0 +1,33 @@ +package redis.clients.jedis; + +import java.util.HashMap; +import java.util.Map; +import java.util.Random; +import java.util.Set; + +import redis.clients.util.Pool; + +public class JedisRandomConnectionHandler implements JedisClusterConnectionHandler { + + private Map nodes = new HashMap(); + + public JedisRandomConnectionHandler(Set nodes) { + initializeSlotsCache(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); + } + + } + + @SuppressWarnings("unchecked") + public Jedis getConnection() { + Object[] nodeArray = nodes.values().toArray(); + return ((Pool) nodeArray[new Random().nextInt(nodeArray.length)]).getResource(); + } + +} diff --git a/src/main/java/redis/clients/jedis/Protocol.java b/src/main/java/redis/clients/jedis/Protocol.java index 123edc4..7eecd25 100644 --- a/src/main/java/redis/clients/jedis/Protocol.java +++ b/src/main/java/redis/clients/jedis/Protocol.java @@ -4,6 +4,7 @@ import java.io.IOException; import java.util.ArrayList; import java.util.List; +import redis.clients.jedis.exceptions.JedisAskDataException; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.exceptions.JedisMovedDataException; @@ -13,6 +14,7 @@ import redis.clients.util.SafeEncoder; 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_SENTINEL_PORT = 26379; @@ -75,9 +77,12 @@ public final class Protocol { private static void processError(final RedisInputStream is) { String message = is.readLine(); - //TODO: Read only first 5 bytes? + //TODO: I'm not sure if this is the best way to do this. + //Maybe Read only first 5 bytes instead? if (message.contains(MOVED_RESPONSE)) { throw new JedisMovedDataException(message); + } else if (message.contains(ASK_RESPONSE)) { + throw new JedisAskDataException(message); } throw new JedisDataException(message); } diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java index 204b4f8..0f7c06c 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java @@ -77,14 +77,13 @@ public class JedisClusterTest extends Assert { node2.get("foo"); } -// @Test(expected=JedisAskDataException.class) -// public void ask() { -// node1.set("foo", "bar"); -// int keySlot = RedisSlot.getSlot("foo"); -// String node2Id = getNodeId(node2.clusterNodes()); -// node1.clusterSetSlotMigrating(keySlot, node2Id); -// node1.get("foo"); -// } + @Test(expected=JedisAskDataException.class) + public void ask() { + int keySlot = RedisSlot.getSlot("test"); + String node2Id = getNodeId(node2.clusterNodes()); + node1.clusterSetSlotMigrating(keySlot, node2Id); + node1.get("test"); + } private String getNodeId(String infoOutput) { for (String infoLine : infoOutput.split("\n")) { diff --git a/src/test/java/redis/clients/jedis/tests/utils/RedisSlot.java b/src/test/java/redis/clients/jedis/tests/utils/RedisSlot.java index 1dd76c3..61a98dd 100644 --- a/src/test/java/redis/clients/jedis/tests/utils/RedisSlot.java +++ b/src/test/java/redis/clients/jedis/tests/utils/RedisSlot.java @@ -22,4 +22,8 @@ public class RedisSlot { return crc &= 0xffff % 16384; } + public static void main(String[] args) { + System.out.println(getSlot("test")); + } + } \ No newline at end of file From af72248c221a6844b3e42e739d5bebc791de7940 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Fri, 20 Dec 2013 16:56:29 -0300 Subject: [PATCH 34/70] Implement all Jedis cluster commands and rename RedisSlot class --- .../redis/clients/jedis/JedisCluster.java | 1030 ++++++++++++----- .../clients/jedis/JedisClusterCommand.java | 7 +- .../clients/jedis/tests/JedisClusterTest.java | 6 +- ...{RedisSlot.java => JedisClusterCRC16.java} | 4 +- 4 files changed, 726 insertions(+), 321 deletions(-) rename src/test/java/redis/clients/jedis/tests/utils/{RedisSlot.java => JedisClusterCRC16.java} (92%) diff --git a/src/main/java/redis/clients/jedis/JedisCluster.java b/src/main/java/redis/clients/jedis/JedisCluster.java index 3c82d8c..460e032 100644 --- a/src/main/java/redis/clients/jedis/JedisCluster.java +++ b/src/main/java/redis/clients/jedis/JedisCluster.java @@ -18,8 +18,6 @@ public class JedisCluster implements JedisCommands, BasicCommands { connectionHandler = new JedisRandomConnectionHandler(nodes); } - - public JedisCluster(Set nodes) { this(nodes, DEFAULT_TIMEOUT); @@ -157,637 +155,1041 @@ public class JedisCluster implements JedisCommands, BasicCommands { } @Override - public String getSet(String key, String value) { - // TODO Auto-generated method stub - return null; + public String getSet(final String key, final String value) { + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().getSet(key, value); + } + }.run(); } @Override - public Long setnx(String key, String value) { - // TODO Auto-generated method stub - return null; + public Long setnx(final String key, final String value) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().setnx(key, value); + } + }.run(); } @Override - public String setex(String key, int seconds, String value) { - // TODO Auto-generated method stub - return null; + public String setex(final String key, final int seconds, final String value) { + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().setex(key, seconds, value); + } + }.run(); } @Override - public Long decrBy(String key, long integer) { - // TODO Auto-generated method stub - return null; + public Long decrBy(final String key, final long integer) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().decrBy(key, integer); + } + }.run(); } @Override - public Long decr(String key) { - // TODO Auto-generated method stub - return null; + public Long decr(final String key) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().decr(key); + } + }.run(); } @Override - public Long incrBy(String key, long integer) { - // TODO Auto-generated method stub - return null; + public Long incrBy(final String key, final long integer) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().incrBy(key, integer); + } + }.run(); } @Override - public Long incr(String key) { - // TODO Auto-generated method stub - return null; + public Long incr(final String key) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().incr(key); + } + }.run(); } @Override - public Long append(String key, String value) { - // TODO Auto-generated method stub - return null; + public Long append(final String key, final String value) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().append(key, value); + } + }.run(); } @Override - public String substr(String key, int start, int end) { - // TODO Auto-generated method stub - return null; + public String substr(final String key, final int start, final int end) { + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().substr(key, start, end); + } + }.run(); } @Override - public Long hset(String key, String field, String value) { - // TODO Auto-generated method stub - return null; + public Long hset(final String key, final String field, final String value) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().hset(key, field, value); + } + }.run(); } @Override - public String hget(String key, String field) { - // TODO Auto-generated method stub - return null; + public String hget(final String key, final String field) { + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().hget(key, field); + } + }.run(); } @Override - public Long hsetnx(String key, String field, String value) { - // TODO Auto-generated method stub - return null; + public Long hsetnx(final String key, final String field, final String value) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().hsetnx(key, field, value); + } + }.run(); } @Override - public String hmset(String key, Map hash) { - // TODO Auto-generated method stub - return null; + public String hmset(final String key, final Map hash) { + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().hmset(key, hash); + } + }.run(); } @Override - public List hmget(String key, String... fields) { - // TODO Auto-generated method stub - return null; + public List hmget(final String key, final String... fields) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public List execute() { + return connectionHandler.getConnection().hmget(key, fields); + } + }.run(); } @Override - public Long hincrBy(String key, String field, long value) { - // TODO Auto-generated method stub - return null; + public Long hincrBy(final String key, final String field, final long value) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().hincrBy(key, field, value); + } + }.run(); } @Override - public Boolean hexists(String key, String field) { - // TODO Auto-generated method stub - return null; + public Boolean hexists(final String key, final String field) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Boolean execute() { + return connectionHandler.getConnection().hexists(key, field); + } + }.run(); } @Override - public Long hdel(String key, String... field) { - // TODO Auto-generated method stub - return null; + public Long hdel(final String key, final String... field) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().hdel(key, field); + } + }.run(); } @Override - public Long hlen(String key) { - // TODO Auto-generated method stub - return null; + public Long hlen(final String key) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().hdel(key); + } + }.run(); } @Override - public Set hkeys(String key) { - // TODO Auto-generated method stub - return null; + public Set hkeys(final String key) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public Set execute() { + return connectionHandler.getConnection().hkeys(key); + } + }.run(); } @Override - public List hvals(String key) { - // TODO Auto-generated method stub - return null; + public List hvals(final String key) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public List execute() { + return connectionHandler.getConnection().hvals(key); + } + }.run(); } @Override - public Map hgetAll(String key) { - // TODO Auto-generated method stub - return null; + public Map hgetAll(final String key) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public Map execute() { + return connectionHandler.getConnection().hgetAll(key); + } + }.run(); } @Override - public Long rpush(String key, String... string) { - // TODO Auto-generated method stub - return null; + public Long rpush(final String key, final String... string) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().rpush(key, string); + } + }.run(); } @Override - public Long lpush(String key, String... string) { - // TODO Auto-generated method stub - return null; + public Long lpush(final String key, final String... string) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().lpush(key, string); + } + }.run(); } @Override - public Long llen(String key) { - // TODO Auto-generated method stub - return null; + public Long llen(final String key) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().llen(key); + } + }.run(); } @Override - public List lrange(String key, long start, long end) { - // TODO Auto-generated method stub - return null; + public List lrange(final String key, final long start, final long end) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public List execute() { + return connectionHandler.getConnection().lrange(key, start, end); + } + }.run(); } @Override - public String ltrim(String key, long start, long end) { - // TODO Auto-generated method stub - return null; + public String ltrim(final String key, final long start, final long end) { + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().ltrim(key, start, end); + } + }.run(); } @Override - public String lindex(String key, long index) { - // TODO Auto-generated method stub - return null; + public String lindex(final String key, final long index) { + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().lindex(key, index); + } + }.run(); } @Override - public String lset(String key, long index, String value) { - // TODO Auto-generated method stub - return null; + public String lset(final String key, final long index, final String value) { + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().lset(key, index, value); + } + }.run(); } @Override - public Long lrem(String key, long count, String value) { - // TODO Auto-generated method stub - return null; + public Long lrem(final String key, final long count, final String value) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().lrem(key, count, value); + } + }.run(); } @Override - public String lpop(String key) { - // TODO Auto-generated method stub - return null; + public String lpop(final String key) { + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().lpop(key); + } + }.run(); } @Override - public String rpop(String key) { - // TODO Auto-generated method stub - return null; + public String rpop(final String key) { + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().rpop(key); + } + }.run(); } @Override - public Long sadd(String key, String... member) { - // TODO Auto-generated method stub - return null; + public Long sadd(final String key, final String... member) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().sadd(key, member); + } + }.run(); } @Override - public Set smembers(String key) { - // TODO Auto-generated method stub - return null; + public Set smembers(final String key) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public Set execute() { + return connectionHandler.getConnection().smembers(key); + } + }.run(); } @Override - public Long srem(String key, String... member) { - // TODO Auto-generated method stub - return null; + public Long srem(final String key, final String... member) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().srem(key, member); + } + }.run(); } @Override - public String spop(String key) { - // TODO Auto-generated method stub - return null; + public String spop(final String key) { + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().spop(key); + } + }.run(); } @Override - public Long scard(String key) { - // TODO Auto-generated method stub - return null; + public Long scard(final String key) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().scard(key); + } + }.run(); } @Override - public Boolean sismember(String key, String member) { - // TODO Auto-generated method stub - return null; + public Boolean sismember(final String key, final String member) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Boolean execute() { + return connectionHandler.getConnection().sismember(key, member); + } + }.run(); } @Override - public String srandmember(String key) { - // TODO Auto-generated method stub - return null; + public String srandmember(final String key) { + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().srandmember(key); + } + }.run(); } @Override - public Long strlen(String key) { - // TODO Auto-generated method stub - return null; + public Long strlen(final String key) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().strlen(key); + } + }.run(); } @Override - public Long zadd(String key, double score, String member) { - // TODO Auto-generated method stub - return null; + public Long zadd(final String key, final double score, final String member) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().zadd(key, score, member); + } + }.run(); } @Override - public Long zadd(String key, Map scoreMembers) { - // TODO Auto-generated method stub - return null; + public Long zadd(final String key, final Map scoreMembers) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().zadd(key, scoreMembers); + } + }.run(); } @Override - public Set zrange(String key, long start, long end) { - // TODO Auto-generated method stub - return null; + public Set zrange(final String key, final long start, final long end) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public Set execute() { + return connectionHandler.getConnection().zrange(key, start, end); + } + }.run(); } @Override - public Long zrem(String key, String... member) { - // TODO Auto-generated method stub - return null; + public Long zrem(final String key, final String... member) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().zrem(key, member); + } + }.run(); } @Override - public Double zincrby(String key, double score, String member) { - // TODO Auto-generated method stub - return null; + public Double zincrby(final String key, final double score, final String member) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Double execute() { + return connectionHandler.getConnection().zincrby(key, score, member); + } + }.run(); } @Override - public Long zrank(String key, String member) { - // TODO Auto-generated method stub - return null; + public Long zrank(final String key, final String member) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().zrank(key, member); + } + }.run(); } @Override - public Long zrevrank(String key, String member) { - // TODO Auto-generated method stub - return null; + public Long zrevrank(final String key, final String member) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().zrevrank(key, member); + } + }.run(); } @Override - public Set zrevrange(String key, long start, long end) { - // TODO Auto-generated method stub - return null; + public Set zrevrange(final String key, final long start, final long end) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public Set execute() { + return connectionHandler.getConnection().zrevrange(key, start, end); + } + }.run(); } @Override - public Set zrangeWithScores(String key, long start, long end) { - // TODO Auto-generated method stub - return null; + public Set zrangeWithScores(final String key, final long start, final long end) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public Set execute() { + return connectionHandler.getConnection().zrangeWithScores(key, start, end); + } + }.run(); } @Override - public Set zrevrangeWithScores(String key, long start, long end) { - // TODO Auto-generated method stub - return null; + public Set zrevrangeWithScores(final String key, final long start, final long end) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public Set execute() { + return connectionHandler.getConnection().zrevrangeWithScores(key, start, end); + } + }.run(); } @Override - public Long zcard(String key) { - // TODO Auto-generated method stub - return null; + public Long zcard(final String key) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().zcard(key); + } + }.run(); } @Override - public Double zscore(String key, String member) { - // TODO Auto-generated method stub - return null; + public Double zscore(final String key, final String member) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Double execute() { + return connectionHandler.getConnection().zscore(key, member); + } + }.run(); } @Override - public List sort(String key) { - // TODO Auto-generated method stub - return null; + public List sort(final String key) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public List execute() { + return connectionHandler.getConnection().sort(key); + } + }.run(); } @Override - public List sort(String key, SortingParams sortingParameters) { - // TODO Auto-generated method stub - return null; + public List sort(final String key, final SortingParams sortingParameters) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public List execute() { + return connectionHandler.getConnection().sort(key, sortingParameters); + } + }.run(); } @Override - public Long zcount(String key, double min, double max) { - // TODO Auto-generated method stub - return null; + public Long zcount(final String key, final double min, final double max) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().zcount(key, min, max); + } + }.run(); } @Override - public Long zcount(String key, String min, String max) { - // TODO Auto-generated method stub - return null; + public Long zcount(final String key, final String min, final String max) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().zcount(key, min, max); + } + }.run(); } @Override - public Set zrangeByScore(String key, double min, double max) { - // TODO Auto-generated method stub - return null; + public Set zrangeByScore(final String key, final double min, final double max) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public Set execute() { + return connectionHandler.getConnection().zrangeByScore(key, min, max); + } + }.run(); } @Override - public Set zrangeByScore(String key, String min, String max) { - // TODO Auto-generated method stub - return null; + public Set zrangeByScore(final String key, final String min, final String max) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public Set execute() { + return connectionHandler.getConnection().zrangeByScore(key, min, max); + } + }.run(); } @Override - public Set zrevrangeByScore(String key, double max, double min) { - // TODO Auto-generated method stub - return null; + public Set zrevrangeByScore(final String key, final double max, final double min) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public Set execute() { + return connectionHandler.getConnection().zrevrangeByScore(key, min, max); + } + }.run(); } @Override - public Set zrangeByScore(String key, double min, double max, - int offset, int count) { - // TODO Auto-generated method stub - return null; + public Set zrangeByScore(final String key, final double min, final double max, + final int offset, final int count) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public Set execute() { + return connectionHandler.getConnection().zrangeByScore(key, min, max, offset, count); + } + }.run(); } @Override - public Set zrevrangeByScore(String key, String max, String min) { - // TODO Auto-generated method stub - return null; + public Set zrevrangeByScore(final String key, final String max, final String min) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public Set execute() { + return connectionHandler.getConnection().zrevrangeByScore(key, min, max); + } + }.run(); } @Override - public Set zrangeByScore(String key, String min, String max, - int offset, int count) { - // TODO Auto-generated method stub - return null; + public Set zrangeByScore(final String key, final String min, final String max, + final int offset, final int count) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public Set execute() { + return connectionHandler.getConnection().zrangeByScore(key, min, max, offset, count); + } + }.run(); } @Override - public Set zrevrangeByScore(String key, double max, double min, - int offset, int count) { - // TODO Auto-generated method stub - return null; + public Set zrevrangeByScore(final String key, final double max, final double min, + final int offset, final int count) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public Set execute() { + return connectionHandler.getConnection().zrevrangeByScore(key, min, max, offset, count); + } + }.run(); } @Override - public Set zrangeByScoreWithScores(String key, double min, double max) { - // TODO Auto-generated method stub - return null; + public Set zrangeByScoreWithScores(final String key, final double min, final double max) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public Set execute() { + return connectionHandler.getConnection().zrangeByScoreWithScores(key, min, max); + } + }.run(); } @Override - public Set zrevrangeByScoreWithScores(String key, double max, - double min) { - // TODO Auto-generated method stub - return null; + public Set zrevrangeByScoreWithScores(final String key, final double max, final double min) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public Set execute() { + return connectionHandler.getConnection().zrevrangeByScoreWithScores(key, min, max); + } + }.run(); } @Override - public Set zrangeByScoreWithScores(String key, double min, - double max, int offset, int count) { - // TODO Auto-generated method stub - return null; + public Set zrangeByScoreWithScores(final String key, final double min, final double max, final int offset, final int count) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public Set execute() { + return connectionHandler.getConnection().zrangeByScoreWithScores(key, min, max, offset, count); + } + }.run(); } @Override - public Set zrevrangeByScore(String key, String max, String min, - int offset, int count) { - // TODO Auto-generated method stub - return null; + public Set zrevrangeByScore(final String key, final String max, final String min, + final int offset, final int count) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public Set execute() { + return connectionHandler.getConnection().zrevrangeByScore(key, min, max, offset, count); + } + }.run(); } @Override - public Set zrangeByScoreWithScores(String key, String min, String max) { - // TODO Auto-generated method stub - return null; + public Set zrangeByScoreWithScores(final String key, final String min, final String max) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public Set execute() { + return connectionHandler.getConnection().zrangeByScoreWithScores(key, min, max); + } + }.run(); } @Override - public Set zrevrangeByScoreWithScores(String key, String max, - String min) { - // TODO Auto-generated method stub - return null; + public Set zrevrangeByScoreWithScores(final String key, final String max, + final String min) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public Set execute() { + return connectionHandler.getConnection().zrevrangeByScoreWithScores(key, min, max); + } + }.run(); } @Override - public Set zrangeByScoreWithScores(String key, String min, - String max, int offset, int count) { - // TODO Auto-generated method stub - return null; + public Set zrangeByScoreWithScores(final String key, final String min, + final String max, final int offset, final int count) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public Set execute() { + return connectionHandler.getConnection().zrangeByScoreWithScores(key, min, max, offset, count); + } + }.run(); } @Override - public Set zrevrangeByScoreWithScores(String key, double max, - double min, int offset, int count) { - // TODO Auto-generated method stub - return null; + public Set zrevrangeByScoreWithScores(final String key, final double max, + final double min, final int offset, final int count) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public Set execute() { + return connectionHandler.getConnection().zrevrangeByScoreWithScores(key, max, min, offset, count); + } + }.run(); } @Override - public Set zrevrangeByScoreWithScores(String key, String max, - String min, int offset, int count) { - // TODO Auto-generated method stub - return null; + public Set zrevrangeByScoreWithScores(final String key, final String max, + final String min, final int offset, final int count) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public Set execute() { + return connectionHandler.getConnection().zrevrangeByScoreWithScores(key, max, min, offset, count); + } + }.run(); } @Override - public Long zremrangeByRank(String key, long start, long end) { - // TODO Auto-generated method stub - return null; + public Long zremrangeByRank(final String key, final long start, final long end) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().zremrangeByRank(key, start, end); + } + }.run(); } @Override - public Long zremrangeByScore(String key, double start, double end) { - // TODO Auto-generated method stub - return null; + public Long zremrangeByScore(final String key, final double start, final double end) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().zremrangeByScore(key, start, end); + } + }.run(); } @Override - public Long zremrangeByScore(String key, String start, String end) { - // TODO Auto-generated method stub - return null; + public Long zremrangeByScore(final String key, final String start, final String end) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().zremrangeByScore(key, start, end); + } + }.run(); } @Override - public Long linsert(String key, LIST_POSITION where, String pivot, - String value) { - // TODO Auto-generated method stub - return null; + public Long linsert(final String key, final LIST_POSITION where, final String pivot, + final String value) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().linsert(key, where, pivot, value); + } + }.run(); } @Override - public Long lpushx(String key, String... string) { - // TODO Auto-generated method stub - return null; + public Long lpushx(final String key, final String... string) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().lpushx(key, string); + } + }.run(); } @Override - public Long rpushx(String key, String... string) { - // TODO Auto-generated method stub - return null; + public Long rpushx(final String key, final String... string) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().rpushx(key, string); + } + }.run(); } @Override - public List blpop(String arg) { - // TODO Auto-generated method stub - return null; + public List blpop(final String arg) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public List execute() { + return connectionHandler.getConnection().blpop(arg); + } + }.run(); } @Override - public List brpop(String arg) { - // TODO Auto-generated method stub - return null; + public List brpop(final String arg) { + return new JedisClusterCommand>(connectionHandler) { + @Override + public List execute() { + return connectionHandler.getConnection().brpop(arg); + } + }.run(); } @Override - public Long del(String key) { - // TODO Auto-generated method stub - return null; + public Long del(final String key) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().del(key); + } + }.run(); } @Override - public String echo(String string) { - // TODO Auto-generated method stub - return null; + public String echo(final String string) { + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().echo(string); + } + }.run(); } @Override - public Long move(String key, int dbIndex) { - // TODO Auto-generated method stub - return null; + public Long move(final String key, final int dbIndex) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().move(key, dbIndex); + } + }.run(); } @Override - public Long bitcount(String key) { - // TODO Auto-generated method stub - return null; + public Long bitcount(final String key) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().bitcount(key); + } + }.run(); } @Override - public Long bitcount(String key, long start, long end) { - // TODO Auto-generated method stub - return null; + public Long bitcount(final String key, final long start, final long end) { + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().bitcount(key, start, end); + } + }.run(); } @Override public String ping() { - // TODO Auto-generated method stub - return null; + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().ping(); + } + }.run(); } @Override public String quit() { - // TODO Auto-generated method stub - return null; + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().quit(); + } + }.run(); } @Override public String flushDB() { - // TODO Auto-generated method stub - return null; + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().flushDB(); + } + }.run(); } @Override public Long dbSize() { - // TODO Auto-generated method stub - return null; + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().dbSize(); + } + }.run(); } @Override - public String select(int index) { - // TODO Auto-generated method stub - return null; + public String select(final int index) { + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().select(index); + } + }.run(); } @Override public String flushAll() { - // TODO Auto-generated method stub - return null; + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().flushAll(); + } + }.run(); } @Override - public String auth(String password) { - // TODO Auto-generated method stub - return null; + public String auth(final String password) { + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().auth(password); + } + }.run(); } @Override public String save() { - // TODO Auto-generated method stub - return null; + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().save(); + } + }.run(); } @Override public String bgsave() { - // TODO Auto-generated method stub - return null; + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().bgsave(); + } + }.run(); } @Override public String bgrewriteaof() { - // TODO Auto-generated method stub - return null; + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().bgrewriteaof(); + } + }.run(); } @Override public Long lastsave() { - // TODO Auto-generated method stub - return null; + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().lastsave(); + } + }.run(); } @Override public String shutdown() { - // TODO Auto-generated method stub - return null; + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().shutdown(); + } + }.run(); } @Override public String info() { - // TODO Auto-generated method stub - return null; + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().info(); + } + }.run(); } @Override - public String info(String section) { - // TODO Auto-generated method stub - return null; + public String info(final String section) { + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().info(section); + } + }.run(); } @Override - public String slaveof(String host, int port) { - // TODO Auto-generated method stub - return null; + public String slaveof(final String host, final int port) { + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().slaveof(host, port); + } + }.run(); } @Override public String slaveofNoOne() { - // TODO Auto-generated method stub - return null; + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().slaveofNoOne(); + } + }.run(); } @Override public Long getDB() { - // TODO Auto-generated method stub - return null; + return new JedisClusterCommand(connectionHandler) { + @Override + public Long execute() { + return connectionHandler.getConnection().getDB(); + } + }.run(); } @Override - public String debug(DebugParams params) { - // TODO Auto-generated method stub - return null; + public String debug(final DebugParams params) { + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().debug(params); + } + }.run(); } @Override public String configResetStat() { - // TODO Auto-generated method stub - return null; + return new JedisClusterCommand(connectionHandler) { + @Override + public String execute() { + return connectionHandler.getConnection().configResetStat(); + } + }.run(); } - - - - - - } diff --git a/src/main/java/redis/clients/jedis/JedisClusterCommand.java b/src/main/java/redis/clients/jedis/JedisClusterCommand.java index 55c9f29..1d9aece 100644 --- a/src/main/java/redis/clients/jedis/JedisClusterCommand.java +++ b/src/main/java/redis/clients/jedis/JedisClusterCommand.java @@ -1,5 +1,6 @@ package redis.clients.jedis; +import redis.clients.jedis.exceptions.JedisAskDataException; import redis.clients.jedis.exceptions.JedisMovedDataException; public abstract class JedisClusterCommand { @@ -15,8 +16,10 @@ public abstract class JedisClusterCommand { public T run() { try { return execute(); - } catch (JedisMovedDataException e) { - //TODO: Retry here + } catch (JedisMovedDataException jme) { + //TODO: Do Retry here + } catch (JedisAskDataException jae) { + //TODO: Do ASK here } return null; } diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java index 0f7c06c..29f275d 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java @@ -11,7 +11,7 @@ import redis.clients.jedis.JedisCluster; import redis.clients.jedis.Pipeline; import redis.clients.jedis.exceptions.JedisAskDataException; import redis.clients.jedis.exceptions.JedisMovedDataException; -import redis.clients.jedis.tests.utils.RedisSlot; +import redis.clients.jedis.tests.utils.JedisClusterCRC16; public class JedisClusterTest extends Assert { private Jedis node1; @@ -78,8 +78,8 @@ public class JedisClusterTest extends Assert { } @Test(expected=JedisAskDataException.class) - public void ask() { - int keySlot = RedisSlot.getSlot("test"); + public void throwAskExceptionTest() { + int keySlot = JedisClusterCRC16.getSlot("test"); String node2Id = getNodeId(node2.clusterNodes()); node1.clusterSetSlotMigrating(keySlot, node2Id); node1.get("test"); diff --git a/src/test/java/redis/clients/jedis/tests/utils/RedisSlot.java b/src/test/java/redis/clients/jedis/tests/utils/JedisClusterCRC16.java similarity index 92% rename from src/test/java/redis/clients/jedis/tests/utils/RedisSlot.java rename to src/test/java/redis/clients/jedis/tests/utils/JedisClusterCRC16.java index 61a98dd..edf7e2c 100644 --- a/src/test/java/redis/clients/jedis/tests/utils/RedisSlot.java +++ b/src/test/java/redis/clients/jedis/tests/utils/JedisClusterCRC16.java @@ -1,10 +1,10 @@ package redis.clients.jedis.tests.utils; -public class RedisSlot { +public class JedisClusterCRC16 { public final static int polynomial = 0x1021; // Represents x^16+x^12+x^5+1 static int crc; - public RedisSlot(){ + public JedisClusterCRC16(){ crc = 0x0000; } From 53b3e041f3346e4c3ab879decc27673e9344a066 Mon Sep 17 00:00:00 2001 From: Jungtaek Lim Date: Mon, 23 Dec 2013 14:19:28 +0900 Subject: [PATCH 35/70] 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 9f767a084859fad71a6ab972973d2f73f3ae1098 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Fri, 27 Dec 2013 23:09:44 -0300 Subject: [PATCH 36/70] Add automatic discovery of cluster nodes --- .../redis/clients/jedis/JedisCluster.java | 6 +++ .../jedis/JedisClusterConnectionHandler.java | 43 ++++++++++++++++++- .../jedis/JedisRandomConnectionHandler.java | 15 +------ .../clients/jedis/tests/JedisClusterTest.java | 42 ++++++++++++++---- 4 files changed, 82 insertions(+), 24 deletions(-) diff --git a/src/main/java/redis/clients/jedis/JedisCluster.java b/src/main/java/redis/clients/jedis/JedisCluster.java index 460e032..9753815 100644 --- a/src/main/java/redis/clients/jedis/JedisCluster.java +++ b/src/main/java/redis/clients/jedis/JedisCluster.java @@ -1,5 +1,7 @@ package redis.clients.jedis; +import java.util.HashSet; +import java.util.IllegalFormatException; import java.util.List; import java.util.Map; import java.util.Set; @@ -1192,4 +1194,8 @@ public class JedisCluster implements JedisCommands, BasicCommands { } }.run(); } + + public Map getClusterNodes() { + return connectionHandler.getNodes(); + } } diff --git a/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java index d5aaf51..a28a23c 100644 --- a/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java +++ b/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java @@ -1,8 +1,47 @@ package redis.clients.jedis; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; -public interface JedisClusterConnectionHandler { + +public abstract class JedisClusterConnectionHandler { - Jedis getConnection(); + protected Map nodes = new HashMap(); + + abstract Jedis getConnection(); + + 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); + this.nodes.putAll(discoverClusterNodes(jp)); + } + } + + private Map discoverClusterNodes(JedisPool jp) { + Map discoveredNodes = new HashMap(); + String localNodes = jp.getResource().clusterNodes(); + for (String nodeInfo : localNodes.split("\n")) { + HostAndPort node = getHostAndPortFromNodeLine(nodeInfo); + JedisPool nodePool = new JedisPool(node.getHost(), node.getPort()); + discoveredNodes.put(node.getHost() + node.getPort(), nodePool); + } + return discoveredNodes; + } + + private HostAndPort getHostAndPortFromNodeLine(String nodeInfo) { + String stringHostAndPort = nodeInfo.split(" ",3)[1]; + String[] arrayHostAndPort = stringHostAndPort.split(":"); + return new HostAndPort(arrayHostAndPort[0], Integer.valueOf(arrayHostAndPort[1])); + } } diff --git a/src/main/java/redis/clients/jedis/JedisRandomConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisRandomConnectionHandler.java index f3da675..fc8226b 100644 --- a/src/main/java/redis/clients/jedis/JedisRandomConnectionHandler.java +++ b/src/main/java/redis/clients/jedis/JedisRandomConnectionHandler.java @@ -1,28 +1,17 @@ package redis.clients.jedis; -import java.util.HashMap; -import java.util.Map; import java.util.Random; import java.util.Set; import redis.clients.util.Pool; -public class JedisRandomConnectionHandler implements JedisClusterConnectionHandler { +public class JedisRandomConnectionHandler extends JedisClusterConnectionHandler { - private Map nodes = new HashMap(); public JedisRandomConnectionHandler(Set nodes) { - initializeSlotsCache(nodes); + super(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); - } - - } @SuppressWarnings("unchecked") public Jedis getConnection() { diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java index 29f275d..5162635 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java @@ -1,5 +1,8 @@ package redis.clients.jedis.tests; +import java.util.HashSet; +import java.util.Set; + import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -43,12 +46,24 @@ public class JedisClusterTest extends Assert { node1.clusterMeet("127.0.0.1", nodeInfo2.getPort()); node1.clusterMeet("127.0.0.1", nodeInfo3.getPort()); - // add all slots to node1 - Pipeline pipelined = node1.pipelined(); + // 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++) { - pipelined.clusterAddSlots(i); + if (i < slotsPerNode) { + pipeline1.clusterAddSlots(i); + } else if (i > slotsPerNode * 2) { + pipeline3.clusterAddSlots(i); + } else { + pipeline2.clusterAddSlots(i); + } } - pipelined.sync(); + pipeline1.sync(); + pipeline2.sync(); + pipeline3.sync(); + boolean clusterOk = false; while (!clusterOk) { @@ -72,19 +87,28 @@ public class JedisClusterTest extends Assert { } @Test(expected=JedisMovedDataException.class) - public void throwMovedExceptionTest() { + public void testThrowMovedException() { node1.set("foo", "bar"); node2.get("foo"); } @Test(expected=JedisAskDataException.class) - public void throwAskExceptionTest() { + public void testThrowAskException() { int keySlot = JedisClusterCRC16.getSlot("test"); - String node2Id = getNodeId(node2.clusterNodes()); - node1.clusterSetSlotMigrating(keySlot, node2Id); - node1.get("test"); + String node3Id = getNodeId(node3.clusterNodes()); + node2.clusterSetSlotMigrating(keySlot, node3Id); + node2.get("test"); } + @Test + public void testDiscoverNodesAutomatically() { + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); + JedisCluster jc = new JedisCluster(jedisClusterNode); + assertEquals(jc.getClusterNodes().size(), 3); + } + + private String getNodeId(String infoOutput) { for (String infoLine : infoOutput.split("\n")) { if (infoLine.contains("myself")) { From b2d22e206037eee2bebd5e4ec0dbe57692f8a57f Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Sat, 28 Dec 2013 00:59:35 -0300 Subject: [PATCH 37/70] Add slot based connection which routes requests according to key slot --- .../redis/clients/jedis/JedisCluster.java | 236 +++++++++--------- .../jedis/JedisClusterConnectionHandler.java | 32 ++- .../jedis/JedisRandomConnectionHandler.java | 2 +- .../JedisSlotBasedConnectionHandler.java | 30 +++ .../clients/jedis/tests/JedisClusterTest.java | 12 +- .../jedis/tests/utils/JedisClusterCRC16.java | 10 +- 6 files changed, 186 insertions(+), 136 deletions(-) create mode 100644 src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java diff --git a/src/main/java/redis/clients/jedis/JedisCluster.java b/src/main/java/redis/clients/jedis/JedisCluster.java index 9753815..b654be7 100644 --- a/src/main/java/redis/clients/jedis/JedisCluster.java +++ b/src/main/java/redis/clients/jedis/JedisCluster.java @@ -1,7 +1,5 @@ package redis.clients.jedis; -import java.util.HashSet; -import java.util.IllegalFormatException; import java.util.List; import java.util.Map; import java.util.Set; @@ -17,7 +15,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { private JedisClusterConnectionHandler connectionHandler; public JedisCluster(Set nodes, int timeout) { - connectionHandler = new JedisRandomConnectionHandler(nodes); + connectionHandler = new JedisSlotBasedConnectionHandler(nodes); } @@ -31,7 +29,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().set(key, value); + return connectionHandler.getConnection(key).set(key, value); } }.run(); } @@ -41,7 +39,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().get(key); + return connectionHandler.getConnection(key).get(key); } }.run(); } @@ -51,7 +49,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Boolean execute() { - return connectionHandler.getConnection().exists(key); + return connectionHandler.getConnection(key).exists(key); } }.run(); } @@ -61,7 +59,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().persist(key); + return connectionHandler.getConnection(key).persist(key); } }.run(); } @@ -71,7 +69,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().type(key); + return connectionHandler.getConnection(key).type(key); } }.run(); } @@ -81,7 +79,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().expire(key, seconds); + return connectionHandler.getConnection(key).expire(key, seconds); } }.run(); } @@ -91,7 +89,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().expireAt(key, unixTime); + return connectionHandler.getConnection(key).expireAt(key, unixTime); } }.run(); } @@ -101,7 +99,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().ttl(key); + return connectionHandler.getConnection(key).ttl(key); } }.run(); } @@ -111,7 +109,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Boolean execute() { - return connectionHandler.getConnection().setbit(key, offset, value); + return connectionHandler.getConnection(key).setbit(key, offset, value); } }.run(); } @@ -121,7 +119,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Boolean execute() { - return connectionHandler.getConnection().setbit(key, offset, value); + return connectionHandler.getConnection(key).setbit(key, offset, value); } }.run(); } @@ -131,7 +129,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Boolean execute() { - return connectionHandler.getConnection().getbit(key, offset); + return connectionHandler.getConnection(key).getbit(key, offset); } }.run(); } @@ -141,7 +139,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().setrange(key, offset, value); + return connectionHandler.getConnection(key).setrange(key, offset, value); } }.run(); } @@ -151,7 +149,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().getrange(key, startOffset, endOffset); + return connectionHandler.getConnection(key).getrange(key, startOffset, endOffset); } }.run(); } @@ -161,7 +159,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().getSet(key, value); + return connectionHandler.getConnection(key).getSet(key, value); } }.run(); } @@ -171,7 +169,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().setnx(key, value); + return connectionHandler.getConnection(key).setnx(key, value); } }.run(); } @@ -181,7 +179,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().setex(key, seconds, value); + return connectionHandler.getConnection(key).setex(key, seconds, value); } }.run(); } @@ -191,7 +189,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().decrBy(key, integer); + return connectionHandler.getConnection(key).decrBy(key, integer); } }.run(); } @@ -201,7 +199,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().decr(key); + return connectionHandler.getConnection(key).decr(key); } }.run(); } @@ -211,7 +209,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().incrBy(key, integer); + return connectionHandler.getConnection(key).incrBy(key, integer); } }.run(); } @@ -221,7 +219,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().incr(key); + return connectionHandler.getConnection(key).incr(key); } }.run(); } @@ -231,7 +229,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().append(key, value); + return connectionHandler.getConnection(key).append(key, value); } }.run(); } @@ -241,7 +239,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().substr(key, start, end); + return connectionHandler.getConnection(key).substr(key, start, end); } }.run(); } @@ -251,7 +249,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().hset(key, field, value); + return connectionHandler.getConnection(key).hset(key, field, value); } }.run(); } @@ -261,7 +259,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().hget(key, field); + return connectionHandler.getConnection(key).hget(key, field); } }.run(); } @@ -271,7 +269,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().hsetnx(key, field, value); + return connectionHandler.getConnection(key).hsetnx(key, field, value); } }.run(); } @@ -281,7 +279,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().hmset(key, hash); + return connectionHandler.getConnection(key).hmset(key, hash); } }.run(); } @@ -291,7 +289,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public List execute() { - return connectionHandler.getConnection().hmget(key, fields); + return connectionHandler.getConnection(key).hmget(key, fields); } }.run(); } @@ -301,7 +299,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().hincrBy(key, field, value); + return connectionHandler.getConnection(key).hincrBy(key, field, value); } }.run(); } @@ -311,7 +309,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Boolean execute() { - return connectionHandler.getConnection().hexists(key, field); + return connectionHandler.getConnection(key).hexists(key, field); } }.run(); } @@ -321,7 +319,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().hdel(key, field); + return connectionHandler.getConnection(key).hdel(key, field); } }.run(); } @@ -331,7 +329,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().hdel(key); + return connectionHandler.getConnection(key).hdel(key); } }.run(); } @@ -341,7 +339,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection().hkeys(key); + return connectionHandler.getConnection(key).hkeys(key); } }.run(); } @@ -351,7 +349,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public List execute() { - return connectionHandler.getConnection().hvals(key); + return connectionHandler.getConnection(key).hvals(key); } }.run(); } @@ -361,7 +359,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Map execute() { - return connectionHandler.getConnection().hgetAll(key); + return connectionHandler.getConnection(key).hgetAll(key); } }.run(); } @@ -371,7 +369,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().rpush(key, string); + return connectionHandler.getConnection(key).rpush(key, string); } }.run(); } @@ -381,7 +379,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().lpush(key, string); + return connectionHandler.getConnection(key).lpush(key, string); } }.run(); } @@ -391,7 +389,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().llen(key); + return connectionHandler.getConnection(key).llen(key); } }.run(); } @@ -401,7 +399,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public List execute() { - return connectionHandler.getConnection().lrange(key, start, end); + return connectionHandler.getConnection(key).lrange(key, start, end); } }.run(); } @@ -411,7 +409,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().ltrim(key, start, end); + return connectionHandler.getConnection(key).ltrim(key, start, end); } }.run(); } @@ -421,7 +419,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().lindex(key, index); + return connectionHandler.getConnection(key).lindex(key, index); } }.run(); } @@ -431,7 +429,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().lset(key, index, value); + return connectionHandler.getConnection(key).lset(key, index, value); } }.run(); } @@ -441,7 +439,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().lrem(key, count, value); + return connectionHandler.getConnection(key).lrem(key, count, value); } }.run(); } @@ -451,7 +449,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().lpop(key); + return connectionHandler.getConnection(key).lpop(key); } }.run(); } @@ -461,7 +459,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().rpop(key); + return connectionHandler.getConnection(key).rpop(key); } }.run(); } @@ -471,7 +469,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().sadd(key, member); + return connectionHandler.getConnection(key).sadd(key, member); } }.run(); } @@ -481,7 +479,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection().smembers(key); + return connectionHandler.getConnection(key).smembers(key); } }.run(); } @@ -491,7 +489,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().srem(key, member); + return connectionHandler.getConnection(key).srem(key, member); } }.run(); } @@ -501,7 +499,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().spop(key); + return connectionHandler.getConnection(key).spop(key); } }.run(); } @@ -511,7 +509,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().scard(key); + return connectionHandler.getConnection(key).scard(key); } }.run(); } @@ -521,7 +519,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Boolean execute() { - return connectionHandler.getConnection().sismember(key, member); + return connectionHandler.getConnection(key).sismember(key, member); } }.run(); } @@ -531,7 +529,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().srandmember(key); + return connectionHandler.getConnection(key).srandmember(key); } }.run(); } @@ -541,7 +539,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().strlen(key); + return connectionHandler.getConnection(key).strlen(key); } }.run(); } @@ -551,7 +549,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().zadd(key, score, member); + return connectionHandler.getConnection(key).zadd(key, score, member); } }.run(); } @@ -561,7 +559,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().zadd(key, scoreMembers); + return connectionHandler.getConnection(key).zadd(key, scoreMembers); } }.run(); } @@ -571,7 +569,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection().zrange(key, start, end); + return connectionHandler.getConnection(key).zrange(key, start, end); } }.run(); } @@ -581,7 +579,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().zrem(key, member); + return connectionHandler.getConnection(key).zrem(key, member); } }.run(); } @@ -591,7 +589,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Double execute() { - return connectionHandler.getConnection().zincrby(key, score, member); + return connectionHandler.getConnection(key).zincrby(key, score, member); } }.run(); } @@ -601,7 +599,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().zrank(key, member); + return connectionHandler.getConnection(key).zrank(key, member); } }.run(); } @@ -611,7 +609,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().zrevrank(key, member); + return connectionHandler.getConnection(key).zrevrank(key, member); } }.run(); } @@ -621,7 +619,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection().zrevrange(key, start, end); + return connectionHandler.getConnection(key).zrevrange(key, start, end); } }.run(); } @@ -631,7 +629,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection().zrangeWithScores(key, start, end); + return connectionHandler.getConnection(key).zrangeWithScores(key, start, end); } }.run(); } @@ -641,7 +639,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection().zrevrangeWithScores(key, start, end); + return connectionHandler.getConnection(key).zrevrangeWithScores(key, start, end); } }.run(); } @@ -651,7 +649,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().zcard(key); + return connectionHandler.getConnection(key).zcard(key); } }.run(); } @@ -661,7 +659,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Double execute() { - return connectionHandler.getConnection().zscore(key, member); + return connectionHandler.getConnection(key).zscore(key, member); } }.run(); } @@ -671,7 +669,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public List execute() { - return connectionHandler.getConnection().sort(key); + return connectionHandler.getConnection(key).sort(key); } }.run(); } @@ -681,7 +679,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public List execute() { - return connectionHandler.getConnection().sort(key, sortingParameters); + return connectionHandler.getConnection(key).sort(key, sortingParameters); } }.run(); } @@ -691,7 +689,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().zcount(key, min, max); + return connectionHandler.getConnection(key).zcount(key, min, max); } }.run(); } @@ -701,7 +699,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().zcount(key, min, max); + return connectionHandler.getConnection(key).zcount(key, min, max); } }.run(); } @@ -711,7 +709,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection().zrangeByScore(key, min, max); + return connectionHandler.getConnection(key).zrangeByScore(key, min, max); } }.run(); } @@ -721,7 +719,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection().zrangeByScore(key, min, max); + return connectionHandler.getConnection(key).zrangeByScore(key, min, max); } }.run(); } @@ -731,7 +729,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection().zrevrangeByScore(key, min, max); + return connectionHandler.getConnection(key).zrevrangeByScore(key, min, max); } }.run(); } @@ -742,7 +740,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection().zrangeByScore(key, min, max, offset, count); + return connectionHandler.getConnection(key).zrangeByScore(key, min, max, offset, count); } }.run(); } @@ -752,7 +750,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection().zrevrangeByScore(key, min, max); + return connectionHandler.getConnection(key).zrevrangeByScore(key, min, max); } }.run(); } @@ -763,7 +761,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection().zrangeByScore(key, min, max, offset, count); + return connectionHandler.getConnection(key).zrangeByScore(key, min, max, offset, count); } }.run(); } @@ -774,7 +772,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection().zrevrangeByScore(key, min, max, offset, count); + return connectionHandler.getConnection(key).zrevrangeByScore(key, min, max, offset, count); } }.run(); } @@ -784,7 +782,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection().zrangeByScoreWithScores(key, min, max); + return connectionHandler.getConnection(key).zrangeByScoreWithScores(key, min, max); } }.run(); } @@ -794,7 +792,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection().zrevrangeByScoreWithScores(key, min, max); + return connectionHandler.getConnection(key).zrevrangeByScoreWithScores(key, min, max); } }.run(); } @@ -804,7 +802,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection().zrangeByScoreWithScores(key, min, max, offset, count); + return connectionHandler.getConnection(key).zrangeByScoreWithScores(key, min, max, offset, count); } }.run(); } @@ -815,7 +813,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection().zrevrangeByScore(key, min, max, offset, count); + return connectionHandler.getConnection(key).zrevrangeByScore(key, min, max, offset, count); } }.run(); } @@ -825,7 +823,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection().zrangeByScoreWithScores(key, min, max); + return connectionHandler.getConnection(key).zrangeByScoreWithScores(key, min, max); } }.run(); } @@ -836,7 +834,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection().zrevrangeByScoreWithScores(key, min, max); + return connectionHandler.getConnection(key).zrevrangeByScoreWithScores(key, min, max); } }.run(); } @@ -847,7 +845,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection().zrangeByScoreWithScores(key, min, max, offset, count); + return connectionHandler.getConnection(key).zrangeByScoreWithScores(key, min, max, offset, count); } }.run(); } @@ -858,7 +856,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection().zrevrangeByScoreWithScores(key, max, min, offset, count); + return connectionHandler.getConnection(key).zrevrangeByScoreWithScores(key, max, min, offset, count); } }.run(); } @@ -869,7 +867,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection().zrevrangeByScoreWithScores(key, max, min, offset, count); + return connectionHandler.getConnection(key).zrevrangeByScoreWithScores(key, max, min, offset, count); } }.run(); } @@ -879,7 +877,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().zremrangeByRank(key, start, end); + return connectionHandler.getConnection(key).zremrangeByRank(key, start, end); } }.run(); } @@ -889,7 +887,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().zremrangeByScore(key, start, end); + return connectionHandler.getConnection(key).zremrangeByScore(key, start, end); } }.run(); } @@ -899,7 +897,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().zremrangeByScore(key, start, end); + return connectionHandler.getConnection(key).zremrangeByScore(key, start, end); } }.run(); } @@ -910,7 +908,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().linsert(key, where, pivot, value); + return connectionHandler.getConnection(key).linsert(key, where, pivot, value); } }.run(); } @@ -920,7 +918,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().lpushx(key, string); + return connectionHandler.getConnection(key).lpushx(key, string); } }.run(); } @@ -930,7 +928,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().rpushx(key, string); + return connectionHandler.getConnection(key).rpushx(key, string); } }.run(); } @@ -940,7 +938,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public List execute() { - return connectionHandler.getConnection().blpop(arg); + return connectionHandler.getConnection(null).blpop(arg); } }.run(); } @@ -950,7 +948,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public List execute() { - return connectionHandler.getConnection().brpop(arg); + return connectionHandler.getConnection(null).brpop(arg); } }.run(); } @@ -960,7 +958,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().del(key); + return connectionHandler.getConnection(key).del(key); } }.run(); } @@ -970,7 +968,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().echo(string); + return connectionHandler.getConnection(null).echo(string); } }.run(); } @@ -980,7 +978,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().move(key, dbIndex); + return connectionHandler.getConnection(key).move(key, dbIndex); } }.run(); } @@ -990,7 +988,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().bitcount(key); + return connectionHandler.getConnection(key).bitcount(key); } }.run(); } @@ -1000,7 +998,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().bitcount(key, start, end); + return connectionHandler.getConnection(key).bitcount(key, start, end); } }.run(); } @@ -1010,7 +1008,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().ping(); + return connectionHandler.getConnection(null).ping(); } }.run(); } @@ -1020,7 +1018,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().quit(); + return connectionHandler.getConnection(null).quit(); } }.run(); } @@ -1030,7 +1028,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().flushDB(); + return connectionHandler.getConnection(null).flushDB(); } }.run(); } @@ -1040,7 +1038,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().dbSize(); + return connectionHandler.getConnection(null).dbSize(); } }.run(); } @@ -1050,7 +1048,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().select(index); + return connectionHandler.getConnection(null).select(index); } }.run(); } @@ -1060,7 +1058,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().flushAll(); + return connectionHandler.getConnection(null).flushAll(); } }.run(); } @@ -1070,7 +1068,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().auth(password); + return connectionHandler.getConnection(null).auth(password); } }.run(); } @@ -1080,7 +1078,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().save(); + return connectionHandler.getConnection(null).save(); } }.run(); } @@ -1090,7 +1088,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().bgsave(); + return connectionHandler.getConnection(null).bgsave(); } }.run(); } @@ -1100,7 +1098,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().bgrewriteaof(); + return connectionHandler.getConnection(null).bgrewriteaof(); } }.run(); } @@ -1110,7 +1108,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().lastsave(); + return connectionHandler.getConnection(null).lastsave(); } }.run(); } @@ -1120,7 +1118,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().shutdown(); + return connectionHandler.getConnection(null).shutdown(); } }.run(); } @@ -1130,7 +1128,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().info(); + return connectionHandler.getConnection(null).info(); } }.run(); } @@ -1140,7 +1138,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().info(section); + return connectionHandler.getConnection(null).info(section); } }.run(); } @@ -1150,7 +1148,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().slaveof(host, port); + return connectionHandler.getConnection(null).slaveof(host, port); } }.run(); } @@ -1160,7 +1158,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().slaveofNoOne(); + return connectionHandler.getConnection(null).slaveofNoOne(); } }.run(); } @@ -1170,7 +1168,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection().getDB(); + return connectionHandler.getConnection(null).getDB(); } }.run(); } @@ -1180,7 +1178,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().debug(params); + return connectionHandler.getConnection(null).debug(params); } }.run(); } @@ -1190,7 +1188,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection().configResetStat(); + return connectionHandler.getConnection(null).configResetStat(); } }.run(); } diff --git a/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java index a28a23c..24cf77f 100644 --- a/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java +++ b/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java @@ -8,8 +8,9 @@ import java.util.Set; public abstract class JedisClusterConnectionHandler { protected Map nodes = new HashMap(); + protected Map slots = new HashMap(); - abstract Jedis getConnection(); + abstract Jedis getConnection(String key); public JedisClusterConnectionHandler(Set nodes) { initializeSlotsCache(nodes); @@ -23,20 +24,39 @@ public abstract class JedisClusterConnectionHandler { for (HostAndPort hostAndPort : nodes) { JedisPool jp = new JedisPool(hostAndPort.getHost(), hostAndPort.getPort()); this.nodes.put(hostAndPort.getHost() + hostAndPort.getPort(), jp); - this.nodes.putAll(discoverClusterNodes(jp)); + discoverClusterNodesAndSlots(jp); } } - private Map discoverClusterNodes(JedisPool jp) { - Map discoveredNodes = new HashMap(); + 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()); - discoveredNodes.put(node.getHost() + node.getPort(), nodePool); + 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 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); } - return discoveredNodes; } private HostAndPort getHostAndPortFromNodeLine(String nodeInfo) { diff --git a/src/main/java/redis/clients/jedis/JedisRandomConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisRandomConnectionHandler.java index fc8226b..f96854e 100644 --- a/src/main/java/redis/clients/jedis/JedisRandomConnectionHandler.java +++ b/src/main/java/redis/clients/jedis/JedisRandomConnectionHandler.java @@ -14,7 +14,7 @@ public class JedisRandomConnectionHandler extends JedisClusterConnectionHandler @SuppressWarnings("unchecked") - public Jedis getConnection() { + public Jedis getConnection(String key) { Object[] nodeArray = nodes.values().toArray(); return ((Pool) nodeArray[new Random().nextInt(nodeArray.length)]).getResource(); } diff --git a/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java new file mode 100644 index 0000000..c8961a5 --- /dev/null +++ b/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java @@ -0,0 +1,30 @@ +package redis.clients.jedis; + +import java.util.Random; +import java.util.Set; + +import redis.clients.jedis.tests.utils.JedisClusterCRC16; + +public class JedisSlotBasedConnectionHandler extends JedisClusterConnectionHandler { + + + public JedisSlotBasedConnectionHandler(Set nodes) { + super(nodes); + } + + + public Jedis getConnection(String key) { + int keySlot = JedisClusterCRC16.getSlot(key); + JedisPool connectionPool = slots.get(keySlot); + if (connectionPool == null) { + connectionPool = getRandomConnection(); + } + return connectionPool.getResource(); + } + + private JedisPool getRandomConnection() { + Object[] nodeArray = nodes.values().toArray(); + return (JedisPool) (nodeArray[new Random().nextInt(nodeArray.length)]); + } + +} diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java index 5162635..bcd8458 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java @@ -89,7 +89,6 @@ public class JedisClusterTest extends Assert { @Test(expected=JedisMovedDataException.class) public void testThrowMovedException() { node1.set("foo", "bar"); - node2.get("foo"); } @Test(expected=JedisAskDataException.class) @@ -108,6 +107,17 @@ public class JedisClusterTest extends Assert { assertEquals(jc.getClusterNodes().size(), 3); } + @Test + public void testCalculateConnectionPerSlot() { + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); + JedisCluster jc = new JedisCluster(jedisClusterNode); + jc.set("foo", "bar"); + jc.set("test", "test"); + assertEquals("bar",node3.get("foo")); + assertEquals("test",node2.get("test")); + + } private String getNodeId(String infoOutput) { for (String infoLine : infoOutput.split("\n")) { diff --git a/src/test/java/redis/clients/jedis/tests/utils/JedisClusterCRC16.java b/src/test/java/redis/clients/jedis/tests/utils/JedisClusterCRC16.java index edf7e2c..24f3e3e 100644 --- a/src/test/java/redis/clients/jedis/tests/utils/JedisClusterCRC16.java +++ b/src/test/java/redis/clients/jedis/tests/utils/JedisClusterCRC16.java @@ -4,11 +4,8 @@ public class JedisClusterCRC16 { public final static int polynomial = 0x1021; // Represents x^16+x^12+x^5+1 static int crc; - public JedisClusterCRC16(){ - crc = 0x0000; - } - 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); @@ -21,9 +18,4 @@ public class JedisClusterCRC16 { return crc &= 0xffff % 16384; } - - public static void main(String[] args) { - System.out.println(getSlot("test")); - } - } \ No newline at end of file From 1b268157999abf69367fd2b6de7c7aed7b649896 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Thu, 2 Jan 2014 20:52:17 -0300 Subject: [PATCH 38/70] Add functionality to recalculate slots when receiving MOVED response from node. Add test to check for ASK responses (implementation missing) --- .../clients/jedis/JedisClusterCommand.java | 7 +- .../jedis/JedisClusterConnectionHandler.java | 5 ++ .../java/redis/clients/jedis/Protocol.java | 4 +- .../exceptions/JedisMovedDataException.java | 28 ++++++- .../clients/jedis/tests/JedisClusterTest.java | 74 +++++++++++++++---- 5 files changed, 94 insertions(+), 24 deletions(-) diff --git a/src/main/java/redis/clients/jedis/JedisClusterCommand.java b/src/main/java/redis/clients/jedis/JedisClusterCommand.java index 1d9aece..0f2b68f 100644 --- a/src/main/java/redis/clients/jedis/JedisClusterCommand.java +++ b/src/main/java/redis/clients/jedis/JedisClusterCommand.java @@ -6,6 +6,7 @@ import redis.clients.jedis.exceptions.JedisMovedDataException; public abstract class JedisClusterCommand { private JedisClusterConnectionHandler connectionHandler; + private boolean asking = false; public JedisClusterCommand(JedisClusterConnectionHandler connectionHandler) { this.connectionHandler = connectionHandler; @@ -17,10 +18,10 @@ public abstract class JedisClusterCommand { try { return execute(); } catch (JedisMovedDataException jme) { - //TODO: Do Retry here + this.connectionHandler.assignSlotToNode(jme.getSlot(), jme.getTargetNode()); + return execute(); } catch (JedisAskDataException jae) { - //TODO: Do ASK here + throw jae; } - return null; } } diff --git a/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java index 24cf77f..e005ded 100644 --- a/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java +++ b/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java @@ -64,4 +64,9 @@ public abstract class JedisClusterConnectionHandler { 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); + } } diff --git a/src/main/java/redis/clients/jedis/Protocol.java b/src/main/java/redis/clients/jedis/Protocol.java index 7eecd25..bff80dd 100644 --- a/src/main/java/redis/clients/jedis/Protocol.java +++ b/src/main/java/redis/clients/jedis/Protocol.java @@ -80,7 +80,9 @@ public final class Protocol { //TODO: I'm not sure if this is the best way to do this. //Maybe Read only first 5 bytes instead? if (message.contains(MOVED_RESPONSE)) { - throw new JedisMovedDataException(message); + String[] movedInfo = message.split(" "); + String[] targetHostAndPort = movedInfo[2].split(":"); + throw new JedisMovedDataException(message, new HostAndPort(targetHostAndPort[0], Integer.valueOf(targetHostAndPort[1])), Integer.valueOf(movedInfo[1])); } else if (message.contains(ASK_RESPONSE)) { throw new JedisAskDataException(message); } diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisMovedDataException.java b/src/main/java/redis/clients/jedis/exceptions/JedisMovedDataException.java index 78e0a4b..c2b5565 100644 --- a/src/main/java/redis/clients/jedis/exceptions/JedisMovedDataException.java +++ b/src/main/java/redis/clients/jedis/exceptions/JedisMovedDataException.java @@ -1,17 +1,37 @@ package redis.clients.jedis.exceptions; +import redis.clients.jedis.HostAndPort; + + public class JedisMovedDataException extends JedisDataException { private static final long serialVersionUID = 3878126572474819403L; + + private HostAndPort targetNode; + private int slot; - public JedisMovedDataException(String message) { - super(message); + public JedisMovedDataException(String message, HostAndPort targetNode, int slot) { + super(message); + this.targetNode = targetNode; + this.slot = slot; } - public JedisMovedDataException(Throwable cause) { + public JedisMovedDataException(Throwable cause, HostAndPort targetNode, int slot) { super(cause); + this.targetNode = targetNode; + this.slot = slot; } - public JedisMovedDataException(String message, Throwable cause) { + public JedisMovedDataException(String message, Throwable cause, HostAndPort targetNode, int slot) { super(message, cause); + this.targetNode = targetNode; + this.slot = slot; } + + public HostAndPort getTargetNode() { + return targetNode; + } + + public int getSlot() { + return slot; + } } diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java index bcd8458..256a807 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java @@ -65,31 +65,36 @@ public class JedisClusterTest extends Assert { pipeline3.sync(); - 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; - } - Thread.sleep(100); - } + waitForClusterReady(); } - @After + + @After public void tearDown() { - // clear all slots of node1 - Pipeline pipelined = node1.pipelined(); - for (int i = 0; i < JedisCluster.HASHSLOTS; i++) { - pipelined.clusterDelSlots(i); + // clear all slots + int[] slotsToDelete = new int[JedisCluster.HASHSLOTS]; + for (int i = 0; i < JedisCluster.HASHSLOTS; i++) { + slotsToDelete[i] = i; } - pipelined.sync(); + node1.clusterDelSlots(slotsToDelete); + node2.clusterDelSlots(slotsToDelete); + node3.clusterDelSlots(slotsToDelete); } @Test(expected=JedisMovedDataException.class) public void testThrowMovedException() { node1.set("foo", "bar"); } + + @Test + public void testMovedExceptionParameters() { + try { + node1.set("foo", "bar"); + } catch (JedisMovedDataException jme) { + assertEquals(12182, jme.getSlot()); + assertEquals(new HostAndPort("127.0.0.1", 7381), jme.getTargetNode()); + } + } @Test(expected=JedisAskDataException.class) public void testThrowAskException() { @@ -116,7 +121,31 @@ public class JedisClusterTest extends Assert { jc.set("test", "test"); assertEquals("bar",node3.get("foo")); assertEquals("test",node2.get("test")); - + } + + @Test + public void testRecalculateSlotsWhenMoved() throws InterruptedException { + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); + JedisCluster jc = new JedisCluster(jedisClusterNode); + node2.clusterDelSlots(JedisClusterCRC16.getSlot("51")); + //TODO: We shouldn't need to issue DELSLOTS in node3, but due to redis-cluster bug we need to. + node3.clusterDelSlots(JedisClusterCRC16.getSlot("51")); + node3.clusterAddSlots(JedisClusterCRC16.getSlot("51")); + waitForClusterReady(); + jc.set("51", "foo"); + assertEquals("foo", jc.get("51")); + } + + @Test + public void testAskResponse() throws InterruptedException { + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); + JedisCluster jc = new JedisCluster(jedisClusterNode); + node3.clusterSetSlotImporting(JedisClusterCRC16.getSlot("51"), getNodeId(node2.clusterNodes())); + node2.clusterSetSlotMigrating(JedisClusterCRC16.getSlot("51"), getNodeId(node3.clusterNodes())); + jc.set("51", "foo"); + assertEquals("foo", jc.get("51")); } private String getNodeId(String infoOutput) { @@ -127,4 +156,17 @@ public class JedisClusterTest extends Assert { } return ""; } + + 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; + } + Thread.sleep(100); + } + } + } \ No newline at end of file From dd0bbdaf9182f5d32c43ce0902b1a99f366c238e Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Fri, 3 Jan 2014 16:42:21 -0300 Subject: [PATCH 39/70] Several changes have been added to this commit: - Add asking to cluster commands - Make jedis cluster return connection to original pool - Add tests for MOVED and ASK cluster responses - Refactor connection handler to recalculate connections based on slots This commit makes the first usable version of Jedis along with Redis Cluster --- .../redis/clients/jedis/BinaryClient.java | 3 + src/main/java/redis/clients/jedis/Jedis.java | 6 + .../redis/clients/jedis/JedisCluster.java | 464 +++++++++--------- .../clients/jedis/JedisClusterCommand.java | 22 +- .../jedis/JedisClusterConnectionHandler.java | 12 +- .../jedis/JedisRandomConnectionHandler.java | 14 +- .../JedisSlotBasedConnectionHandler.java | 38 +- .../java/redis/clients/jedis/Protocol.java | 21 +- .../exceptions/JedisAskDataException.java | 23 +- .../clients/jedis/tests/JedisClusterTest.java | 11 +- 10 files changed, 349 insertions(+), 265 deletions(-) diff --git a/src/main/java/redis/clients/jedis/BinaryClient.java b/src/main/java/redis/clients/jedis/BinaryClient.java index 1b9db49..fd10d38 100644 --- a/src/main/java/redis/clients/jedis/BinaryClient.java +++ b/src/main/java/redis/clients/jedis/BinaryClient.java @@ -1104,5 +1104,8 @@ public class BinaryClient extends Connection { public void cluster(final byte[]... args) { sendCommand(CLUSTER, args); } + public void asking() { + sendCommand(Command.ASKING); + } } diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index c6add77..83a4a1b 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -3130,4 +3130,10 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand 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/JedisCluster.java b/src/main/java/redis/clients/jedis/JedisCluster.java index b654be7..be33412 100644 --- a/src/main/java/redis/clients/jedis/JedisCluster.java +++ b/src/main/java/redis/clients/jedis/JedisCluster.java @@ -29,9 +29,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(key).set(key, value); + return connectionHandler.getConnection().set(key, value); } - }.run(); + }.run(key); } @Override @@ -39,9 +39,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(key).get(key); + return connectionHandler.getConnection().get(key); } - }.run(); + }.run(key); } @Override @@ -49,9 +49,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Boolean execute() { - return connectionHandler.getConnection(key).exists(key); + return connectionHandler.getConnection().exists(key); } - }.run(); + }.run(key); } @Override @@ -59,9 +59,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).persist(key); + return connectionHandler.getConnection().persist(key); } - }.run(); + }.run(key); } @Override @@ -69,9 +69,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(key).type(key); + return connectionHandler.getConnection().type(key); } - }.run(); + }.run(key); } @Override @@ -79,9 +79,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).expire(key, seconds); + return connectionHandler.getConnection().expire(key, seconds); } - }.run(); + }.run(key); } @Override @@ -89,9 +89,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).expireAt(key, unixTime); + return connectionHandler.getConnection().expireAt(key, unixTime); } - }.run(); + }.run(key); } @Override @@ -99,9 +99,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).ttl(key); + return connectionHandler.getConnection().ttl(key); } - }.run(); + }.run(key); } @Override @@ -109,9 +109,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Boolean execute() { - return connectionHandler.getConnection(key).setbit(key, offset, value); + return connectionHandler.getConnection().setbit(key, offset, value); } - }.run(); + }.run(key); } @Override @@ -119,9 +119,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Boolean execute() { - return connectionHandler.getConnection(key).setbit(key, offset, value); + return connectionHandler.getConnection().setbit(key, offset, value); } - }.run(); + }.run(key); } @Override @@ -129,9 +129,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Boolean execute() { - return connectionHandler.getConnection(key).getbit(key, offset); + return connectionHandler.getConnection().getbit(key, offset); } - }.run(); + }.run(key); } @Override @@ -139,9 +139,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).setrange(key, offset, value); + return connectionHandler.getConnection().setrange(key, offset, value); } - }.run(); + }.run(key); } @Override @@ -149,9 +149,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(key).getrange(key, startOffset, endOffset); + return connectionHandler.getConnection().getrange(key, startOffset, endOffset); } - }.run(); + }.run(key); } @Override @@ -159,9 +159,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(key).getSet(key, value); + return connectionHandler.getConnection().getSet(key, value); } - }.run(); + }.run(key); } @Override @@ -169,9 +169,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).setnx(key, value); + return connectionHandler.getConnection().setnx(key, value); } - }.run(); + }.run(key); } @Override @@ -179,9 +179,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(key).setex(key, seconds, value); + return connectionHandler.getConnection().setex(key, seconds, value); } - }.run(); + }.run(key); } @Override @@ -189,9 +189,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).decrBy(key, integer); + return connectionHandler.getConnection().decrBy(key, integer); } - }.run(); + }.run(key); } @Override @@ -199,9 +199,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).decr(key); + return connectionHandler.getConnection().decr(key); } - }.run(); + }.run(key); } @Override @@ -209,9 +209,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).incrBy(key, integer); + return connectionHandler.getConnection().incrBy(key, integer); } - }.run(); + }.run(key); } @Override @@ -219,9 +219,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).incr(key); + return connectionHandler.getConnection().incr(key); } - }.run(); + }.run(key); } @Override @@ -229,9 +229,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).append(key, value); + return connectionHandler.getConnection().append(key, value); } - }.run(); + }.run(key); } @Override @@ -239,9 +239,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(key).substr(key, start, end); + return connectionHandler.getConnection().substr(key, start, end); } - }.run(); + }.run(key); } @Override @@ -249,9 +249,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).hset(key, field, value); + return connectionHandler.getConnection().hset(key, field, value); } - }.run(); + }.run(key); } @Override @@ -259,9 +259,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(key).hget(key, field); + return connectionHandler.getConnection().hget(key, field); } - }.run(); + }.run(key); } @Override @@ -269,9 +269,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).hsetnx(key, field, value); + return connectionHandler.getConnection().hsetnx(key, field, value); } - }.run(); + }.run(key); } @Override @@ -279,9 +279,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(key).hmset(key, hash); + return connectionHandler.getConnection().hmset(key, hash); } - }.run(); + }.run(key); } @Override @@ -289,9 +289,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public List execute() { - return connectionHandler.getConnection(key).hmget(key, fields); + return connectionHandler.getConnection().hmget(key, fields); } - }.run(); + }.run(key); } @Override @@ -299,9 +299,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).hincrBy(key, field, value); + return connectionHandler.getConnection().hincrBy(key, field, value); } - }.run(); + }.run(key); } @Override @@ -309,9 +309,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Boolean execute() { - return connectionHandler.getConnection(key).hexists(key, field); + return connectionHandler.getConnection().hexists(key, field); } - }.run(); + }.run(key); } @Override @@ -319,9 +319,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).hdel(key, field); + return connectionHandler.getConnection().hdel(key, field); } - }.run(); + }.run(key); } @Override @@ -329,9 +329,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).hdel(key); + return connectionHandler.getConnection().hdel(key); } - }.run(); + }.run(key); } @Override @@ -339,9 +339,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection(key).hkeys(key); + return connectionHandler.getConnection().hkeys(key); } - }.run(); + }.run(key); } @Override @@ -349,9 +349,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public List execute() { - return connectionHandler.getConnection(key).hvals(key); + return connectionHandler.getConnection().hvals(key); } - }.run(); + }.run(key); } @Override @@ -359,9 +359,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Map execute() { - return connectionHandler.getConnection(key).hgetAll(key); + return connectionHandler.getConnection().hgetAll(key); } - }.run(); + }.run(key); } @Override @@ -369,9 +369,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).rpush(key, string); + return connectionHandler.getConnection().rpush(key, string); } - }.run(); + }.run(key); } @Override @@ -379,9 +379,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).lpush(key, string); + return connectionHandler.getConnection().lpush(key, string); } - }.run(); + }.run(key); } @Override @@ -389,9 +389,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).llen(key); + return connectionHandler.getConnection().llen(key); } - }.run(); + }.run(key); } @Override @@ -399,9 +399,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public List execute() { - return connectionHandler.getConnection(key).lrange(key, start, end); + return connectionHandler.getConnection().lrange(key, start, end); } - }.run(); + }.run(key); } @Override @@ -409,9 +409,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(key).ltrim(key, start, end); + return connectionHandler.getConnection().ltrim(key, start, end); } - }.run(); + }.run(key); } @Override @@ -419,9 +419,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(key).lindex(key, index); + return connectionHandler.getConnection().lindex(key, index); } - }.run(); + }.run(key); } @Override @@ -429,9 +429,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(key).lset(key, index, value); + return connectionHandler.getConnection().lset(key, index, value); } - }.run(); + }.run(key); } @Override @@ -439,9 +439,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).lrem(key, count, value); + return connectionHandler.getConnection().lrem(key, count, value); } - }.run(); + }.run(key); } @Override @@ -449,9 +449,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(key).lpop(key); + return connectionHandler.getConnection().lpop(key); } - }.run(); + }.run(key); } @Override @@ -459,9 +459,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(key).rpop(key); + return connectionHandler.getConnection().rpop(key); } - }.run(); + }.run(key); } @Override @@ -469,9 +469,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).sadd(key, member); + return connectionHandler.getConnection().sadd(key, member); } - }.run(); + }.run(key); } @Override @@ -479,9 +479,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection(key).smembers(key); + return connectionHandler.getConnection().smembers(key); } - }.run(); + }.run(key); } @Override @@ -489,9 +489,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).srem(key, member); + return connectionHandler.getConnection().srem(key, member); } - }.run(); + }.run(key); } @Override @@ -499,9 +499,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(key).spop(key); + return connectionHandler.getConnection().spop(key); } - }.run(); + }.run(key); } @Override @@ -509,9 +509,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).scard(key); + return connectionHandler.getConnection().scard(key); } - }.run(); + }.run(key); } @Override @@ -519,9 +519,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Boolean execute() { - return connectionHandler.getConnection(key).sismember(key, member); + return connectionHandler.getConnection().sismember(key, member); } - }.run(); + }.run(key); } @Override @@ -529,9 +529,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(key).srandmember(key); + return connectionHandler.getConnection().srandmember(key); } - }.run(); + }.run(key); } @Override @@ -539,9 +539,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).strlen(key); + return connectionHandler.getConnection().strlen(key); } - }.run(); + }.run(key); } @Override @@ -549,9 +549,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).zadd(key, score, member); + return connectionHandler.getConnection().zadd(key, score, member); } - }.run(); + }.run(key); } @Override @@ -559,9 +559,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).zadd(key, scoreMembers); + return connectionHandler.getConnection().zadd(key, scoreMembers); } - }.run(); + }.run(key); } @Override @@ -569,9 +569,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection(key).zrange(key, start, end); + return connectionHandler.getConnection().zrange(key, start, end); } - }.run(); + }.run(key); } @Override @@ -579,9 +579,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).zrem(key, member); + return connectionHandler.getConnection().zrem(key, member); } - }.run(); + }.run(key); } @Override @@ -589,9 +589,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Double execute() { - return connectionHandler.getConnection(key).zincrby(key, score, member); + return connectionHandler.getConnection().zincrby(key, score, member); } - }.run(); + }.run(key); } @Override @@ -599,9 +599,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).zrank(key, member); + return connectionHandler.getConnection().zrank(key, member); } - }.run(); + }.run(key); } @Override @@ -609,9 +609,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).zrevrank(key, member); + return connectionHandler.getConnection().zrevrank(key, member); } - }.run(); + }.run(key); } @Override @@ -619,9 +619,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection(key).zrevrange(key, start, end); + return connectionHandler.getConnection().zrevrange(key, start, end); } - }.run(); + }.run(key); } @Override @@ -629,9 +629,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection(key).zrangeWithScores(key, start, end); + return connectionHandler.getConnection().zrangeWithScores(key, start, end); } - }.run(); + }.run(key); } @Override @@ -639,9 +639,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection(key).zrevrangeWithScores(key, start, end); + return connectionHandler.getConnection().zrevrangeWithScores(key, start, end); } - }.run(); + }.run(key); } @Override @@ -649,9 +649,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).zcard(key); + return connectionHandler.getConnection().zcard(key); } - }.run(); + }.run(key); } @Override @@ -659,9 +659,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Double execute() { - return connectionHandler.getConnection(key).zscore(key, member); + return connectionHandler.getConnection().zscore(key, member); } - }.run(); + }.run(key); } @Override @@ -669,9 +669,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public List execute() { - return connectionHandler.getConnection(key).sort(key); + return connectionHandler.getConnection().sort(key); } - }.run(); + }.run(key); } @Override @@ -679,9 +679,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public List execute() { - return connectionHandler.getConnection(key).sort(key, sortingParameters); + return connectionHandler.getConnection().sort(key, sortingParameters); } - }.run(); + }.run(key); } @Override @@ -689,9 +689,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).zcount(key, min, max); + return connectionHandler.getConnection().zcount(key, min, max); } - }.run(); + }.run(key); } @Override @@ -699,9 +699,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).zcount(key, min, max); + return connectionHandler.getConnection().zcount(key, min, max); } - }.run(); + }.run(key); } @Override @@ -709,9 +709,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection(key).zrangeByScore(key, min, max); + return connectionHandler.getConnection().zrangeByScore(key, min, max); } - }.run(); + }.run(key); } @Override @@ -719,9 +719,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection(key).zrangeByScore(key, min, max); + return connectionHandler.getConnection().zrangeByScore(key, min, max); } - }.run(); + }.run(key); } @Override @@ -729,9 +729,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection(key).zrevrangeByScore(key, min, max); + return connectionHandler.getConnection().zrevrangeByScore(key, min, max); } - }.run(); + }.run(key); } @Override @@ -740,9 +740,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection(key).zrangeByScore(key, min, max, offset, count); + return connectionHandler.getConnection().zrangeByScore(key, min, max, offset, count); } - }.run(); + }.run(key); } @Override @@ -750,9 +750,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection(key).zrevrangeByScore(key, min, max); + return connectionHandler.getConnection().zrevrangeByScore(key, min, max); } - }.run(); + }.run(key); } @Override @@ -761,9 +761,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection(key).zrangeByScore(key, min, max, offset, count); + return connectionHandler.getConnection().zrangeByScore(key, min, max, offset, count); } - }.run(); + }.run(key); } @Override @@ -772,9 +772,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection(key).zrevrangeByScore(key, min, max, offset, count); + return connectionHandler.getConnection().zrevrangeByScore(key, min, max, offset, count); } - }.run(); + }.run(key); } @Override @@ -782,9 +782,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection(key).zrangeByScoreWithScores(key, min, max); + return connectionHandler.getConnection().zrangeByScoreWithScores(key, min, max); } - }.run(); + }.run(key); } @Override @@ -792,9 +792,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection(key).zrevrangeByScoreWithScores(key, min, max); + return connectionHandler.getConnection().zrevrangeByScoreWithScores(key, min, max); } - }.run(); + }.run(key); } @Override @@ -802,9 +802,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection(key).zrangeByScoreWithScores(key, min, max, offset, count); + return connectionHandler.getConnection().zrangeByScoreWithScores(key, min, max, offset, count); } - }.run(); + }.run(key); } @Override @@ -813,9 +813,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection(key).zrevrangeByScore(key, min, max, offset, count); + return connectionHandler.getConnection().zrevrangeByScore(key, min, max, offset, count); } - }.run(); + }.run(key); } @Override @@ -823,9 +823,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection(key).zrangeByScoreWithScores(key, min, max); + return connectionHandler.getConnection().zrangeByScoreWithScores(key, min, max); } - }.run(); + }.run(key); } @Override @@ -834,9 +834,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection(key).zrevrangeByScoreWithScores(key, min, max); + return connectionHandler.getConnection().zrevrangeByScoreWithScores(key, min, max); } - }.run(); + }.run(key); } @Override @@ -845,9 +845,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection(key).zrangeByScoreWithScores(key, min, max, offset, count); + return connectionHandler.getConnection().zrangeByScoreWithScores(key, min, max, offset, count); } - }.run(); + }.run(key); } @Override @@ -856,9 +856,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection(key).zrevrangeByScoreWithScores(key, max, min, offset, count); + return connectionHandler.getConnection().zrevrangeByScoreWithScores(key, max, min, offset, count); } - }.run(); + }.run(key); } @Override @@ -867,9 +867,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public Set execute() { - return connectionHandler.getConnection(key).zrevrangeByScoreWithScores(key, max, min, offset, count); + return connectionHandler.getConnection().zrevrangeByScoreWithScores(key, max, min, offset, count); } - }.run(); + }.run(key); } @Override @@ -877,9 +877,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).zremrangeByRank(key, start, end); + return connectionHandler.getConnection().zremrangeByRank(key, start, end); } - }.run(); + }.run(key); } @Override @@ -887,9 +887,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).zremrangeByScore(key, start, end); + return connectionHandler.getConnection().zremrangeByScore(key, start, end); } - }.run(); + }.run(key); } @Override @@ -897,9 +897,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).zremrangeByScore(key, start, end); + return connectionHandler.getConnection().zremrangeByScore(key, start, end); } - }.run(); + }.run(key); } @Override @@ -908,9 +908,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).linsert(key, where, pivot, value); + return connectionHandler.getConnection().linsert(key, where, pivot, value); } - }.run(); + }.run(key); } @Override @@ -918,9 +918,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).lpushx(key, string); + return connectionHandler.getConnection().lpushx(key, string); } - }.run(); + }.run(key); } @Override @@ -928,9 +928,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).rpushx(key, string); + return connectionHandler.getConnection().rpushx(key, string); } - }.run(); + }.run(key); } @Override @@ -938,9 +938,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public List execute() { - return connectionHandler.getConnection(null).blpop(arg); + return connectionHandler.getConnection().blpop(arg); } - }.run(); + }.run(null); } @Override @@ -948,9 +948,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand>(connectionHandler) { @Override public List execute() { - return connectionHandler.getConnection(null).brpop(arg); + return connectionHandler.getConnection().brpop(arg); } - }.run(); + }.run(null); } @Override @@ -958,9 +958,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).del(key); + return connectionHandler.getConnection().del(key); } - }.run(); + }.run(null); } @Override @@ -968,9 +968,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(null).echo(string); + return connectionHandler.getConnection().echo(string); } - }.run(); + }.run(null); } @Override @@ -978,9 +978,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).move(key, dbIndex); + return connectionHandler.getConnection().move(key, dbIndex); } - }.run(); + }.run(key); } @Override @@ -988,9 +988,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).bitcount(key); + return connectionHandler.getConnection().bitcount(key); } - }.run(); + }.run(key); } @Override @@ -998,9 +998,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(key).bitcount(key, start, end); + return connectionHandler.getConnection().bitcount(key, start, end); } - }.run(); + }.run(key); } @Override @@ -1008,9 +1008,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(null).ping(); + return connectionHandler.getConnection().ping(); } - }.run(); + }.run(null); } @Override @@ -1018,9 +1018,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(null).quit(); + return connectionHandler.getConnection().quit(); } - }.run(); + }.run(null); } @Override @@ -1028,9 +1028,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(null).flushDB(); + return connectionHandler.getConnection().flushDB(); } - }.run(); + }.run(null); } @Override @@ -1038,9 +1038,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(null).dbSize(); + return connectionHandler.getConnection().dbSize(); } - }.run(); + }.run(null); } @Override @@ -1048,9 +1048,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(null).select(index); + return connectionHandler.getConnection().select(index); } - }.run(); + }.run(null); } @Override @@ -1058,9 +1058,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(null).flushAll(); + return connectionHandler.getConnection().flushAll(); } - }.run(); + }.run(null); } @Override @@ -1068,9 +1068,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(null).auth(password); + return connectionHandler.getConnection().auth(password); } - }.run(); + }.run(null); } @Override @@ -1078,9 +1078,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(null).save(); + return connectionHandler.getConnection().save(); } - }.run(); + }.run(null); } @Override @@ -1088,9 +1088,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(null).bgsave(); + return connectionHandler.getConnection().bgsave(); } - }.run(); + }.run(null); } @Override @@ -1098,9 +1098,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(null).bgrewriteaof(); + return connectionHandler.getConnection().bgrewriteaof(); } - }.run(); + }.run(null); } @Override @@ -1108,9 +1108,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(null).lastsave(); + return connectionHandler.getConnection().lastsave(); } - }.run(); + }.run(null); } @Override @@ -1118,9 +1118,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(null).shutdown(); + return connectionHandler.getConnection().shutdown(); } - }.run(); + }.run(null); } @Override @@ -1128,9 +1128,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(null).info(); + return connectionHandler.getConnection().info(); } - }.run(); + }.run(null); } @Override @@ -1138,9 +1138,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(null).info(section); + return connectionHandler.getConnection().info(section); } - }.run(); + }.run(null); } @Override @@ -1148,9 +1148,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(null).slaveof(host, port); + return connectionHandler.getConnection().slaveof(host, port); } - }.run(); + }.run(null); } @Override @@ -1158,9 +1158,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(null).slaveofNoOne(); + return connectionHandler.getConnection().slaveofNoOne(); } - }.run(); + }.run(null); } @Override @@ -1168,9 +1168,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public Long execute() { - return connectionHandler.getConnection(null).getDB(); + return connectionHandler.getConnection().getDB(); } - }.run(); + }.run(null); } @Override @@ -1178,9 +1178,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(null).debug(params); + return connectionHandler.getConnection().debug(params); } - }.run(); + }.run(null); } @Override @@ -1188,9 +1188,9 @@ public class JedisCluster implements JedisCommands, BasicCommands { return new JedisClusterCommand(connectionHandler) { @Override public String execute() { - return connectionHandler.getConnection(null).configResetStat(); + return connectionHandler.getConnection().configResetStat(); } - }.run(); + }.run(null); } public Map getClusterNodes() { diff --git a/src/main/java/redis/clients/jedis/JedisClusterCommand.java b/src/main/java/redis/clients/jedis/JedisClusterCommand.java index 0f2b68f..61e4d3a 100644 --- a/src/main/java/redis/clients/jedis/JedisClusterCommand.java +++ b/src/main/java/redis/clients/jedis/JedisClusterCommand.java @@ -1,27 +1,41 @@ package redis.clients.jedis; import redis.clients.jedis.exceptions.JedisAskDataException; +import redis.clients.jedis.exceptions.JedisClusterException; import redis.clients.jedis.exceptions.JedisMovedDataException; +import redis.clients.jedis.tests.utils.JedisClusterCRC16; public abstract class JedisClusterCommand { - private JedisClusterConnectionHandler connectionHandler; private boolean asking = false; + private JedisClusterConnectionHandler connectionHandler; +// private boolean asking = false; + public JedisClusterCommand(JedisClusterConnectionHandler connectionHandler) { this.connectionHandler = connectionHandler; } public abstract T execute(); - public T run() { + public T run(String key) { try { + if (key == null) { + throw new JedisClusterException("No way to dispatch this command to Redis Cluster."); + } + connectionHandler.getConnectionFromSlot(JedisClusterCRC16.getSlot(key)); + if (asking) { + //TODO: Pipeline asking with the original command to make it faster.... + connectionHandler.getConnection().asking(); + } return execute(); } catch (JedisMovedDataException jme) { this.connectionHandler.assignSlotToNode(jme.getSlot(), jme.getTargetNode()); - return execute(); + return run(key); } catch (JedisAskDataException jae) { - throw jae; + asking = true; + this.connectionHandler.assignSlotToNode(jae.getSlot(), jae.getTargetNode()); + return run(key); } } } diff --git a/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java index e005ded..765b9a2 100644 --- a/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java +++ b/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java @@ -2,6 +2,7 @@ package redis.clients.jedis; import java.util.HashMap; import java.util.Map; +import java.util.Random; import java.util.Set; @@ -10,7 +11,8 @@ public abstract class JedisClusterConnectionHandler { protected Map nodes = new HashMap(); protected Map slots = new HashMap(); - abstract Jedis getConnection(String key); + abstract Jedis getConnection(); + abstract Jedis getConnectionFromSlot(int slot); public JedisClusterConnectionHandler(Set nodes) { initializeSlotsCache(nodes); @@ -69,4 +71,12 @@ public abstract class JedisClusterConnectionHandler { 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/JedisRandomConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisRandomConnectionHandler.java index f96854e..40d3f04 100644 --- a/src/main/java/redis/clients/jedis/JedisRandomConnectionHandler.java +++ b/src/main/java/redis/clients/jedis/JedisRandomConnectionHandler.java @@ -1,10 +1,7 @@ package redis.clients.jedis; -import java.util.Random; import java.util.Set; -import redis.clients.util.Pool; - public class JedisRandomConnectionHandler extends JedisClusterConnectionHandler { @@ -12,11 +9,12 @@ public class JedisRandomConnectionHandler extends JedisClusterConnectionHandler super(nodes); } - - @SuppressWarnings("unchecked") - public Jedis getConnection(String key) { - Object[] nodeArray = nodes.values().toArray(); - return ((Pool) nodeArray[new Random().nextInt(nodeArray.length)]).getResource(); + public Jedis getConnection() { + return getRandomConnection().getResource(); } + @Override + Jedis getConnectionFromSlot(int slot) { + return getRandomConnection().getResource(); + } } diff --git a/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java index c8961a5..4f3ea5d 100644 --- a/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java +++ b/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java @@ -1,30 +1,48 @@ package redis.clients.jedis; -import java.util.Random; import java.util.Set; -import redis.clients.jedis.tests.utils.JedisClusterCRC16; - public class JedisSlotBasedConnectionHandler extends JedisClusterConnectionHandler { + private Jedis currentConnection; public JedisSlotBasedConnectionHandler(Set nodes) { super(nodes); } - public Jedis getConnection(String key) { - int keySlot = JedisClusterCRC16.getSlot(key); - JedisPool connectionPool = slots.get(keySlot); + 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); + } + + } + + + @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(); } - private JedisPool getRandomConnection() { - Object[] nodeArray = nodes.values().toArray(); - return (JedisPool) (nodeArray[new Random().nextInt(nodeArray.length)]); - } + } diff --git a/src/main/java/redis/clients/jedis/Protocol.java b/src/main/java/redis/clients/jedis/Protocol.java index bff80dd..18e453f 100644 --- a/src/main/java/redis/clients/jedis/Protocol.java +++ b/src/main/java/redis/clients/jedis/Protocol.java @@ -79,15 +79,26 @@ public final class Protocol { 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.contains(MOVED_RESPONSE)) { - String[] movedInfo = message.split(" "); - String[] targetHostAndPort = movedInfo[2].split(":"); - throw new JedisMovedDataException(message, new HostAndPort(targetHostAndPort[0], Integer.valueOf(targetHostAndPort[1])), Integer.valueOf(movedInfo[1])); + String[] movedInfo = parseTargetHostAndSlot(message); + throw new JedisMovedDataException(message, new HostAndPort(movedInfo[1], Integer.valueOf(movedInfo[2])), Integer.valueOf(movedInfo[0])); } else if (message.contains(ASK_RESPONSE)) { - throw new JedisAskDataException(message); + 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 Object process(final RedisInputStream is) { try { @@ -179,7 +190,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, CLUSTER; + DUMP, RESTORE, PEXPIRE, PEXPIREAT, PTTL, INCRBYFLOAT, PSETEX, CLIENT, TIME, MIGRATE, HINCRBYFLOAT, CLUSTER, ASKING; public final byte[] raw; diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisAskDataException.java b/src/main/java/redis/clients/jedis/exceptions/JedisAskDataException.java index 158256d..645d5c2 100644 --- a/src/main/java/redis/clients/jedis/exceptions/JedisAskDataException.java +++ b/src/main/java/redis/clients/jedis/exceptions/JedisAskDataException.java @@ -1,11 +1,12 @@ package redis.clients.jedis.exceptions; +import redis.clients.jedis.HostAndPort; + public class JedisAskDataException extends JedisDataException { private static final long serialVersionUID = 3878126572474819403L; - - public JedisAskDataException(String message) { - super(message); - } + + private HostAndPort targetNode; + private int slot; public JedisAskDataException(Throwable cause) { super(cause); @@ -14,4 +15,18 @@ public class JedisAskDataException extends JedisDataException { public JedisAskDataException(String message, Throwable cause) { super(message, cause); } + + public JedisAskDataException(String message, HostAndPort targetHost, int slot) { + super(message); + this.targetNode = targetHost; + this.slot = slot; + } + + public HostAndPort getTargetNode() { + return targetNode; + } + + public int getSlot() { + return slot; + } } diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java index 256a807..b13c559 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java @@ -13,6 +13,7 @@ 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.JedisMovedDataException; import redis.clients.jedis.tests.utils.JedisClusterCRC16; @@ -39,7 +40,7 @@ public class JedisClusterTest extends Assert { node3.connect(); node3.flushAll(); - // ---- configure cluster + // ---- configure cluster // add nodes to cluster node1.clusterMeet("127.0.0.1", nodeInfo1.getPort()); @@ -148,6 +149,14 @@ public class JedisClusterTest extends Assert { assertEquals("foo", jc.get("51")); } + @Test(expected=JedisClusterException.class) + public void testThrowExceptionWithoutKey() { + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); + JedisCluster jc = new JedisCluster(jedisClusterNode); + jc.ping(); + } + private String getNodeId(String infoOutput) { for (String infoLine : infoOutput.split("\n")) { if (infoLine.contains("myself")) { From 33716e237c239a12dd6320bcd04251a328c6d24b Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Fri, 3 Jan 2014 16:45:22 -0300 Subject: [PATCH 40/70] Add JedisClusterException file --- .../exceptions/JedisClusterException.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 src/main/java/redis/clients/jedis/exceptions/JedisClusterException.java diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisClusterException.java b/src/main/java/redis/clients/jedis/exceptions/JedisClusterException.java new file mode 100644 index 0000000..e20d5a7 --- /dev/null +++ b/src/main/java/redis/clients/jedis/exceptions/JedisClusterException.java @@ -0,0 +1,18 @@ +package redis.clients.jedis.exceptions; + + +public class JedisClusterException extends JedisDataException { + private static final long serialVersionUID = 3878126572474819403L; + + public JedisClusterException(Throwable cause) { + super(cause); + } + + public JedisClusterException(String message, Throwable cause) { + super(message, cause); + } + + public JedisClusterException(String message) { + super(message); + } +} From 4ab8ea2ef7f349349dbd0c00e89e5c20a967f87d Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Tue, 14 Jan 2014 15:57:53 -0300 Subject: [PATCH 41/70] Move Jedis CRC16 util as it's being used in the project. Changed Makefile to cleanup redis cluster node configuration before running tests Add cleanup to ClusterCommandTest. --- Makefile | 5 ++- .../clients/jedis/JedisClusterCommand.java | 2 +- .../clients/util}/JedisClusterCRC16.java | 2 +- .../clients/jedis/tests/JedisClusterTest.java | 4 +- .../tests/commands/ClusterCommandsTest.java | 40 +++++++++++++++++-- 5 files changed, 45 insertions(+), 8 deletions(-) rename src/{test/java/redis/clients/jedis/tests/utils => main/java/redis/clients/util}/JedisClusterCRC16.java (93%) diff --git a/Makefile b/Makefile index 8e45570..16c1dc6 100644 --- a/Makefile +++ b/Makefile @@ -145,7 +145,7 @@ export REDIS_CLUSTER_NODE1_CONF export REDIS_CLUSTER_NODE2_CONF export REDIS_CLUSTER_NODE3_CONF -start: +start: cleanup echo "$$REDIS1_CONF" | redis-server - echo "$$REDIS2_CONF" | redis-server - echo "$$REDIS3_CONF" | redis-server - @@ -161,6 +161,9 @@ start: echo "$$REDIS_CLUSTER_NODE2_CONF" | redis-server - echo "$$REDIS_CLUSTER_NODE3_CONF" | redis-server - +cleanup: + rm -vf /tmp/redis_cluster_node*.conf + stop: kill `cat /tmp/redis1.pid` kill `cat /tmp/redis2.pid` diff --git a/src/main/java/redis/clients/jedis/JedisClusterCommand.java b/src/main/java/redis/clients/jedis/JedisClusterCommand.java index 61e4d3a..163b7c4 100644 --- a/src/main/java/redis/clients/jedis/JedisClusterCommand.java +++ b/src/main/java/redis/clients/jedis/JedisClusterCommand.java @@ -3,7 +3,7 @@ package redis.clients.jedis; import redis.clients.jedis.exceptions.JedisAskDataException; import redis.clients.jedis.exceptions.JedisClusterException; import redis.clients.jedis.exceptions.JedisMovedDataException; -import redis.clients.jedis.tests.utils.JedisClusterCRC16; +import redis.clients.util.JedisClusterCRC16; public abstract class JedisClusterCommand { diff --git a/src/test/java/redis/clients/jedis/tests/utils/JedisClusterCRC16.java b/src/main/java/redis/clients/util/JedisClusterCRC16.java similarity index 93% rename from src/test/java/redis/clients/jedis/tests/utils/JedisClusterCRC16.java rename to src/main/java/redis/clients/util/JedisClusterCRC16.java index 24f3e3e..044e003 100644 --- a/src/test/java/redis/clients/jedis/tests/utils/JedisClusterCRC16.java +++ b/src/main/java/redis/clients/util/JedisClusterCRC16.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.utils; +package redis.clients.util; public class JedisClusterCRC16 { public final static int polynomial = 0x1021; // Represents x^16+x^12+x^5+1 diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java index b13c559..d612b5e 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java @@ -15,7 +15,7 @@ import redis.clients.jedis.Pipeline; import redis.clients.jedis.exceptions.JedisAskDataException; import redis.clients.jedis.exceptions.JedisClusterException; import redis.clients.jedis.exceptions.JedisMovedDataException; -import redis.clients.jedis.tests.utils.JedisClusterCRC16; +import redis.clients.util.JedisClusterCRC16; public class JedisClusterTest extends Assert { private Jedis node1; @@ -174,7 +174,7 @@ public class JedisClusterTest extends Assert { node3.clusterInfo().split("\n")[0].contains("ok") ) { clusterOk = true; } - Thread.sleep(100); + Thread.sleep(50); } } 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 f4abd11..91a0d78 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java @@ -3,6 +3,7 @@ package redis.clients.jedis.tests.commands; import java.util.List; import org.junit.After; +import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; @@ -12,8 +13,8 @@ import redis.clients.jedis.tests.HostAndPortUtil; import redis.clients.jedis.tests.JedisTestBase; public class ClusterCommandsTest extends JedisTestBase { - private Jedis node1; - private Jedis node2; + private static Jedis node1; + private static Jedis node2; private HostAndPort nodeInfo1 = HostAndPortUtil.getClusterServers().get(0); private HostAndPort nodeInfo2 = HostAndPortUtil.getClusterServers().get(1); @@ -35,8 +36,41 @@ 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(); + System.out.println(node1.clusterInfo()); + System.out.println(node2.clusterInfo()); + 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); + System.out.println(node1.clusterNodes()); + System.out.println(node2.clusterNodes()); + } - @Test + 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 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 public void clusterNodes() { String nodes = node1.clusterNodes(); assertTrue(nodes.split("\n").length > 0); From a09a682f0910add7492924c0f0bde314f23f9a1a Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Tue, 14 Jan 2014 16:00:22 -0300 Subject: [PATCH 42/70] Remove sysout prints from test --- .../clients/jedis/tests/commands/ClusterCommandsTest.java | 4 ---- 1 file changed, 4 deletions(-) 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 91a0d78..8de59a7 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java +++ b/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java @@ -41,8 +41,6 @@ public class ClusterCommandsTest extends JedisTestBase { public static void removeSlots() throws InterruptedException { //This is to wait for gossip to replicate data. waitForEqualClusterSize(); - System.out.println(node1.clusterInfo()); - System.out.println(node2.clusterInfo()); String[] nodes = node1.clusterNodes().split("\n"); String node1Id = nodes[0].split(" ")[0]; node1.clusterDelSlots(1,2,3,4,5,500); @@ -50,8 +48,6 @@ public class ClusterCommandsTest extends JedisTestBase { node1.clusterDelSlots(5000, 10000); node1.clusterDelSlots(6000); node2.clusterDelSlots(6000,1,2,3,4,5,500,5000); - System.out.println(node1.clusterNodes()); - System.out.println(node2.clusterNodes()); } private static void waitForEqualClusterSize() throws InterruptedException { From ccf93714e67057a1b8951713ec1986d236e4fe06 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Tue, 14 Jan 2014 17:58:21 -0300 Subject: [PATCH 43/70] Fix ClusterCommand tearDown as gossip may take some time to send data to nodes --- .../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 8de59a7..a7045a6 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; @@ -48,6 +49,11 @@ public class ClusterCommandsTest extends JedisTestBase { 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 { From 2f9564e1d331a2cfad400eea17fdf4058e98dd48 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Tue, 14 Jan 2014 21:20:33 -0300 Subject: [PATCH 44/70] Variable refactor in JedisClusterTest --- .../redis/clients/jedis/tests/JedisClusterTest.java | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java index d612b5e..08ce912 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java @@ -129,10 +129,11 @@ public class JedisClusterTest extends Assert { Set jedisClusterNode = new HashSet(); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); JedisCluster jc = new JedisCluster(jedisClusterNode); - node2.clusterDelSlots(JedisClusterCRC16.getSlot("51")); + int slot51 = JedisClusterCRC16.getSlot("51"); + node2.clusterDelSlots(slot51); //TODO: We shouldn't need to issue DELSLOTS in node3, but due to redis-cluster bug we need to. - node3.clusterDelSlots(JedisClusterCRC16.getSlot("51")); - node3.clusterAddSlots(JedisClusterCRC16.getSlot("51")); + node3.clusterDelSlots(slot51); + node3.clusterAddSlots(slot51); waitForClusterReady(); jc.set("51", "foo"); assertEquals("foo", jc.get("51")); @@ -143,8 +144,9 @@ public class JedisClusterTest extends Assert { Set jedisClusterNode = new HashSet(); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); JedisCluster jc = new JedisCluster(jedisClusterNode); - node3.clusterSetSlotImporting(JedisClusterCRC16.getSlot("51"), getNodeId(node2.clusterNodes())); - node2.clusterSetSlotMigrating(JedisClusterCRC16.getSlot("51"), getNodeId(node3.clusterNodes())); + int slot51 = JedisClusterCRC16.getSlot("51"); + node3.clusterSetSlotImporting(slot51, getNodeId(node2.clusterNodes())); + node2.clusterSetSlotMigrating(slot51, getNodeId(node3.clusterNodes())); jc.set("51", "foo"); assertEquals("foo", jc.get("51")); } From 46733c5d5a081d3397e05e3027e89435b7859035 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Thu, 16 Jan 2014 18:04:27 -0300 Subject: [PATCH 45/70] Add test for redis cluster max redirections and refactor JedisClusterCommand exception handling --- .../redis/clients/jedis/JedisCluster.java | 247 +++++++++--------- .../clients/jedis/JedisClusterCommand.java | 32 ++- .../exceptions/JedisAskDataException.java | 24 +- .../JedisClusterMaxRedirectionsException.java | 18 ++ .../exceptions/JedisMovedDataException.java | 24 +- .../exceptions/JedisRedirectionException.java | 37 +++ .../clients/jedis/tests/JedisClusterTest.java | 14 +- 7 files changed, 228 insertions(+), 168 deletions(-) create mode 100644 src/main/java/redis/clients/jedis/exceptions/JedisClusterMaxRedirectionsException.java create mode 100644 src/main/java/redis/clients/jedis/exceptions/JedisRedirectionException.java diff --git a/src/main/java/redis/clients/jedis/JedisCluster.java b/src/main/java/redis/clients/jedis/JedisCluster.java index be33412..e9f4bcd 100644 --- a/src/main/java/redis/clients/jedis/JedisCluster.java +++ b/src/main/java/redis/clients/jedis/JedisCluster.java @@ -10,23 +10,31 @@ public class JedisCluster implements JedisCommands, BasicCommands { public static final short HASHSLOTS = 16384; private static final int DEFAULT_TIMEOUT = 1; + private static final int DEFAULT_MAX_REDIRECTIONS = 5; + + private int timeout; + private int maxRedirections; private JedisClusterConnectionHandler connectionHandler; public JedisCluster(Set nodes, int timeout) { - connectionHandler = new JedisSlotBasedConnectionHandler(nodes); - + this(nodes, timeout, DEFAULT_MAX_REDIRECTIONS); } public JedisCluster(Set nodes) { this(nodes, DEFAULT_TIMEOUT); } - + + public JedisCluster(Set jedisClusterNode, int timeout, int maxRedirections) { + this.connectionHandler = new JedisSlotBasedConnectionHandler(jedisClusterNode); + this.timeout = timeout; + this.maxRedirections = maxRedirections; + } @Override public String set(final String key, final String value) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().set(key, value); @@ -36,7 +44,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String get(final String key) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().get(key); @@ -46,7 +54,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Boolean exists(final String key) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Boolean execute() { return connectionHandler.getConnection().exists(key); @@ -56,7 +64,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long persist(final String key) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().persist(key); @@ -66,7 +74,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String type(final String key) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().type(key); @@ -76,7 +84,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long expire(final String key, final int seconds) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().expire(key, seconds); @@ -86,7 +94,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long expireAt(final String key, final long unixTime) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().expireAt(key, unixTime); @@ -96,7 +104,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long ttl(final String key) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().ttl(key); @@ -106,7 +114,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Boolean setbit(final String key, final long offset, final boolean value) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Boolean execute() { return connectionHandler.getConnection().setbit(key, offset, value); @@ -116,7 +124,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Boolean setbit(final String key, final long offset, final String value) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Boolean execute() { return connectionHandler.getConnection().setbit(key, offset, value); @@ -126,7 +134,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Boolean getbit(final String key, final long offset) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Boolean execute() { return connectionHandler.getConnection().getbit(key, offset); @@ -136,7 +144,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long setrange(final String key, final long offset, final String value) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().setrange(key, offset, value); @@ -146,7 +154,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String getrange(final String key, final long startOffset, final long endOffset) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().getrange(key, startOffset, endOffset); @@ -156,7 +164,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String getSet(final String key, final String value) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().getSet(key, value); @@ -166,7 +174,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long setnx(final String key, final String value) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().setnx(key, value); @@ -176,7 +184,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String setex(final String key, final int seconds, final String value) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().setex(key, seconds, value); @@ -186,7 +194,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long decrBy(final String key, final long integer) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().decrBy(key, integer); @@ -196,7 +204,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long decr(final String key) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().decr(key); @@ -206,7 +214,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long incrBy(final String key, final long integer) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().incrBy(key, integer); @@ -216,7 +224,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long incr(final String key) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().incr(key); @@ -226,7 +234,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long append(final String key, final String value) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().append(key, value); @@ -236,7 +244,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String substr(final String key, final int start, final int end) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().substr(key, start, end); @@ -246,7 +254,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long hset(final String key, final String field, final String value) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().hset(key, field, value); @@ -256,7 +264,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String hget(final String key, final String field) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().hget(key, field); @@ -266,7 +274,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long hsetnx(final String key, final String field, final String value) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().hsetnx(key, field, value); @@ -276,7 +284,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String hmset(final String key, final Map hash) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().hmset(key, hash); @@ -286,7 +294,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public List hmget(final String key, final String... fields) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public List execute() { return connectionHandler.getConnection().hmget(key, fields); @@ -296,7 +304,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long hincrBy(final String key, final String field, final long value) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().hincrBy(key, field, value); @@ -306,7 +314,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Boolean hexists(final String key, final String field) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Boolean execute() { return connectionHandler.getConnection().hexists(key, field); @@ -316,7 +324,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long hdel(final String key, final String... field) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().hdel(key, field); @@ -326,7 +334,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long hlen(final String key) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().hdel(key); @@ -336,7 +344,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Set hkeys(final String key) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public Set execute() { return connectionHandler.getConnection().hkeys(key); @@ -346,7 +354,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public List hvals(final String key) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public List execute() { return connectionHandler.getConnection().hvals(key); @@ -356,7 +364,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Map hgetAll(final String key) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public Map execute() { return connectionHandler.getConnection().hgetAll(key); @@ -366,7 +374,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long rpush(final String key, final String... string) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().rpush(key, string); @@ -376,7 +384,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long lpush(final String key, final String... string) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().lpush(key, string); @@ -386,7 +394,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long llen(final String key) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().llen(key); @@ -396,7 +404,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public List lrange(final String key, final long start, final long end) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public List execute() { return connectionHandler.getConnection().lrange(key, start, end); @@ -406,7 +414,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String ltrim(final String key, final long start, final long end) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().ltrim(key, start, end); @@ -416,7 +424,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String lindex(final String key, final long index) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().lindex(key, index); @@ -426,7 +434,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String lset(final String key, final long index, final String value) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().lset(key, index, value); @@ -436,7 +444,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long lrem(final String key, final long count, final String value) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().lrem(key, count, value); @@ -446,7 +454,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String lpop(final String key) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().lpop(key); @@ -456,7 +464,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String rpop(final String key) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().rpop(key); @@ -466,7 +474,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long sadd(final String key, final String... member) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().sadd(key, member); @@ -476,7 +484,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Set smembers(final String key) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public Set execute() { return connectionHandler.getConnection().smembers(key); @@ -486,7 +494,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long srem(final String key, final String... member) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().srem(key, member); @@ -496,7 +504,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String spop(final String key) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().spop(key); @@ -506,7 +514,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long scard(final String key) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().scard(key); @@ -516,7 +524,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Boolean sismember(final String key, final String member) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Boolean execute() { return connectionHandler.getConnection().sismember(key, member); @@ -526,7 +534,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String srandmember(final String key) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().srandmember(key); @@ -536,7 +544,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long strlen(final String key) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().strlen(key); @@ -546,7 +554,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long zadd(final String key, final double score, final String member) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().zadd(key, score, member); @@ -556,7 +564,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long zadd(final String key, final Map scoreMembers) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().zadd(key, scoreMembers); @@ -566,7 +574,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Set zrange(final String key, final long start, final long end) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public Set execute() { return connectionHandler.getConnection().zrange(key, start, end); @@ -576,7 +584,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long zrem(final String key, final String... member) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().zrem(key, member); @@ -586,7 +594,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Double zincrby(final String key, final double score, final String member) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Double execute() { return connectionHandler.getConnection().zincrby(key, score, member); @@ -596,7 +604,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long zrank(final String key, final String member) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().zrank(key, member); @@ -606,7 +614,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long zrevrank(final String key, final String member) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().zrevrank(key, member); @@ -616,7 +624,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Set zrevrange(final String key, final long start, final long end) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public Set execute() { return connectionHandler.getConnection().zrevrange(key, start, end); @@ -626,7 +634,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Set zrangeWithScores(final String key, final long start, final long end) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public Set execute() { return connectionHandler.getConnection().zrangeWithScores(key, start, end); @@ -636,7 +644,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Set zrevrangeWithScores(final String key, final long start, final long end) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public Set execute() { return connectionHandler.getConnection().zrevrangeWithScores(key, start, end); @@ -646,7 +654,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long zcard(final String key) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().zcard(key); @@ -656,7 +664,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Double zscore(final String key, final String member) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Double execute() { return connectionHandler.getConnection().zscore(key, member); @@ -666,7 +674,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public List sort(final String key) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public List execute() { return connectionHandler.getConnection().sort(key); @@ -676,7 +684,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public List sort(final String key, final SortingParams sortingParameters) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public List execute() { return connectionHandler.getConnection().sort(key, sortingParameters); @@ -686,7 +694,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long zcount(final String key, final double min, final double max) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().zcount(key, min, max); @@ -696,7 +704,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long zcount(final String key, final String min, final String max) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().zcount(key, min, max); @@ -706,7 +714,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Set zrangeByScore(final String key, final double min, final double max) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public Set execute() { return connectionHandler.getConnection().zrangeByScore(key, min, max); @@ -716,7 +724,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Set zrangeByScore(final String key, final String min, final String max) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public Set execute() { return connectionHandler.getConnection().zrangeByScore(key, min, max); @@ -726,7 +734,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Set zrevrangeByScore(final String key, final double max, final double min) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public Set execute() { return connectionHandler.getConnection().zrevrangeByScore(key, min, max); @@ -737,7 +745,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Set zrangeByScore(final String key, final double min, final double max, final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public Set execute() { return connectionHandler.getConnection().zrangeByScore(key, min, max, offset, count); @@ -747,7 +755,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Set zrevrangeByScore(final String key, final String max, final String min) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public Set execute() { return connectionHandler.getConnection().zrevrangeByScore(key, min, max); @@ -758,7 +766,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Set zrangeByScore(final String key, final String min, final String max, final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public Set execute() { return connectionHandler.getConnection().zrangeByScore(key, min, max, offset, count); @@ -769,7 +777,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Set zrevrangeByScore(final String key, final double max, final double min, final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public Set execute() { return connectionHandler.getConnection().zrevrangeByScore(key, min, max, offset, count); @@ -779,7 +787,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Set zrangeByScoreWithScores(final String key, final double min, final double max) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public Set execute() { return connectionHandler.getConnection().zrangeByScoreWithScores(key, min, max); @@ -789,7 +797,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Set zrevrangeByScoreWithScores(final String key, final double max, final double min) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public Set execute() { return connectionHandler.getConnection().zrevrangeByScoreWithScores(key, min, max); @@ -799,7 +807,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Set zrangeByScoreWithScores(final String key, final double min, final double max, final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public Set execute() { return connectionHandler.getConnection().zrangeByScoreWithScores(key, min, max, offset, count); @@ -810,7 +818,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Set zrevrangeByScore(final String key, final String max, final String min, final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public Set execute() { return connectionHandler.getConnection().zrevrangeByScore(key, min, max, offset, count); @@ -820,7 +828,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Set zrangeByScoreWithScores(final String key, final String min, final String max) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public Set execute() { return connectionHandler.getConnection().zrangeByScoreWithScores(key, min, max); @@ -831,7 +839,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Set zrevrangeByScoreWithScores(final String key, final String max, final String min) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public Set execute() { return connectionHandler.getConnection().zrevrangeByScoreWithScores(key, min, max); @@ -842,7 +850,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Set zrangeByScoreWithScores(final String key, final String min, final String max, final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public Set execute() { return connectionHandler.getConnection().zrangeByScoreWithScores(key, min, max, offset, count); @@ -853,7 +861,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Set zrevrangeByScoreWithScores(final String key, final double max, final double min, final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public Set execute() { return connectionHandler.getConnection().zrevrangeByScoreWithScores(key, max, min, offset, count); @@ -864,7 +872,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Set zrevrangeByScoreWithScores(final String key, final String max, final String min, final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public Set execute() { return connectionHandler.getConnection().zrevrangeByScoreWithScores(key, max, min, offset, count); @@ -874,7 +882,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long zremrangeByRank(final String key, final long start, final long end) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().zremrangeByRank(key, start, end); @@ -884,7 +892,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long zremrangeByScore(final String key, final double start, final double end) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().zremrangeByScore(key, start, end); @@ -894,7 +902,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long zremrangeByScore(final String key, final String start, final String end) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().zremrangeByScore(key, start, end); @@ -905,7 +913,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long linsert(final String key, final LIST_POSITION where, final String pivot, final String value) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().linsert(key, where, pivot, value); @@ -915,7 +923,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long lpushx(final String key, final String... string) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().lpushx(key, string); @@ -925,7 +933,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long rpushx(final String key, final String... string) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().rpushx(key, string); @@ -935,7 +943,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public List blpop(final String arg) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public List execute() { return connectionHandler.getConnection().blpop(arg); @@ -945,7 +953,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public List brpop(final String arg) { - return new JedisClusterCommand>(connectionHandler) { + return new JedisClusterCommand>(connectionHandler, timeout, maxRedirections) { @Override public List execute() { return connectionHandler.getConnection().brpop(arg); @@ -955,7 +963,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long del(final String key) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().del(key); @@ -965,7 +973,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String echo(final String string) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().echo(string); @@ -975,7 +983,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long move(final String key, final int dbIndex) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().move(key, dbIndex); @@ -985,7 +993,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long bitcount(final String key) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().bitcount(key); @@ -995,7 +1003,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long bitcount(final String key, final long start, final long end) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().bitcount(key, start, end); @@ -1005,7 +1013,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String ping() { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().ping(); @@ -1015,7 +1023,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String quit() { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().quit(); @@ -1025,7 +1033,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String flushDB() { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().flushDB(); @@ -1035,7 +1043,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long dbSize() { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().dbSize(); @@ -1045,7 +1053,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String select(final int index) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().select(index); @@ -1055,7 +1063,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String flushAll() { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().flushAll(); @@ -1065,7 +1073,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String auth(final String password) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().auth(password); @@ -1075,7 +1083,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String save() { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().save(); @@ -1085,7 +1093,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String bgsave() { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().bgsave(); @@ -1095,7 +1103,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String bgrewriteaof() { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().bgrewriteaof(); @@ -1105,7 +1113,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long lastsave() { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().lastsave(); @@ -1115,7 +1123,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String shutdown() { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().shutdown(); @@ -1125,7 +1133,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String info() { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().info(); @@ -1135,7 +1143,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String info(final String section) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().info(section); @@ -1145,7 +1153,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String slaveof(final String host, final int port) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().slaveof(host, port); @@ -1155,7 +1163,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String slaveofNoOne() { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().slaveofNoOne(); @@ -1165,7 +1173,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public Long getDB() { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public Long execute() { return connectionHandler.getConnection().getDB(); @@ -1175,7 +1183,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String debug(final DebugParams params) { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().debug(params); @@ -1185,7 +1193,7 @@ public class JedisCluster implements JedisCommands, BasicCommands { @Override public String configResetStat() { - return new JedisClusterCommand(connectionHandler) { + return new JedisClusterCommand(connectionHandler, timeout, maxRedirections) { @Override public String execute() { return connectionHandler.getConnection().configResetStat(); @@ -1197,3 +1205,4 @@ public class JedisCluster implements JedisCommands, BasicCommands { return connectionHandler.getNodes(); } } + diff --git a/src/main/java/redis/clients/jedis/JedisClusterCommand.java b/src/main/java/redis/clients/jedis/JedisClusterCommand.java index 163b7c4..8596971 100644 --- a/src/main/java/redis/clients/jedis/JedisClusterCommand.java +++ b/src/main/java/redis/clients/jedis/JedisClusterCommand.java @@ -2,7 +2,8 @@ package redis.clients.jedis; import redis.clients.jedis.exceptions.JedisAskDataException; import redis.clients.jedis.exceptions.JedisClusterException; -import redis.clients.jedis.exceptions.JedisMovedDataException; +import redis.clients.jedis.exceptions.JedisClusterMaxRedirectionsException; +import redis.clients.jedis.exceptions.JedisRedirectionException; import redis.clients.util.JedisClusterCRC16; public abstract class JedisClusterCommand { @@ -10,18 +11,25 @@ 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) { + public JedisClusterCommand(JedisClusterConnectionHandler connectionHandler, int timeout, int maxRedirections) { this.connectionHandler = connectionHandler; + this.commandTimeout = timeout; + this.redirections = maxRedirections; } public abstract T execute(); public T run(String key) { try { + if (key == null) { throw new JedisClusterException("No way to dispatch this command to Redis Cluster."); + } else if (redirections == 0) { + throw new JedisClusterMaxRedirectionsException("Too many Cluster redirections?"); } connectionHandler.getConnectionFromSlot(JedisClusterCRC16.getSlot(key)); if (asking) { @@ -29,13 +37,17 @@ public abstract class JedisClusterCommand { connectionHandler.getConnection().asking(); } return execute(); - } catch (JedisMovedDataException jme) { - this.connectionHandler.assignSlotToNode(jme.getSlot(), jme.getTargetNode()); - return run(key); - } catch (JedisAskDataException jae) { - asking = true; - this.connectionHandler.assignSlotToNode(jae.getSlot(), jae.getTargetNode()); - return run(key); + } catch (JedisRedirectionException jre) { + return handleRedirection(jre, key); } } -} + + private T handleRedirection(JedisRedirectionException jre, String key) { + if (jre instanceof JedisAskDataException) { + asking = true; + } + redirections--; + this.connectionHandler.assignSlotToNode(jre.getSlot(), jre.getTargetNode()); + return run(key); + } +} \ No newline at end of file diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisAskDataException.java b/src/main/java/redis/clients/jedis/exceptions/JedisAskDataException.java index 645d5c2..599a779 100644 --- a/src/main/java/redis/clients/jedis/exceptions/JedisAskDataException.java +++ b/src/main/java/redis/clients/jedis/exceptions/JedisAskDataException.java @@ -2,31 +2,19 @@ package redis.clients.jedis.exceptions; import redis.clients.jedis.HostAndPort; -public class JedisAskDataException extends JedisDataException { +public class JedisAskDataException extends JedisRedirectionException { private static final long serialVersionUID = 3878126572474819403L; - private HostAndPort targetNode; - private int slot; - - public JedisAskDataException(Throwable cause) { - super(cause); + public JedisAskDataException(Throwable cause, HostAndPort targetHost, int slot) { + super(cause, targetHost, slot); } - public JedisAskDataException(String message, Throwable cause) { - super(message, cause); + 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); - this.targetNode = targetHost; - this.slot = slot; + super(message, targetHost, slot); } - public HostAndPort getTargetNode() { - return targetNode; - } - - public int getSlot() { - return slot; - } } diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisClusterMaxRedirectionsException.java b/src/main/java/redis/clients/jedis/exceptions/JedisClusterMaxRedirectionsException.java new file mode 100644 index 0000000..519188b --- /dev/null +++ b/src/main/java/redis/clients/jedis/exceptions/JedisClusterMaxRedirectionsException.java @@ -0,0 +1,18 @@ +package redis.clients.jedis.exceptions; + + +public class JedisClusterMaxRedirectionsException extends JedisDataException { + private static final long serialVersionUID = 3878126572474819403L; + + public JedisClusterMaxRedirectionsException(Throwable cause) { + super(cause); + } + + public JedisClusterMaxRedirectionsException(String message, Throwable cause) { + super(message, cause); + } + + public JedisClusterMaxRedirectionsException(String message) { + super(message); + } +} diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisMovedDataException.java b/src/main/java/redis/clients/jedis/exceptions/JedisMovedDataException.java index c2b5565..c7a0873 100644 --- a/src/main/java/redis/clients/jedis/exceptions/JedisMovedDataException.java +++ b/src/main/java/redis/clients/jedis/exceptions/JedisMovedDataException.java @@ -3,35 +3,19 @@ package redis.clients.jedis.exceptions; import redis.clients.jedis.HostAndPort; -public class JedisMovedDataException extends JedisDataException { +public class JedisMovedDataException extends JedisRedirectionException { private static final long serialVersionUID = 3878126572474819403L; - private HostAndPort targetNode; - private int slot; public JedisMovedDataException(String message, HostAndPort targetNode, int slot) { - super(message); - this.targetNode = targetNode; - this.slot = slot; + super(message, targetNode, slot); } public JedisMovedDataException(Throwable cause, HostAndPort targetNode, int slot) { - super(cause); - this.targetNode = targetNode; - this.slot = slot; + super(cause, targetNode, slot); } public JedisMovedDataException(String message, Throwable cause, HostAndPort targetNode, int slot) { - super(message, cause); - this.targetNode = targetNode; - this.slot = slot; + super(message, cause, targetNode, slot); } - - public HostAndPort getTargetNode() { - return targetNode; - } - - public int getSlot() { - return slot; - } } diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisRedirectionException.java b/src/main/java/redis/clients/jedis/exceptions/JedisRedirectionException.java new file mode 100644 index 0000000..65969f3 --- /dev/null +++ b/src/main/java/redis/clients/jedis/exceptions/JedisRedirectionException.java @@ -0,0 +1,37 @@ +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(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 HostAndPort getTargetNode() { + return targetNode; + } + + public int getSlot() { + return slot; + } +} diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java index 08ce912..794f624 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java @@ -14,6 +14,7 @@ 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; import redis.clients.jedis.exceptions.JedisMovedDataException; import redis.clients.util.JedisClusterCRC16; @@ -131,9 +132,9 @@ public class JedisClusterTest extends Assert { JedisCluster jc = new JedisCluster(jedisClusterNode); int slot51 = JedisClusterCRC16.getSlot("51"); node2.clusterDelSlots(slot51); - //TODO: We shouldn't need to issue DELSLOTS in node3, but due to redis-cluster bug we need to. node3.clusterDelSlots(slot51); node3.clusterAddSlots(slot51); + waitForClusterReady(); jc.set("51", "foo"); assertEquals("foo", jc.get("51")); @@ -159,6 +160,17 @@ public class JedisClusterTest extends Assert { jc.ping(); } + @Test(expected=JedisClusterMaxRedirectionsException.class) + public void testRedisClusterMaxRedirections() { + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); + JedisCluster jc = new JedisCluster(jedisClusterNode); + int slot51 = JedisClusterCRC16.getSlot("51"); + //This will cause an infinite redirection loop + node2.clusterSetSlotMigrating(slot51, getNodeId(node3.clusterNodes())); + jc.set("51", "foo"); + } + private String getNodeId(String infoOutput) { for (String infoLine : infoOutput.split("\n")) { if (infoLine.contains("myself")) { From 6c8d7a5045e3e8b34944067fe769cacde3be2604 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Thu, 16 Jan 2014 18:14:55 -0300 Subject: [PATCH 46/70] Add fail in case test doesn't throw any exception --- src/test/java/redis/clients/jedis/tests/JedisClusterTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java index 794f624..ef48a21 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java @@ -96,6 +96,7 @@ public class JedisClusterTest extends Assert { assertEquals(12182, jme.getSlot()); assertEquals(new HostAndPort("127.0.0.1", 7381), jme.getTargetNode()); } + fail(); } @Test(expected=JedisAskDataException.class) From 354dd721e0697dfbf377245cdbc3ad341f08c520 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Thu, 16 Jan 2014 19:23:18 -0200 Subject: [PATCH 47/70] Update README.md --- README.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/README.md b/README.md index 455c273..b5b7219 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ All of the following redis features are supported: - Key-tags for sharding - Sharding with pipelining - Scripting with pipelining +- Redis Cluster ## How do I use it? @@ -65,6 +66,19 @@ Please check the [wiki](http://github.com/xetorthio/jedis/wiki "wiki"). There ar And you are done! +## Jedis Cluster + +Redis cluster [specification](http://redis.io/topics/cluster-spec) (still under development) is implemented + +```java +Set jedisClusterNodes = new HashSet(); +//Jedis Cluster will attempt to discover cluster nodes automatically +jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); +JedisCluster jc = new JedisCluster(jedisClusterNode); +jc.set("foo", "bar"); +String value = jc.get("foo"); +``` + ## I want to contribute! That is great! Just fork the project in github. Create a topic branch, write some code, and add some tests for your new code. From 23b54c2cef17c4d85ab2e25cc659d37ceac83e49 Mon Sep 17 00:00:00 2001 From: Jonathan Leibiusky Date: Thu, 16 Jan 2014 20:37:47 -0500 Subject: [PATCH 48/70] Fix sentinel test not to be so sensitive to time --- Makefile | 1 + .../clients/jedis/tests/JedisClusterTest.java | 268 +++++++++--------- .../jedis/tests/JedisSentinelPoolTest.java | 1 + 3 files changed, 136 insertions(+), 134 deletions(-) diff --git a/Makefile b/Makefile index cf4751f..e00fb83 100644 --- a/Makefile +++ b/Makefile @@ -188,6 +188,7 @@ stop: test: make start + sleep 2 mvn -Dtest=${TEST} clean compile test make stop diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java index ef48a21..c32a9be 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java @@ -29,168 +29,168 @@ public class JedisClusterTest extends Assert { @Before public void setUp() throws InterruptedException { - node1 = new Jedis(nodeInfo1.getHost(), nodeInfo1.getPort()); - node1.connect(); - node1.flushAll(); - - node2 = new Jedis(nodeInfo2.getHost(), nodeInfo2.getPort()); - node2.connect(); - node2.flushAll(); - - node3 = new Jedis(nodeInfo3.getHost(), nodeInfo3.getPort()); - node3.connect(); - node3.flushAll(); - - // ---- 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()); - - // 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++) { - if (i < slotsPerNode) { - pipeline1.clusterAddSlots(i); - } else if (i > slotsPerNode * 2) { - pipeline3.clusterAddSlots(i); - } else { - pipeline2.clusterAddSlots(i); - } - } - pipeline1.sync(); - pipeline2.sync(); - pipeline3.sync(); - - - waitForClusterReady(); + node1 = new Jedis(nodeInfo1.getHost(), nodeInfo1.getPort()); + node1.connect(); + node1.flushAll(); + + node2 = new Jedis(nodeInfo2.getHost(), nodeInfo2.getPort()); + node2.connect(); + node2.flushAll(); + + node3 = new Jedis(nodeInfo3.getHost(), nodeInfo3.getPort()); + node3.connect(); + node3.flushAll(); + + // ---- 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()); + + // 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++) { + if (i < slotsPerNode) { + pipeline1.clusterAddSlots(i); + } else if (i > slotsPerNode * 2) { + pipeline3.clusterAddSlots(i); + } else { + pipeline2.clusterAddSlots(i); + } + } + pipeline1.sync(); + pipeline2.sync(); + pipeline3.sync(); + + waitForClusterReady(); } - - @After + @After public void tearDown() { - // 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); + // 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); } - @Test(expected=JedisMovedDataException.class) + @Test(expected = JedisMovedDataException.class) public void testThrowMovedException() { - node1.set("foo", "bar"); + node1.set("foo", "bar"); } - + @Test public void testMovedExceptionParameters() { - try { - node1.set("foo", "bar"); - } catch (JedisMovedDataException jme) { - assertEquals(12182, jme.getSlot()); - assertEquals(new HostAndPort("127.0.0.1", 7381), jme.getTargetNode()); - } - fail(); + try { + node1.set("foo", "bar"); + } catch (JedisMovedDataException jme) { + assertEquals(12182, jme.getSlot()); + assertEquals(new HostAndPort("127.0.0.1", 7381), + jme.getTargetNode()); + return; + } + fail(); } - @Test(expected=JedisAskDataException.class) + @Test(expected = JedisAskDataException.class) public void testThrowAskException() { - int keySlot = JedisClusterCRC16.getSlot("test"); - String node3Id = getNodeId(node3.clusterNodes()); - node2.clusterSetSlotMigrating(keySlot, node3Id); - node2.get("test"); + int keySlot = JedisClusterCRC16.getSlot("test"); + String node3Id = getNodeId(node3.clusterNodes()); + node2.clusterSetSlotMigrating(keySlot, node3Id); + node2.get("test"); } - + @Test public void testDiscoverNodesAutomatically() { - Set jedisClusterNode = new HashSet(); - jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); - JedisCluster jc = new JedisCluster(jedisClusterNode); - assertEquals(jc.getClusterNodes().size(), 3); + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); + JedisCluster jc = new JedisCluster(jedisClusterNode); + assertEquals(jc.getClusterNodes().size(), 3); } - + @Test public void testCalculateConnectionPerSlot() { - Set jedisClusterNode = new HashSet(); - jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); - JedisCluster jc = new JedisCluster(jedisClusterNode); - jc.set("foo", "bar"); - jc.set("test", "test"); - assertEquals("bar",node3.get("foo")); - assertEquals("test",node2.get("test")); + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); + JedisCluster jc = new JedisCluster(jedisClusterNode); + jc.set("foo", "bar"); + jc.set("test", "test"); + assertEquals("bar", node3.get("foo")); + assertEquals("test", node2.get("test")); } - + @Test public void testRecalculateSlotsWhenMoved() throws InterruptedException { - Set jedisClusterNode = new HashSet(); - jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); - JedisCluster jc = new JedisCluster(jedisClusterNode); - int slot51 = JedisClusterCRC16.getSlot("51"); - node2.clusterDelSlots(slot51); - node3.clusterDelSlots(slot51); - node3.clusterAddSlots(slot51); - - waitForClusterReady(); - jc.set("51", "foo"); - assertEquals("foo", jc.get("51")); + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); + JedisCluster jc = new JedisCluster(jedisClusterNode); + int slot51 = JedisClusterCRC16.getSlot("51"); + node2.clusterDelSlots(slot51); + node3.clusterDelSlots(slot51); + node3.clusterAddSlots(slot51); + + waitForClusterReady(); + jc.set("51", "foo"); + assertEquals("foo", jc.get("51")); } - + @Test public void testAskResponse() throws InterruptedException { - Set jedisClusterNode = new HashSet(); - 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())); - jc.set("51", "foo"); - assertEquals("foo", jc.get("51")); + Set jedisClusterNode = new HashSet(); + 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())); + jc.set("51", "foo"); + assertEquals("foo", jc.get("51")); } - - @Test(expected=JedisClusterException.class) + + @Test(expected = JedisClusterException.class) public void testThrowExceptionWithoutKey() { - Set jedisClusterNode = new HashSet(); - jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); - JedisCluster jc = new JedisCluster(jedisClusterNode); - jc.ping(); + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); + JedisCluster jc = new JedisCluster(jedisClusterNode); + jc.ping(); } - - @Test(expected=JedisClusterMaxRedirectionsException.class) + + @Test(expected = JedisClusterMaxRedirectionsException.class) public void testRedisClusterMaxRedirections() { - Set jedisClusterNode = new HashSet(); - jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); - JedisCluster jc = new JedisCluster(jedisClusterNode); - int slot51 = JedisClusterCRC16.getSlot("51"); - //This will cause an infinite redirection loop - node2.clusterSetSlotMigrating(slot51, getNodeId(node3.clusterNodes())); - jc.set("51", "foo"); + Set jedisClusterNode = new HashSet(); + jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); + JedisCluster jc = new JedisCluster(jedisClusterNode); + int slot51 = JedisClusterCRC16.getSlot("51"); + // This will cause an infinite redirection loop + node2.clusterSetSlotMigrating(slot51, getNodeId(node3.clusterNodes())); + jc.set("51", "foo"); } - + private String getNodeId(String infoOutput) { - for (String infoLine : infoOutput.split("\n")) { - if (infoLine.contains("myself")) { - return infoLine.split(" ")[0]; - } - } - return ""; - } - - 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; - } - Thread.sleep(50); - } + for (String infoLine : infoOutput.split("\n")) { + if (infoLine.contains("myself")) { + return infoLine.split(" ")[0]; + } } - -} \ No newline at end of file + return ""; + } + + 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; + } + Thread.sleep(50); + } + } + +} diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java index c3a72a0..048eeca 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java +++ b/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java @@ -69,6 +69,7 @@ public class JedisSentinelPoolTest extends JedisTestBase { } waitForFailover(pool, oldMaster); + Thread.sleep(100); jedis = pool.getResource(); assertEquals("PONG", jedis.ping()); From f11c1622de1d529cad509b7793977714229f4883 Mon Sep 17 00:00:00 2001 From: Darren Shepherd Date: Thu, 16 Jan 2014 21:57:22 -0700 Subject: [PATCH 49/70] 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 37f629765e236c430357202bfdf562f897072893 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Fri, 17 Jan 2014 12:06:20 -0300 Subject: [PATCH 50/70] Improve performance in MOVED and ASK response parsing --- src/main/java/redis/clients/jedis/Protocol.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/java/redis/clients/jedis/Protocol.java b/src/main/java/redis/clients/jedis/Protocol.java index fb9eb8c..a5e08c6 100644 --- a/src/main/java/redis/clients/jedis/Protocol.java +++ b/src/main/java/redis/clients/jedis/Protocol.java @@ -79,11 +79,10 @@ public final class Protocol { 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.contains(MOVED_RESPONSE)) { + 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.contains(ASK_RESPONSE)) { + } 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])); } From 5f5b80e6e33f93b99874de71174a2297256d0abe Mon Sep 17 00:00:00 2001 From: Mayank Kakodkar Date: Thu, 23 Jan 2014 21:03:46 +0530 Subject: [PATCH 51/70] 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 52/70] 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 53/70] 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 54/70] 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 55/70] 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 56/70] 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 57/70] 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 58/70] 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 59/70] 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 60/70] 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 61/70] 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 62/70] [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 63/70] [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 d846149ae16739b55cc891eba1f2455a4acc28c3 Mon Sep 17 00:00:00 2001 From: Marcos Nils Date: Tue, 4 Feb 2014 22:34:48 -0300 Subject: [PATCH 64/70] 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 65/70] 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 66/70] 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 67/70] 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 68/70] 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 69/70] [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 70/70] [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