Merge branch 'master' into eval-with-nested-lists-and-longs

Conflicts:
	src/main/java/redis/clients/jedis/Jedis.java
	src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java
This commit is contained in:
Daniel Josefsson
2014-02-05 22:24:23 +00:00
122 changed files with 10799 additions and 7506 deletions

View File

@@ -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);
}
}

View File

@@ -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();
}

View File

@@ -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;
}
}

View File

@@ -3,112 +3,112 @@ 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<HostAndPort> redisHostAndPortList = new ArrayList<HostAndPortUtil.HostAndPort>();
private static List<HostAndPort> sentinelHostAndPortList = new ArrayList<HostAndPortUtil.HostAndPort>();
private static List<HostAndPort> redisHostAndPortList = new ArrayList<HostAndPort>();
private static List<HostAndPort> sentinelHostAndPortList = new ArrayList<HostAndPort>();
private static List<HostAndPort> clusterHostAndPortList = new ArrayList<HostAndPort>();
static {
HostAndPort defaulthnp1 = new HostAndPort();
defaulthnp1.host = "localhost";
defaulthnp1.port = Protocol.DEFAULT_PORT;
redisHostAndPortList.add(defaulthnp1);
HostAndPort defaulthnp2 = new HostAndPort();
defaulthnp2.host = "localhost";
defaulthnp2.port = Protocol.DEFAULT_PORT + 1;
redisHostAndPortList.add(defaulthnp2);
HostAndPort defaulthnp3 = new HostAndPort();
defaulthnp3.host = "localhost";
defaulthnp3.port = Protocol.DEFAULT_PORT + 2;
redisHostAndPortList.add(defaulthnp3);
HostAndPort defaulthnp4 = new HostAndPort();
defaulthnp4.host = "localhost";
defaulthnp4.port = Protocol.DEFAULT_PORT + 3;
redisHostAndPortList.add(defaulthnp4);
HostAndPort defaulthnp5 = new HostAndPort();
defaulthnp5.host = "localhost";
defaulthnp5.port = Protocol.DEFAULT_PORT + 4;
redisHostAndPortList.add(defaulthnp5);
HostAndPort defaulthnp6 = new HostAndPort();
defaulthnp6.host = "localhost";
defaulthnp6.port = Protocol.DEFAULT_SENTINEL_PORT;
sentinelHostAndPortList.add(defaulthnp6);
HostAndPort defaulthnp7 = new HostAndPort();
defaulthnp7.host = "localhost";
defaulthnp7.port = Protocol.DEFAULT_SENTINEL_PORT + 1;
sentinelHostAndPortList.add(defaulthnp7);
HostAndPort defaulthnp8 = new HostAndPort();
defaulthnp8.host = "localhost";
defaulthnp8.port = Protocol.DEFAULT_SENTINEL_PORT + 2;
sentinelHostAndPortList.add(defaulthnp8);
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<HostAndPort> parseHosts(String envHosts, List<HostAndPort> existingHostsAndPorts) {
if (null != envHosts && 0 < envHosts.length()) {
String[] hostDefs = envHosts.split(",");
if (null != hostDefs && 2 <= hostDefs.length) {
List<HostAndPort> envHostsAndPorts = new ArrayList<HostAndPortUtil.HostAndPort>(hostDefs.length);
for (String hostDef : hostDefs) {
String[] hostAndPort = hostDef.split(":");
if (null != hostAndPort && 2 == hostAndPort.length) {
HostAndPort hnp = new HostAndPort();
hnp.host = hostAndPort[0];
try {
hnp.port = Integer.parseInt(hostAndPort[1]);
} catch (final NumberFormatException nfe) {
hnp.port = Protocol.DEFAULT_PORT;
}
envHostsAndPorts.add(hnp);
}
}
return envHostsAndPorts;
}
}
return existingHostsAndPorts;
public static List<HostAndPort> parseHosts(String envHosts,
List<HostAndPort> existingHostsAndPorts) {
if (null != envHosts && 0 < envHosts.length()) {
String[] hostDefs = envHosts.split(",");
if (null != hostDefs && 2 <= hostDefs.length) {
List<HostAndPort> envHostsAndPorts = new ArrayList<HostAndPort>(
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<HostAndPort> getRedisServers() {
return redisHostAndPortList;
}
public static List<HostAndPort> getSentinelServers() {
return sentinelHostAndPortList;
return redisHostAndPortList;
}
public static class HostAndPort {
public String host;
public int port;
@Override
public String toString() {
return host + ":" + port;
}
public static List<HostAndPort> getSentinelServers() {
return sentinelHostAndPortList;
}
public static List<HostAndPort> getClusterServers() {
return clusterHostAndPortList;
}
}

View File

@@ -0,0 +1,195 @@
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;
import org.junit.Test;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.exceptions.JedisAskDataException;
import redis.clients.jedis.exceptions.JedisClusterException;
import redis.clients.jedis.exceptions.JedisClusterMaxRedirectionsException;
import redis.clients.jedis.exceptions.JedisMovedDataException;
import redis.clients.util.JedisClusterCRC16;
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() 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", 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
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);
}
@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());
return;
}
fail();
}
@Test(expected = JedisAskDataException.class)
public void testThrowAskException() {
int keySlot = JedisClusterCRC16.getSlot("test");
String node3Id = getNodeId(node3.clusterNodes());
node2.clusterSetSlotMigrating(keySlot, node3Id);
node2.get("test");
}
@Test
public void testDiscoverNodesAutomatically() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode);
assertEquals(jc.getClusterNodes().size(), 3);
}
@Test
public void testCalculateConnectionPerSlot() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
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<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
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<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
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)
public void testThrowExceptionWithoutKey() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode);
jc.ping();
}
@Test(expected = JedisClusterMaxRedirectionsException.class)
public void testRedisClusterMaxRedirections() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
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);
}
}
}

View File

@@ -3,128 +3,120 @@ 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.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;
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);
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.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.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.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();
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();
}
@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.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)
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.getHost(), hnp.getPort());
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.getHost(), hnp.getPort(),
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.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);
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.getHost(),
hnp.getPort(), 2000, "foobared", 1);
Jedis jedis1 = pool1.getResource();
assertNull(jedis1.get("foo"));
pool1.returnResource(jedis1);
pool1.destroy();
}
@Test
@@ -145,43 +137,65 @@ 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.getHost(),
hnp.getPort(), 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.getHost(),
hnp.getPort(), 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();
}
@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();
}
}

View File

@@ -2,97 +2,173 @@ package redis.clients.jedis.tests;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.pool.impl.GenericObjectPool.Config;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.DebugParams;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;
import redis.clients.jedis.JedisSentinelPool;
import redis.clients.jedis.tests.HostAndPortUtil.HostAndPort;
import redis.clients.jedis.Transaction;
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);
.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 sentinelJedis1;
protected Set<String> sentinels = new HashSet<String>();
@Before
public void setUp() throws Exception {
// set up master and slaves
masterJedis = new Jedis(master.host, master.port);
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++;
sentinels.add(sentinel1.toString());
sentinels.add(sentinel2.toString());
// 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);
sentinelJedis1 = new Jedis(sentinel1.getHost(), sentinel1.getPort());
}
@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(MASTER_NAME, 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 {
HostAndPort oldMaster = pool.getCurrentHostMaster();
// 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 connection should be master
Jedis jedis = pool.getResource();
assertEquals("PONG", jedis.ping());
jedis = pool.getResource();
assertEquals("PONG", jedis.ping());
assertEquals("foobared", jedis.configGet("requirepass").get(1));
assertEquals(2, jedis.getDB().intValue());
try {
jedis.debug(DebugParams.SEGFAULT());
} catch (Exception e) {
}
waitForFailover(pool, oldMaster);
Thread.sleep(100);
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 {
waitForJedisSentinelPoolRecognizeNewMaster(pool);
}
private void waitForJedisSentinelPoolRecognizeNewMaster(
JedisSentinelPool pool) throws InterruptedException {
final AtomicReference<String> newmaster = new AtomicReference<String>(
"");
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();
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(100);
}
}
@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();
}
}

View File

@@ -1,9 +1,5 @@
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.List;
import java.util.Map;
@@ -11,33 +7,40 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
public class JedisSentinelTest {
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 sentinel = HostAndPortUtil
.getSentinelServers().get(0);
protected static Jedis masterJedis;
protected static Jedis slaveJedis;
protected static Jedis sentinelJedis;
@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);
}
@After
public void clear() {
Jedis j = new Jedis("localhost", 6380);
j.auth("foobared");
j.slaveofNoOne();
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
}
@Test
public void sentinel() {
Jedis j = new Jedis("localhost", 26379);
Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());
List<Map<String, String>> masters = j.sentinelMasters();
final String masterName = masters.get(0).get("name");
@@ -45,25 +48,18 @@ public class JedisSentinelTest {
List<String> 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<Map<String, String>> slaves = j.sentinelSlaves(masterName);
assertTrue(slaves.size() > 0);
assertEquals("6379", slaves.get(0).get("master-port"));
List<? extends Object> 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)));
assertEquals(master.getPort(),
Integer.parseInt(slaves.get(0).get("master-port")));
// DO NOT RE-RUN TEST TOO FAST, RESET TAKES SOME TIME TO... RESET
assertEquals(Long.valueOf(1), j.sentinelReset(masterName));
assertEquals(Long.valueOf(0), j.sentinelReset("woof" + masterName));
}
}

View File

@@ -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");
}

View File

@@ -8,18 +8,18 @@ import org.junit.Assert;
public abstract class JedisTestBase extends Assert {
protected void assertEquals(List<byte[]> expected, List<byte[]> 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<byte[]> expected, Set<byte[]> actual) {
assertEquals(expected.size(), actual.size());
Iterator<byte[]> iterator = expected.iterator();
Iterator<byte[]> iterator2 = actual.iterator();
while (iterator.hasNext() || iterator2.hasNext()) {
assertArrayEquals(iterator.next(), iterator2.next());
}
assertEquals(expected.size(), actual.size());
Iterator<byte[]> iterator = expected.iterator();
Iterator<byte[]> iterator2 = actual.iterator();
while (iterator.hasNext() || iterator2.hasNext()) {
assertArrayEquals(iterator.next(), iterator2.next());
}
}
}

View File

@@ -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,307 +27,321 @@ public class PipeliningTest extends Assert {
@Before
public void setUp() throws Exception {
jedis = new Jedis(hnp.host, hnp.port, 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<Object> results = jedis.pipelined(new PipelineBlock() {
public void execute() {
set("foo", "bar");
get("foo");
}
});
List<Object> 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> string = p.get("string");
Response<String> list = p.lpop("list");
Response<String> hash = p.hget("hash", "foo");
Response<Set<String>> zset = p.zrange("zset", 0, -1);
Response<String> set = p.spop("set");
Response<Boolean> blist = p.exists("list");
Response<Double> zincrby = p.zincrby("zset", 1, "foo");
Response<Long> zcard = p.zcard("zset");
p.lpush("list", "bar");
Response<List<String>> lrange = p.lrange("list", 0, -1);
Response<Map<String, String>> hgetAll = p.hgetAll("hash");
p.sadd("set", "foo");
Response<Set<String>> smembers = p.smembers("set");
Response<Set<Tuple>> zrangeWithScores = p.zrangeWithScores("zset", 0,
-1);
p.sync();
Pipeline p = jedis.pipelined();
Response<String> string = p.get("string");
Response<String> list = p.lpop("list");
Response<String> hash = p.hget("hash", "foo");
Response<Set<String>> zset = p.zrange("zset", 0, -1);
Response<String> set = p.spop("set");
Response<Boolean> blist = p.exists("list");
Response<Double> zincrby = p.zincrby("zset", 1, "foo");
Response<Long> zcard = p.zcard("zset");
p.lpush("list", "bar");
Response<List<String>> lrange = p.lrange("list", 0, -1);
Response<Map<String, String>> hgetAll = p.hgetAll("hash");
p.sadd("set", "foo");
Response<Set<String>> smembers = p.smembers("set");
Response<Set<Tuple>> 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<Double> score = p.zscore("zset", "foo");
p.sync();
jedis.zadd("zset", 1, "foo");
assertNotNull(score.get());
Pipeline p = jedis.pipelined();
Response<Double> 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<Map<byte[],byte[]>> fmap = p.hgetAll("key".getBytes());
Response<Set<byte[]>> fkeys = p.hkeys("key".getBytes());
Response<List<byte[]>> fordered = p.hmget("key".getBytes(), "f22".getBytes(), "f1".getBytes());
Response<List<byte[]>> fvals = p.hvals("key".getBytes());
p.sync();
Pipeline p = jedis.pipelined();
Response<Map<byte[], byte[]>> fmap = p.hgetAll("key".getBytes());
Response<Set<byte[]>> fkeys = p.hkeys("key".getBytes());
Response<List<byte[]>> fordered = p.hmget("key".getBytes(),
"f22".getBytes(), "f1".getBytes());
Response<List<byte[]>> 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<byte[],byte[]> map = fmap.get();
Set<byte[]> mapKeys = map.keySet();
Iterator<byte[]> 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<byte[], byte[]> map = fmap.get();
Set<byte[]> mapKeys = map.keySet();
Iterator<byte[]> 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<byte[]> 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<byte[]> 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<Double> score = p.zscore("zset", "bar");
p.sync();
jedis.zadd("zset", 1, "foo");
assertNull(score.get());
Pipeline p = jedis.pipelined();
Response<Double> 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> string = p.get("string");
string.get();
p.sync();
Pipeline p = jedis.pipelined();
Response<String> string = p.get("string");
string.get();
p.sync();
}
@Test
public void pipelineWithPubSub() {
Pipeline pipelined = jedis.pipelined();
Response<Long> p1 = pipelined.publish("foo", "bar");
Response<Long> p2 = pipelined.publish("foo".getBytes(), "bar"
.getBytes());
pipelined.sync();
assertEquals(0, p1.get().longValue());
assertEquals(0, p2.get().longValue());
Pipeline pipelined = jedis.pipelined();
Response<Long> p1 = pipelined.publish("foo", "bar");
Response<Long> 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<String> shouldNotExist = p.get(UUID.randomUUID().toString());
p.sync();
assertNull(shouldNotExist.get());
}
@Test
public void piplineWithError(){
Pipeline p = jedis.pipelined();
p.set("foo", "bar");
Response<Set<String>> error = p.smembers("foo");
Response<String> 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<String> shouldNotExist = p.get(UUID.randomUUID().toString());
p.sync();
assertNull(shouldNotExist.get());
}
@Test
public void multi(){
Pipeline p = jedis.pipelined();
p.multi();
Response<Long> r1 = p.hincrBy("a", "f1", -1);
Response<Long> r2 = p.hincrBy("a", "f1", -2);
Response<List<Object>> r3 = p.exec();
List<Object> 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<Object> multiResult = (List<Object>) 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<Set<String>> error = p.smembers("foo");
Response<String> 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<Long> r1 = p.hincrBy("a", "f1", -1);
Response<Long> r2 = p.hincrBy("a", "f1", -2);
Response<List<Object>> r3 = p.exec();
List<Object> 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<Object> multiResult = (List<Object>) 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<String> discard = pipeline.discard();
Response<String> get = pipeline.get("foo");
pipeline.sync();
discard.get();
get.get();
Pipeline pipeline = jedis.pipelined();
pipeline.multi();
pipeline.set("foo", "bar");
Response<String> discard = pipeline.discard();
Response<String> get = pipeline.get("foo");
pipeline.sync();
discard.get();
get.get();
}
@Test
public void testEval() {
String script = "return 'success!'";
Pipeline p = jedis.pipelined();
Response<String> result = p.eval(script);
p.sync();
@Test
public void testEval() {
String script = "return 'success!'";
assertEquals("success!", result.get());
}
Pipeline p = jedis.pipelined();
Response<String> 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<String> result0 = p.eval(script, Arrays.asList(key), Arrays.asList(arg));
p.incr(key);
Response<String> result1 = p.eval(script, Arrays.asList(key), Arrays.asList(arg));
Response<String> 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<String> result0 = p.eval(script, Arrays.asList(key),
Arrays.asList(arg));
p.incr(key);
Response<String> result1 = p.eval(script, Arrays.asList(key),
Arrays.asList(arg));
Response<String> 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<String> result = p.evalsha(sha1);
p.sync();
assertTrue(jedis.scriptExists(sha1));
assertEquals("success!", result.get());
}
Pipeline p = jedis.pipelined();
Response<String> 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<String> result0 = p.evalsha(sha1, Arrays.asList(key), Arrays.asList(arg));
p.incr(key);
Response<String> result1 = p.evalsha(sha1, Arrays.asList(key), Arrays.asList(arg));
Response<String> 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<String> result0 = p.evalsha(sha1, Arrays.asList(key),
Arrays.asList(arg));
p.incr(key);
Response<String> result1 = p.evalsha(sha1, Arrays.asList(key),
Arrays.asList(arg));
Response<String> result2 = p.get(key);
p.sync();
assertNull(result0.get());
assertNull(result1.get());
assertEquals("13", result2.get());
}
}

View File

@@ -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<byte[]> response = (List<byte[]>) Protocol
.read(new RedisInputStream(is));
List<byte[]> expected = new ArrayList<byte[]>();
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<byte[]> response = (List<byte[]>) Protocol
.read(new RedisInputStream(is));
List<byte[]> expected = new ArrayList<byte[]>();
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<String> response = (List<String>) Protocol
.read(new RedisInputStream(is));
assertNull(response);
InputStream is = new ByteArrayInputStream("*-1\r\n".getBytes());
List<String> response = (List<String>) Protocol
.read(new RedisInputStream(is));
assertNull(response);
}
}

View File

@@ -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;
@@ -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,105 +25,109 @@ import redis.clients.jedis.Tuple;
import redis.clients.jedis.exceptions.JedisDataException;
public class ShardedJedisPipelineTest {
private static HostAndPortUtil.HostAndPort redis1 = HostAndPortUtil
.getRedisServers().get(0);
private static HostAndPortUtil.HostAndPort redis2 = HostAndPortUtil
.getRedisServers().get(1);
private static HostAndPort redis1 = HostAndPortUtil.getRedisServers()
.get(0);
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.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.getHost(), redis1.getPort());
jedis.auth("foobared");
jedis.flushAll();
jedis.disconnect();
jedis = new Jedis(redis2.getHost(), redis2.getPort());
jedis.auth("foobared");
jedis.flushAll();
jedis.disconnect();
JedisShardInfo shardInfo1 = new JedisShardInfo(redis1.getHost(),
redis1.getPort());
JedisShardInfo shardInfo2 = new JedisShardInfo(redis2.getHost(),
redis2.getPort());
shardInfo1.setPassword("foobared");
shardInfo2.setPassword("foobared");
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
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<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
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<Object> results = p.syncAndReturnAll();
ShardedJedisPipeline p = jedis.pipelined();
p.set("foo", "bar");
p.get("foo");
List<Object> 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> string = p.get("string");
Response<Long> del = p.del("string");
Response<String> emptyString = p.get("string");
Response<String> list = p.lpop("list");
Response<String> hash = p.hget("hash", "foo");
Response<Set<String>> zset = p.zrange("zset", 0, -1);
Response<String> set = p.spop("set");
Response<Boolean> blist = p.exists("list");
Response<Double> zincrby = p.zincrby("zset", 1, "foo");
Response<Long> zcard = p.zcard("zset");
p.lpush("list", "bar");
Response<List<String>> lrange = p.lrange("list", 0, -1);
Response<Map<String, String>> hgetAll = p.hgetAll("hash");
p.sadd("set", "foo");
Response<Set<String>> smembers = p.smembers("set");
Response<Set<Tuple>> zrangeWithScores = p.zrangeWithScores("zset", 0,
-1);
p.sync();
ShardedJedisPipeline p = jedis.pipelined();
Response<String> string = p.get("string");
Response<Long> del = p.del("string");
Response<String> emptyString = p.get("string");
Response<String> list = p.lpop("list");
Response<String> hash = p.hget("hash", "foo");
Response<Set<String>> zset = p.zrange("zset", 0, -1);
Response<String> set = p.spop("set");
Response<Boolean> blist = p.exists("list");
Response<Double> zincrby = p.zincrby("zset", 1, "foo");
Response<Long> zcard = p.zcard("zset");
p.lpush("list", "bar");
Response<List<String>> lrange = p.lrange("list", 0, -1);
Response<Map<String, String>> hgetAll = p.hgetAll("hash");
p.sadd("set", "foo");
Response<Set<String>> smembers = p.smembers("set");
Response<Set<Tuple>> 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> string = p.get("string");
string.get();
p.sync();
ShardedJedisPipeline p = jedis.pipelined();
Response<String> string = p.get("string");
string.get();
p.sync();
}
@Test
public void canRetrieveUnsetKey() {
ShardedJedisPipeline p = jedis.pipelined();
Response<String> shouldNotExist = p.get(UUID.randomUUID().toString());
p.sync();
assertNull(shouldNotExist.get());
ShardedJedisPipeline p = jedis.pipelined();
Response<String> shouldNotExist = p.get(UUID.randomUUID().toString());
p.sync();
assertNull(shouldNotExist.get());
}
}

View File

@@ -5,222 +5,230 @@ 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;
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()
.get(0);
.get(0);
private static HostAndPort redis2 = HostAndPortUtil.getRedisServers()
.get(1);
.get(1);
private List<JedisShardInfo> shards;
@Before
public void startUp() {
shards = new ArrayList<JedisShardInfo>();
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<JedisShardInfo>();
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));
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<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
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<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
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"));

View File

@@ -6,298 +6,300 @@ 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;
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<String> getKeysDifferentShard(ShardedJedis jedis) {
List<String> ret = new ArrayList<String>();
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<String> ret = new ArrayList<String>();
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<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(redis1.host, redis1.port));
shards.add(new JedisShardInfo(redis2.host, redis2.port));
ShardedJedis jedis = new ShardedJedis(shards);
List<String> keys = getKeysDifferentShard(jedis);
JedisShardInfo s1 = jedis.getShardInfo(keys.get(0));
JedisShardInfo s2 = jedis.getShardInfo(keys.get(1));
assertNotSame(s1, s2);
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(redis1.getHost(), redis1.getPort()));
shards.add(new JedisShardInfo(redis2.getHost(), redis2.getPort()));
ShardedJedis jedis = new ShardedJedis(shards);
List<String> 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<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
JedisShardInfo si = new JedisShardInfo(redis1.host, redis1.port);
si.setPassword("foobared");
shards.add(si);
si = new JedisShardInfo(redis2.host, redis2.port);
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<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
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<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
JedisShardInfo si = new JedisShardInfo(redis1.host, redis1.port);
si.setPassword("foobared");
shards.add(si);
si = new JedisShardInfo(redis2.host, redis2.port);
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<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
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<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(redis1.host, redis1.port));
shards.add(new JedisShardInfo(redis2.host, redis2.port));
ShardedJedis jedis = new ShardedJedis(shards,
ShardedJedis.DEFAULT_KEY_TAG_PATTERN);
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
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<String> keys = getKeysDifferentShard(jedis);
JedisShardInfo s3 = jedis.getShardInfo(keys.get(0));
JedisShardInfo s4 = jedis.getShardInfo(keys.get(1));
assertNotSame(s3, s4);
List<String> 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<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
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");
ShardedJedis jedis = new ShardedJedis(shards);
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
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<String> keys = getKeysDifferentShard(jedis);
jedis.set(keys.get(0), "a");
jedis.set(keys.get(1), "b");
final List<String> 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<Object> results = jedis.pipelined(new ShardedJedisPipeline() {
public void execute() {
get(keys.get(0));
get(keys.get(1));
}
});
List<Object> results = jedis.pipelined(new ShardedJedisPipeline() {
public void execute() {
get(keys.get(0));
get(keys.get(1));
}
});
List<Object> expected = new ArrayList<Object>(2);
expected.add(SafeEncoder.encode("a"));
expected.add(SafeEncoder.encode("b"));
List<Object> expected = new ArrayList<Object>(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<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(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<Jedis, JedisShardInfo> sharded = new Sharded<Jedis, JedisShardInfo>(
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<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(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<Jedis, JedisShardInfo> sharded = new Sharded<Jedis, JedisShardInfo>(
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<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(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<Jedis, JedisShardInfo> sharded = new Sharded<Jedis, JedisShardInfo>(
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<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(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<Jedis, JedisShardInfo> sharded = new Sharded<Jedis, JedisShardInfo>(
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<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(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<Jedis, JedisShardInfo> sharded = new Sharded<Jedis, JedisShardInfo>(
shards, Hashing.MURMUR_HASH);
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(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<Jedis, JedisShardInfo> sharded = new Sharded<Jedis, JedisShardInfo>(
shards, Hashing.MURMUR_HASH);
List<JedisShardInfo> otherShards = new ArrayList<JedisShardInfo>(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<Jedis, JedisShardInfo> sharded2 = new Sharded<Jedis, JedisShardInfo>(
otherShards, Hashing.MURMUR_HASH);
List<JedisShardInfo> otherShards = new ArrayList<JedisShardInfo>(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<Jedis, JedisShardInfo> sharded2 = new Sharded<Jedis, JedisShardInfo>(
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<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(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<Jedis, JedisShardInfo> sharded = new Sharded<Jedis, JedisShardInfo>(
shards, Hashing.MURMUR_HASH);
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(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<Jedis, JedisShardInfo> sharded = new Sharded<Jedis, JedisShardInfo>(
shards, Hashing.MURMUR_HASH);
List<JedisShardInfo> otherShards = new ArrayList<JedisShardInfo>(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<Jedis, JedisShardInfo> sharded2 = new Sharded<Jedis, JedisShardInfo>(
otherShards, Hashing.MURMUR_HASH);
List<JedisShardInfo> otherShards = new ArrayList<JedisShardInfo>(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<Jedis, JedisShardInfo> sharded2 = new Sharded<Jedis, JedisShardInfo>(
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());
}
}
}

View File

@@ -4,17 +4,17 @@ 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);
private static HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0);
private static final int TOTAL_OPERATIONS = 100000;
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();

View File

@@ -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);
@@ -19,32 +19,33 @@ public class HashingBenchmark {
private static final int TOTAL_OPERATIONS = 100000;
public static void main(String[] args) throws UnknownHostException,
IOException {
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
JedisShardInfo shard = new JedisShardInfo(hnp1.host, hnp1.port);
shard.setPassword("foobared");
shards.add(shard);
shard = new JedisShardInfo(hnp2.host, hnp2.port);
shard.setPassword("foobared");
shards.add(shard);
ShardedJedis jedis = new ShardedJedis(shards);
Collection<Jedis> allShards = jedis.getAllShards();
for (Jedis j : allShards) {
j.flushAll();
}
IOException {
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
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<Jedis> 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");
}
}

View File

@@ -4,36 +4,36 @@ 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);
private static final int TOTAL_OPERATIONS = 200000;
public static void main(String[] args) throws UnknownHostException,
IOException {
Jedis jedis = new Jedis(hnp.host, hnp.port);
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");
}
}

View File

@@ -4,60 +4,61 @@ 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.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);
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.getHost(), hnp.getPort());
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<Thread> tds = new ArrayList<Thread>();
final JedisPool pool = new JedisPool(new GenericObjectPoolConfig(),
hnp.getHost(), hnp.getPort(), 2000, "foobared");
List<Thread> tds = new ArrayList<Thread>();
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();
}
}

View File

@@ -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");
}
}

View File

@@ -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");
}
}

View File

@@ -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,489 +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<String> keys = jedis.keys("foo*");
Set<String> expected = new HashSet<String>();
expected.add("foo");
expected.add("foobar");
assertEquals(expected, keys);
Set<String> keys = jedis.keys("foo*");
Set<String> expected = new HashSet<String>();
expected.add("foo");
expected.add("foobar");
assertEquals(expected, keys);
expected = new HashSet<String>();
keys = jedis.keys("bar*");
expected = new HashSet<String>();
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<byte[]> bkeys = jedis.keys(bfoostar);
assertEquals(2, bkeys.size());
assertTrue(setContains(bkeys, bfoo));
assertTrue(setContains(bkeys, bfoobar));
Set<byte[]> 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() {
// 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);
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);
// 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(-2, bttl);
// Binary
long bttl = jedis.ttl(bfoo);
assertEquals(-1, 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(-1, 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<String> 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<String> 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<String> result = jedis.scan(0, params);
assertFalse(result.getResult().isEmpty());
}
}

View File

@@ -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<byte[]> values = jedis.mget(bfoo, bbar);
List<byte[]> expected = new ArrayList<byte[]>();
expected.add(null);
expected.add(null);
List<byte[]> values = jedis.mget(bfoo, bbar);
List<byte[]> expected = new ArrayList<byte[]>();
expected.add(null);
expected.add(null);
assertEquals(expected, values);
assertEquals(expected, values);
jedis.set(bfoo, binaryValue);
jedis.set(bfoo, binaryValue);
expected = new ArrayList<byte[]>();
expected.add(binaryValue);
expected.add(null);
values = jedis.mget(bfoo, bbar);
expected = new ArrayList<byte[]>();
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<byte[]>();
expected.add(binaryValue);
expected.add(bfoo);
values = jedis.mget(bfoo, bbar);
expected = new ArrayList<byte[]>();
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());
}
}

View File

@@ -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");
}
}

View File

@@ -0,0 +1,141 @@
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;
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;
public class ClusterCommandsTest extends JedisTestBase {
private static Jedis node1;
private static Jedis node2;
private HostAndPort nodeInfo1 = HostAndPortUtil.getClusterServers().get(0);
private HostAndPort nodeInfo2 = HostAndPortUtil.getClusterServers().get(1);
@Before
public void setUp() throws Exception {
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();
}
@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
}
}
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);
}
@Test
public void clusterMeet() {
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<String> 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);
}
}

View File

@@ -3,20 +3,20 @@ 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);
@Test
public void quit() {
assertEquals("OK", jedis.quit());
assertEquals("OK", jedis.quit());
}
@Test
public void binary_quit() {
BinaryJedis bj = new BinaryJedis(hnp.host);
assertEquals("OK", bj.quit());
BinaryJedis bj = new BinaryJedis(hnp.getHost());
assertEquals("OK", bj.quit());
}
}

View File

@@ -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
@@ -71,16 +61,16 @@ public class ControlCommandsTest extends JedisCommandTestBase {
public void monitor() {
new Thread(new Runnable() {
public void run() {
Jedis j = new Jedis("localhost");
j.auth("foobared");
for (int i = 0; i < 4; i++) {
j.incr("foobared");
}
try {
Thread.sleep(2500);
// sleep 100ms to make sure that monitor thread runs first
Thread.sleep(100);
} catch (InterruptedException e) {
}
j.incr("foobared");
Jedis j = new Jedis("localhost");
j.auth("foobared");
for (int i = 0; i < 5; i++) {
j.incr("foobared");
}
j.disconnect();
}
}).start();
@@ -127,4 +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());
}
}

View File

@@ -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,314 @@ 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<String, String> hash = new HashMap<String, String>();
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<String, String> hash = new HashMap<String, String>();
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<byte[], byte[]> bhash = new HashMap<byte[], byte[]>();
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<byte[], byte[]> bhash = new HashMap<byte[], byte[]>();
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<String, String> hash = new HashMap<String, String>();
hash.put("bar", "car");
hash.put("car", "bar");
jedis.hmset("foo", hash);
Map<String, String> hash = new HashMap<String, String>();
hash.put("bar", "car");
hash.put("car", "bar");
jedis.hmset("foo", hash);
List<String> values = jedis.hmget("foo", "bar", "car", "foo");
List<String> expected = new ArrayList<String>();
expected.add("car");
expected.add("bar");
expected.add(null);
List<String> values = jedis.hmget("foo", "bar", "car", "foo");
List<String> expected = new ArrayList<String>();
expected.add("car");
expected.add("bar");
expected.add(null);
assertEquals(expected, values);
assertEquals(expected, values);
// Binary
Map<byte[], byte[]> bhash = new HashMap<byte[], byte[]>();
bhash.put(bbar, bcar);
bhash.put(bcar, bbar);
jedis.hmset(bfoo, bhash);
// Binary
Map<byte[], byte[]> bhash = new HashMap<byte[], byte[]>();
bhash.put(bbar, bcar);
bhash.put(bcar, bbar);
jedis.hmset(bfoo, bhash);
List<byte[]> bvalues = jedis.hmget(bfoo, bbar, bcar, bfoo);
List<byte[]> bexpected = new ArrayList<byte[]>();
bexpected.add(bcar);
bexpected.add(bbar);
bexpected.add(null);
List<byte[]> bvalues = jedis.hmget(bfoo, bbar, bcar, bfoo);
List<byte[]> bexpected = new ArrayList<byte[]>();
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<String, String> hash = new HashMap<String, String>();
hash.put("bar", "car");
hash.put("car", "bar");
jedis.hmset("foo", hash);
Map<String, String> hash = new HashMap<String, String>();
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<byte[], byte[]> bhash = new HashMap<byte[], byte[]>();
bhash.put(bbar, bcar);
bhash.put(bcar, bbar);
jedis.hmset(bfoo, bhash);
// Binary
Map<byte[], byte[]> bhash = new HashMap<byte[], byte[]>();
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<String, String> hash = new HashMap<String, String>();
hash.put("bar", "car");
hash.put("car", "bar");
jedis.hmset("foo", hash);
Map<String, String> hash = new HashMap<String, String>();
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<byte[], byte[]> bhash = new HashMap<byte[], byte[]>();
bhash.put(bbar, bcar);
bhash.put(bcar, bbar);
jedis.hmset(bfoo, bhash);
// Binary
Map<byte[], byte[]> bhash = new HashMap<byte[], byte[]>();
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<String, String> hash = new HashMap<String, String>();
hash.put("bar", "car");
hash.put("car", "bar");
jedis.hmset("foo", hash);
Map<String, String> hash = new HashMap<String, String>();
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<byte[], byte[]> bhash = new HashMap<byte[], byte[]>();
bhash.put(bbar, bcar);
bhash.put(bcar, bbar);
jedis.hmset(bfoo, bhash);
// Binary
Map<byte[], byte[]> bhash = new HashMap<byte[], byte[]>();
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<String, String> hash = new LinkedHashMap<String, String>();
hash.put("bar", "car");
hash.put("car", "bar");
jedis.hmset("foo", hash);
Map<String, String> hash = new LinkedHashMap<String, String>();
hash.put("bar", "car");
hash.put("car", "bar");
jedis.hmset("foo", hash);
Set<String> keys = jedis.hkeys("foo");
Set<String> expected = new LinkedHashSet<String>();
expected.add("bar");
expected.add("car");
assertEquals(expected, keys);
Set<String> keys = jedis.hkeys("foo");
Set<String> expected = new LinkedHashSet<String>();
expected.add("bar");
expected.add("car");
assertEquals(expected, keys);
// Binary
Map<byte[], byte[]> bhash = new LinkedHashMap<byte[], byte[]>();
bhash.put(bbar, bcar);
bhash.put(bcar, bbar);
jedis.hmset(bfoo, bhash);
// Binary
Map<byte[], byte[]> bhash = new LinkedHashMap<byte[], byte[]>();
bhash.put(bbar, bcar);
bhash.put(bcar, bbar);
jedis.hmset(bfoo, bhash);
Set<byte[]> bkeys = jedis.hkeys(bfoo);
Set<byte[]> bexpected = new LinkedHashSet<byte[]>();
bexpected.add(bbar);
bexpected.add(bcar);
assertEquals(bexpected, bkeys);
Set<byte[]> bkeys = jedis.hkeys(bfoo);
Set<byte[]> bexpected = new LinkedHashSet<byte[]>();
bexpected.add(bbar);
bexpected.add(bcar);
assertEquals(bexpected, bkeys);
}
@Test
public void hvals() {
Map<String, String> hash = new LinkedHashMap<String, String>();
hash.put("bar", "car");
hash.put("car", "bar");
jedis.hmset("foo", hash);
Map<String, String> hash = new LinkedHashMap<String, String>();
hash.put("bar", "car");
hash.put("car", "bar");
jedis.hmset("foo", hash);
List<String> vals = jedis.hvals("foo");
assertEquals(2, vals.size());
assertTrue(vals.contains("bar"));
assertTrue(vals.contains("car"));
List<String> vals = jedis.hvals("foo");
assertEquals(2, vals.size());
assertTrue(vals.contains("bar"));
assertTrue(vals.contains("car"));
// Binary
Map<byte[], byte[]> bhash = new LinkedHashMap<byte[], byte[]>();
bhash.put(bbar, bcar);
bhash.put(bcar, bbar);
jedis.hmset(bfoo, bhash);
// Binary
Map<byte[], byte[]> bhash = new LinkedHashMap<byte[], byte[]>();
bhash.put(bbar, bcar);
bhash.put(bcar, bbar);
jedis.hmset(bfoo, bhash);
List<byte[]> bvals = jedis.hvals(bfoo);
List<byte[]> 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<String, String> h = new HashMap<String, String>();
h.put("bar", "car");
h.put("car", "bar");
jedis.hmset("foo", h);
Map<String, String> h = new HashMap<String, String>();
h.put("bar", "car");
h.put("car", "bar");
jedis.hmset("foo", h);
Map<String, String> hash = jedis.hgetAll("foo");
assertEquals(2, hash.size());
assertEquals("car", hash.get("bar"));
assertEquals("bar", hash.get("car"));
Map<String, String> hash = jedis.hgetAll("foo");
assertEquals(2, hash.size());
assertEquals("car", hash.get("bar"));
assertEquals("bar", hash.get("car"));
// Binary
Map<byte[], byte[]> bh = new HashMap<byte[], byte[]>();
bh.put(bbar, bcar);
bh.put(bcar, bbar);
jedis.hmset(bfoo, bh);
Map<byte[], byte[]> bhash = jedis.hgetAll(bfoo);
// Binary
Map<byte[], byte[]> bh = new HashMap<byte[], byte[]>();
bh.put(bbar, bcar);
bh.put(bcar, bbar);
jedis.hmset(bfoo, bh);
Map<byte[], byte[]> 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<Map.Entry<String, String>> 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<Map.Entry<String, String>> 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<Map.Entry<String, String>> result = jedis.hscan("foo", 0,
params);
assertFalse(result.getResult().isEmpty());
}
}

View File

@@ -1,95 +1,96 @@
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);
protected Jedis jedis;
public JedisCommandTestBase() {
super();
super();
}
@Before
public void setUp() throws Exception {
jedis = new Jedis(hnp.host, hnp.port, 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.host, hnp.port);
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<byte[]> expected, List<byte[]> 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<byte[]> expected, Set<byte[]> actual) {
assertEquals(expected.size(), actual.size());
Iterator<byte[]> 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<byte[]> 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<byte[]> 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<byte[]> 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;
}
}

View File

@@ -26,607 +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<String> expected = new ArrayList<String>();
expected.add("a");
expected.add("b");
expected.add("c");
List<String> expected = new ArrayList<String>();
expected.add("a");
expected.add("b");
expected.add("c");
List<String> range = jedis.lrange("foo", 0, 2);
assertEquals(expected, range);
List<String> 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<String>();
expected.add("b");
expected.add("c");
expected = new ArrayList<String>();
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<String>();
range = jedis.lrange("foo", 2, 1);
assertEquals(expected, range);
expected = new ArrayList<String>();
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<byte[]> bexpected = new ArrayList<byte[]>();
bexpected.add(bA);
bexpected.add(bB);
bexpected.add(bC);
List<byte[]> bexpected = new ArrayList<byte[]>();
bexpected.add(bA);
bexpected.add(bB);
bexpected.add(bC);
List<byte[]> brange = jedis.lrange(bfoo, 0, 2);
assertEquals(bexpected, brange);
List<byte[]> 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<byte[]>();
bexpected.add(bB);
bexpected.add(bC);
bexpected = new ArrayList<byte[]>();
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<byte[]>();
brange = jedis.lrange(bfoo, 2, 1);
assertEquals(bexpected, brange);
bexpected = new ArrayList<byte[]>();
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<String> expected = new ArrayList<String>();
expected.add("3");
expected.add("2");
List<String> expected = new ArrayList<String>();
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<byte[]> bexpected = new ArrayList<byte[]>();
bexpected.add(b3);
bexpected.add(b2);
List<byte[]> bexpected = new ArrayList<byte[]>();
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<String> expected = new ArrayList<String>();
expected.add("3");
expected.add("bar");
expected.add("1");
List<String> expected = new ArrayList<String>();
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<byte[]> bexpected = new ArrayList<byte[]>();
bexpected.add(b3);
bexpected.add(bbar);
bexpected.add(b1);
List<byte[]> bexpected = new ArrayList<byte[]>();
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<String> expected = new ArrayList<String>();
expected.add("a");
expected.add("b");
expected.add("c");
expected.add("hello");
expected.add("x");
List<String> expected = new ArrayList<String>();
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<byte[]> bexpected = new ArrayList<byte[]>();
bexpected.add(bA);
bexpected.add(bB);
bexpected.add(bC);
bexpected.add(bhello);
bexpected.add(bx);
List<byte[]> bexpected = new ArrayList<byte[]>();
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<String> expected = new ArrayList<String>();
expected.add("b");
expected.add("c");
List<String> expected = new ArrayList<String>();
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<byte[]> bexpected = new ArrayList<byte[]>();
bexpected.add(bB);
bexpected.add(bC);
List<byte[]> bexpected = new ArrayList<byte[]>();
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<String> expected = new ArrayList<String>();
expected.add("a");
expected.add("b");
List<String> expected = new ArrayList<String>();
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<byte[]> bexpected = new ArrayList<byte[]>();
bexpected.add(bA);
bexpected.add(bB);
List<byte[]> bexpected = new ArrayList<byte[]>();
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<String> srcExpected = new ArrayList<String>();
srcExpected.add("a");
srcExpected.add("b");
List<String> srcExpected = new ArrayList<String>();
srcExpected.add("a");
srcExpected.add("b");
List<String> dstExpected = new ArrayList<String>();
dstExpected.add("c");
dstExpected.add("foo");
dstExpected.add("bar");
List<String> dstExpected = new ArrayList<String>();
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<byte[]> bsrcExpected = new ArrayList<byte[]>();
bsrcExpected.add(bA);
bsrcExpected.add(bB);
List<byte[]> bsrcExpected = new ArrayList<byte[]>();
bsrcExpected.add(bA);
bsrcExpected.add(bB);
List<byte[]> bdstExpected = new ArrayList<byte[]>();
bdstExpected.add(bC);
bdstExpected.add(bfoo);
bdstExpected.add(bbar);
List<byte[]> bdstExpected = new ArrayList<byte[]>();
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<String> result = jedis.blpop(1, "foo");
assertNull(result);
List<String> 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");
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
List<byte[]> bresult = jedis.blpop(1, bfoo);
assertNull(bresult);
// Binary
jedis.lpush(bfoo, bbar);
List<byte[]> bresult = jedis.blpop(1, bfoo);
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));
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<String> result = jedis.brpop(1, "foo");
assertNull(result);
List<String> 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());
assertEquals("foo", result.get(0));
assertEquals("bar", result.get(1));
result = jedis.brpop(1, "foo");
assertNotNull(result);
assertEquals(2, result.size());
assertEquals("foo", result.get(0));
assertEquals("bar", result.get(1));
// Binary
// Binary
List<byte[]> 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));
assertArrayEquals(bbar, bresult.get(1));
jedis.lpush(bfoo, bbar);
List<byte[]> 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<String> actual = jedis.lrange("foo", 0, 100);
List<String> expected = new ArrayList<String>();
expected.add("a");
expected.add("b");
List<String> actual = jedis.lrange("foo", 0, 100);
List<String> expected = new ArrayList<String>();
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<byte[]> bactual = jedis.lrange(bfoo, 0, 100);
List<byte[]> bexpected = new ArrayList<byte[]>();
bexpected.add(bA);
bexpected.add(bB);
List<byte[]> bactual = jedis.lrange(bfoo, 0, 100);
List<byte[]> bexpected = new ArrayList<byte[]>();
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(2000);
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));
}
}

View File

@@ -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);
}
}

View File

@@ -3,529 +3,578 @@ 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 {
private void publishOne(final String channel, final String message) {
Thread t = new Thread(new Runnable() {
public void run() {
try {
Jedis j = createJedis();
j.publish(channel, message);
j.disconnect();
} catch (Exception ex) {
}
}
});
t.start();
}
@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();
}
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);
}
// now that I'm subscribed... publish
publishOne("foo", "exit");
}
public void onPSubscribe(String pattern, int subscribedChannels) {
}
public void onUnsubscribe(String channel, int subscribedChannels) {
assertEquals("foo", channel);
assertEquals(0, subscribedChannels);
}
public void onPUnsubscribe(String pattern, int subscribedChannels) {
}
public void onPSubscribe(String pattern, int subscribedChannels) {
}
public void onPMessage(String pattern, String channel,
String message) {
}
}, "foo");
t.join();
public void onPUnsubscribe(String pattern, int subscribedChannels) {
}
public void onPMessage(String pattern, String channel,
String message) {
}
}, "foo");
}
@Test
public void pubSubChannels(){
final List<String> 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<String> activeChannels = otherJedis.pubsubChannels("test*");
assertTrue(expectedActiveChannels.containsAll(activeChannels));
unsubscribe();
}
}
@Override
public void onPUnsubscribe(String pattern, int subscribedChannels) {
}
@Override
public void onPSubscribe(String pattern, int subscribedChannels) {
}
@Override
public void onPMessage(String pattern, String channel, String message) {
}
@Override
public void onMessage(String channel, String message) {
}
}, "testchan1", "testchan2", "testchan3");
}
@Test
public void pubSubNumPat(){
jedis.psubscribe(new JedisPubSub() {
private int count=0;
@Override
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<String, String> expectedNumSub = new HashMap<String, String>();
expectedNumSub.put("testchannel2", "1");
expectedNumSub.put("testchannel1", "1");
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<String, String> 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,
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 {
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) {
publishOne(channel, "exit");
}
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");
}
@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 {
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);
publishOne("foo.bar", "exit");
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 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.*");
}
@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 {
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) {
publishOne(pattern.replace("*", "123"), "exit");
}
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.*");
}
@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) {
publishOne(channel, "exit");
if (!channel.equals("bar")) {
this.subscribe("bar");
this.psubscribe("bar.*");
}
}
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) {
publishOne(pattern.replace("*", "123"), "exit");
}
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();
jedis.subscribe(pubsub, "foo");
}
@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 {
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);
publishOne(SafeEncoder.encode(channel), "exit");
}
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"));
}
@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 {
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) {
publishOne(SafeEncoder.encode(channel), "exit");
}
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"));
}
@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 {
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);
publishOne(SafeEncoder.encode(pattern).replace("*", "bar"),
"exit");
}
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.*"));
}
@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 {
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) {
publishOne(SafeEncoder.encode(pattern).replace("*", "123"),
"exit");
}
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.*"));
}
@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) {
publishOne(SafeEncoder.encode(channel), "exit");
public void onUnsubscribe(byte[] channel, int subscribedChannels) {
}
if (!SafeEncoder.encode(channel).equals("bar")) {
this.subscribe(SafeEncoder.encode("bar"));
this.psubscribe(SafeEncoder.encode("bar.*"));
}
}
public void onPSubscribe(byte[] pattern, int subscribedChannels) {
}
public void onUnsubscribe(byte[] channel, int subscribedChannels) {
}
public void onPUnsubscribe(byte[] pattern, int subscribedChannels) {
}
public void onPSubscribe(byte[] pattern, int subscribedChannels) {
publishOne(SafeEncoder.encode(pattern).replace("*", "123"),
"exit");
}
public void onPMessage(byte[] pattern, byte[] channel,
byte[] message) {
punsubscribe(pattern);
}
};
public void onPUnsubscribe(byte[] pattern, int subscribedChannels) {
}
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();
}
public void onPMessage(byte[] pattern, byte[] channel,
byte[] message) {
punsubscribe(pattern);
}
};
@Test @Ignore
public void subscribeWithoutConnecting() {
try {
Jedis jedis = new Jedis(hnp.host, hnp.port);
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
}
jedis.subscribe(pubsub, SafeEncoder.encode("foo"));
}
@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 Jedis j = createJedis();
final AtomicBoolean exit = new AtomicBoolean(false);
final Thread t = new Thread(new Runnable() {
public void run() {
try {
// 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 100M data for making situation for exceed
// client-output-buffer-limit
String veryLargeString = makeLargeString(10485760);
// 10M * 10 = 100M
for (int i = 0; i < 10 && !exit.get(); i++) {
j.publish("foo", veryLargeString);
}
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(100);
} 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");
} finally {
// exit the publisher thread. if exception is thrown, thread might
// still keep publishing things.
exit.set(true);
if (t.isAlive()) {
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();
}
}

View File

@@ -3,6 +3,8 @@ package redis.clients.jedis.tests.commands;
import org.hamcrest.CoreMatchers;
import org.hamcrest.core.CombinableMatcher;
import org.junit.Test;
import redis.clients.jedis.BinaryJedis;
import redis.clients.jedis.exceptions.JedisDataException;
import redis.clients.util.SafeEncoder;
@@ -18,7 +20,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<String> keys = new ArrayList<String>();
keys.add("key1");
keys.add("key2");
@@ -26,14 +28,44 @@ public class ScriptingCommandsTest extends JedisCommandTestBase {
List<String> args = new ArrayList<String>();
args.add("first");
args.add("second");
args.add("third");
List<String> response = (List<String>) 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<byte[]> keys = new ArrayList<byte[]>();
keys.add("key1".getBytes());
keys.add("key2".getBytes());
List<byte[]> args = new ArrayList<byte[]>();
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<byte[]> responses = (List<byte[]>) 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
@@ -176,4 +208,3 @@ public class ScriptingCommandsTest extends JedisCommandTestBase {
return both(CoreMatchers.<List<T>>instanceOf(List.class)).and(hasItem(equalTo(expected)));
}
}

View File

@@ -6,6 +6,9 @@ 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 };
@@ -18,437 +21,469 @@ 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<String> expected = new HashSet<String>();
expected.add("a");
expected.add("b");
Set<String> expected = new HashSet<String>();
expected.add("a");
expected.add("b");
Set<String> members = jedis.smembers("foo");
Set<String> 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<byte[]> bexpected = new HashSet<byte[]>();
bexpected.add(bb);
bexpected.add(ba);
Set<byte[]> bexpected = new HashSet<byte[]>();
bexpected.add(bb);
bexpected.add(ba);
Set<byte[]> bmembers = jedis.smembers(bfoo);
Set<byte[]> 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<String> expected = new HashSet<String>();
expected.add("b");
Set<String> expected = new HashSet<String>();
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<byte[]> bexpected = new HashSet<byte[]>();
bexpected.add(bb);
Set<byte[]> bexpected = new HashSet<byte[]>();
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<String> expectedSrc = new HashSet<String>();
expectedSrc.add("b");
Set<String> expectedSrc = new HashSet<String>();
expectedSrc.add("b");
Set<String> expectedDst = new HashSet<String>();
expectedDst.add("c");
expectedDst.add("a");
Set<String> expectedDst = new HashSet<String>();
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<byte[]> bexpectedSrc = new HashSet<byte[]>();
bexpectedSrc.add(bb);
Set<byte[]> bexpectedSrc = new HashSet<byte[]>();
bexpectedSrc.add(bb);
Set<byte[]> bexpectedDst = new HashSet<byte[]>();
bexpectedDst.add(bc);
bexpectedDst.add(ba);
Set<byte[]> bexpectedDst = new HashSet<byte[]>();
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<String> expected = new HashSet<String>();
expected.add("b");
Set<String> expected = new HashSet<String>();
expected.add("b");
Set<String> intersection = jedis.sinter("foo", "bar");
assertEquals(expected, intersection);
Set<String> 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<byte[]> bexpected = new HashSet<byte[]>();
bexpected.add(bb);
Set<byte[]> bexpected = new HashSet<byte[]>();
bexpected.add(bb);
Set<byte[]> bintersection = jedis.sinter(bfoo, bbar);
assertEquals(bexpected, bintersection);
Set<byte[]> 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<String> expected = new HashSet<String>();
expected.add("b");
Set<String> expected = new HashSet<String>();
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<byte[]> bexpected = new HashSet<byte[]>();
bexpected.add(bb);
Set<byte[]> bexpected = new HashSet<byte[]>();
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<String> expected = new HashSet<String>();
expected.add("a");
expected.add("b");
expected.add("c");
Set<String> expected = new HashSet<String>();
expected.add("a");
expected.add("b");
expected.add("c");
Set<String> union = jedis.sunion("foo", "bar");
assertEquals(expected, union);
Set<String> 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<byte[]> bexpected = new HashSet<byte[]>();
bexpected.add(bb);
bexpected.add(bc);
bexpected.add(ba);
Set<byte[]> bexpected = new HashSet<byte[]>();
bexpected.add(bb);
bexpected.add(bc);
bexpected.add(ba);
Set<byte[]> bunion = jedis.sunion(bfoo, bbar);
assertEquals(bexpected, bunion);
Set<byte[]> 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<String> expected = new HashSet<String>();
expected.add("a");
expected.add("b");
expected.add("c");
Set<String> expected = new HashSet<String>();
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<byte[]> bexpected = new HashSet<byte[]>();
bexpected.add(bb);
bexpected.add(bc);
bexpected.add(ba);
Set<byte[]> bexpected = new HashSet<byte[]>();
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<String> expected = new HashSet<String>();
expected.add("x");
expected.add("b");
Set<String> expected = new HashSet<String>();
expected.add("x");
expected.add("b");
Set<String> diff = jedis.sdiff("foo", "bar", "car");
assertEquals(expected, diff);
Set<String> 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<byte[]> bexpected = new HashSet<byte[]>();
bexpected.add(bb);
bexpected.add(bx);
Set<byte[]> bexpected = new HashSet<byte[]>();
bexpected.add(bb);
bexpected.add(bx);
Set<byte[]> bdiff = jedis.sdiff(bfoo, bbar, bcar);
assertEquals(bexpected, bdiff);
Set<byte[]> 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<String> expected = new HashSet<String>();
expected.add("d");
expected.add("a");
Set<String> expected = new HashSet<String>();
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<byte[]> bexpected = new HashSet<byte[]>();
bexpected.add(bd);
bexpected.add(ba);
Set<byte[]> bexpected = new HashSet<byte[]>();
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());
bmember = jedis.srandmember(bbar);
assertNull(bmember);
assertTrue(Arrays.equals(ba, bmember) || Arrays.equals(bb, bmember));
assertEquals(2, jedis.smembers(bfoo).size());
bmember = jedis.srandmember(bbar);
assertNull(bmember);
}
@Test
public void sscan() {
jedis.sadd("foo", "a", "b");
ScanResult<String> 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<String> 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<String> result = jedis.sscan("foo", 0, params);
assertFalse(result.getResult().isEmpty());
}
}

View File

@@ -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<Slowlog> 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<byte[]> breducedLog = jedis.slowlogGetBinary(1);
assertEquals(1, breducedLog.size());
List<Slowlog> log1 = jedis.slowlogGet();
List<byte[]> blog1 = jedis.slowlogGetBinary();
assertNotNull(log1);
assertNotNull(blog1);
long len1 = jedis.slowlogLen();
jedis.slowlogReset();
List<Slowlog> log2 = jedis.slowlogGet();
List<byte[]> 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<Slowlog> 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<byte[]> breducedLog = jedis.slowlogGetBinary(1);
assertEquals(1, breducedLog.size());
List<Slowlog> log1 = jedis.slowlogGet();
List<byte[]> blog1 = jedis.slowlogGetBinary();
assertNotNull(log1);
assertNotNull(blog1);
long len1 = jedis.slowlogLen();
jedis.slowlogReset();
List<Slowlog> log2 = jedis.slowlogGet();
List<byte[]> blog2 = jedis.slowlogGetBinary();
long len2 = jedis.slowlogLen();
assertTrue(len1 > len2);
assertTrue(log1.size() > log2.size());
assertTrue(blog1.size() > blog2.size());
}
}

View File

@@ -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<String> result = jedis.sort("foo");
List<String> result = jedis.sort("foo");
List<String> expected = new ArrayList<String>();
expected.add("1");
expected.add("2");
expected.add("3");
List<String> expected = new ArrayList<String>();
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<byte[]> bresult = jedis.sort(bfoo);
List<byte[]> bresult = jedis.sort(bfoo);
List<byte[]> bexpected = new ArrayList<byte[]>();
bexpected.add(b1);
bexpected.add(b2);
bexpected.add(b3);
List<byte[]> bexpected = new ArrayList<byte[]>();
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<String> result = jedis.sort("foo", sp);
List<String> result = jedis.sort("foo", sp);
List<String> expected = new ArrayList<String>();
expected.add("3");
expected.add("2");
expected.add("1");
List<String> expected = new ArrayList<String>();
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<byte[]> bresult = jedis.sort(bfoo, bsp);
List<byte[]> bresult = jedis.sort(bfoo, bsp);
List<byte[]> bexpected = new ArrayList<byte[]>();
bexpected.add(b3);
bexpected.add(b2);
bexpected.add(b1);
List<byte[]> bexpected = new ArrayList<byte[]>();
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<String> result = jedis.sort("foo", sp);
List<String> result = jedis.sort("foo", sp);
List<String> expected = new ArrayList<String>();
expected.add("3");
expected.add("2");
expected.add("1");
List<String> expected = new ArrayList<String>();
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<byte[]> bresult = jedis.sort(bfoo, bsp);
List<byte[]> bresult = jedis.sort(bfoo, bsp);
List<byte[]> bexpected = new ArrayList<byte[]>();
bexpected.add(b3);
bexpected.add(b2);
bexpected.add(b1);
List<byte[]> bexpected = new ArrayList<byte[]>();
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<String> result = jedis.sort("foo", sp);
List<String> result = jedis.sort("foo", sp);
List<String> expected = new ArrayList<String>();
expected.add("1");
expected.add("2");
expected.add("3");
List<String> expected = new ArrayList<String>();
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<byte[]> bresult = jedis.sort(bfoo, bsp);
List<byte[]> bresult = jedis.sort(bfoo, bsp);
List<byte[]> bexpected = new ArrayList<byte[]>();
bexpected.add(b1);
bexpected.add(b2);
bexpected.add(b3);
List<byte[]> bexpected = new ArrayList<byte[]>();
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<String> result = jedis.sort("foo", sp);
List<String> result = jedis.sort("foo", sp);
List<String> expected = new ArrayList<String>();
expected.add("1");
expected.add("10");
expected.add("2");
List<String> expected = new ArrayList<String>();
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<byte[]> bresult = jedis.sort(bfoo, bsp);
List<byte[]> bresult = jedis.sort(bfoo, bsp);
List<byte[]> bexpected = new ArrayList<byte[]>();
bexpected.add(b1);
bexpected.add(b10);
bexpected.add(b2);
List<byte[]> bexpected = new ArrayList<byte[]>();
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<String> result = jedis.sort("foo", sp);
List<String> result = jedis.sort("foo", sp);
List<String> expected = new ArrayList<String>();
expected.add("car1");
expected.add("bar1");
expected.add("car2");
expected.add("bar2");
expected.add("car10");
expected.add("bar10");
List<String> expected = new ArrayList<String>();
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<byte[]> bresult = jedis.sort(bfoo, bsp);
List<byte[]> bresult = jedis.sort(bfoo, bsp);
List<byte[]> bexpected = new ArrayList<byte[]>();
bexpected.add(bcar1);
bexpected.add(bbar1);
bexpected.add(bcar2);
bexpected.add(bbar2);
bexpected.add(bcar10);
bexpected.add(bbar10);
List<byte[]> bexpected = new ArrayList<byte[]>();
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<String> expected = new ArrayList<String>();
expected.add("1");
expected.add("2");
expected.add("10");
List<String> expected = new ArrayList<String>();
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<byte[]> bexpected = new ArrayList<byte[]>();
bexpected.add(b1);
bexpected.add(b2);
bexpected.add(b10);
List<byte[]> bexpected = new ArrayList<byte[]>();
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));
}
}

View File

@@ -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<String> values = jedis.mget("foo", "bar");
List<String> expected = new ArrayList<String>();
expected.add(null);
expected.add(null);
List<String> values = jedis.mget("foo", "bar");
List<String> expected = new ArrayList<String>();
expected.add(null);
expected.add(null);
assertEquals(expected, values);
assertEquals(expected, values);
jedis.set("foo", "bar");
jedis.set("foo", "bar");
expected = new ArrayList<String>();
expected.add("bar");
expected.add(null);
values = jedis.mget("foo", "bar");
expected = new ArrayList<String>();
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<String>();
expected.add("bar");
expected.add("foo");
values = jedis.mget("foo", "bar");
expected = new ArrayList<String>();
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);
}
}

View File

@@ -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;
@@ -12,11 +13,12 @@ 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;
import redis.clients.jedis.exceptions.JedisException;
public class TransactionCommandsTest extends JedisCommandTestBase {
final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 };
@@ -30,269 +32,359 @@ 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.getHost(), hnp.getPort(), 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<Object> response = trans.exec();
List<Object> response = trans.exec();
List<Object> expected = new ArrayList<Object>();
expected.add(1L);
expected.add(1L);
expected.add(2L);
assertEquals(expected, response);
List<Object> expected = new ArrayList<Object>();
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<Object>();
expected.add(1L);
expected.add(1L);
expected.add(2L);
assertEquals(expected, response);
expected = new ArrayList<Object>();
expected.add(1L);
expected.add(1L);
expected.add(2L);
assertEquals(expected, response);
}
@Test
public void multiBlock() {
List<Object> response = jedis.multi(new TransactionBlock() {
@Override
public void execute() {
sadd("foo", "a");
sadd("foo", "b");
scard("foo");
}
});
List<Object> response = jedis.multi(new TransactionBlock() {
@Override
public void execute() {
sadd("foo", "a");
sadd("foo", "b");
scard("foo");
}
});
List<Object> expected = new ArrayList<Object>();
expected.add(1L);
expected.add(1L);
expected.add(2L);
assertEquals(expected, response);
List<Object> expected = new ArrayList<Object>();
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<Object>();
expected.add(1L);
expected.add(1L);
expected.add(2L);
assertEquals(expected, response);
expected = new ArrayList<Object>();
expected.add(1L);
expected.add(1L);
expected.add(2L);
assertEquals(expected, response);
}
@Test
public void multiBlockWithErrorRedisDiscardsTransaction() throws Exception {
// Transaction with error - Redis discards transaction automatically
// (Syntax Error, etc.)
TransactionBlock tb = new TransactionBlock() {
@Override
public void execute() throws JedisException {
del("hello");
hmset("hello", new HashMap<String, String>());
}
};
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<Object> responses = jedis.multi(tb2);
assertEquals("OK", responses.get(1));
assertEquals(JedisDataException.class, responses.get(2).getClass());
Exception exc = (JedisDataException) responses.get(2);
assertTrue(exc.getMessage().contains("WRONGTYPE"));
}
@Test
public void watch() throws UnknownHostException, IOException {
jedis.watch("mykey", "somekey");
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<Object> resp = t.exec();
assertEquals(null, resp);
assertEquals("bar", jedis.get("mykey"));
t.set("mykey", "foo");
List<Object> 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<Object> resp = t.exec();
assertEquals(1, resp.size());
assertEquals("OK", resp.get(0));
t.set("mykey", val);
List<Object> 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> string = t.get("string");
Response<String> list = t.lpop("list");
Response<String> hash = t.hget("hash", "foo");
Response<Set<String>> zset = t.zrange("zset", 0, -1);
Response<String> set = t.spop("set");
t.exec();
Transaction t = jedis.multi();
Response<String> string = t.get("string");
Response<String> list = t.lpop("list");
Response<String> hash = t.hget("hash", "foo");
Response<Set<String>> zset = t.zrange("zset", 0, -1);
Response<String> 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<byte[]> string = t.get("string".getBytes());
Response<byte[]> list = t.lpop("list".getBytes());
Response<byte[]> hash = t.hget("hash".getBytes(), "foo".getBytes());
Response<Set<byte[]>> zset = t.zrange("zset".getBytes(), 0, -1);
Response<byte[]> set = t.spop("set".getBytes());
t.exec();
Transaction t = jedis.multi();
Response<byte[]> string = t.get("string".getBytes());
Response<byte[]> list = t.lpop("list".getBytes());
Response<byte[]> hash = t.hget("hash".getBytes(), "foo".getBytes());
Response<Set<byte[]>> zset = t.zrange("zset".getBytes(), 0, -1);
Response<byte[]> 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> string = t.get("string");
string.get();
t.exec();
Transaction t = jedis.multi();
Response<String> string = t.get("string");
string.get();
t.exec();
}
@Test
public void transactionResponseWithError() {
Transaction t = jedis.multi();
t.set("foo", "bar");
Response<Set<String>> error = t.smembers("foo");
Response<String> r = t.get("foo");
List<Object> 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<Set<String>> error = t.smembers("foo");
Response<String> r = t.get("foo");
List<Object> 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<Response<?>> 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<Response<?>> 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<Object> 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<Object> results = t.exec();
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<Object> resp = t.exec();
assertNotNull(resp);
assertEquals(1, resp.size());
assertEquals("foo", jedis.get("mykey"));
}
}

View File

@@ -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<String, String> hash = new HashMap<String, String>();
hash.put("bar", "car");
hash.put("car", "bar");
hash.put("foo2", "bar");
jedis.hmset("foo", hash);
Map<String, String> hash = new HashMap<String, String>();
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<byte[], byte[]> bhash = new HashMap<byte[], byte[]>();
bhash.put(bbar, bcar);
bhash.put(bcar, bbar);
bhash.put(bfoo2, bbar);
jedis.hmset(bfoo, bhash);
// Binary
Map<byte[], byte[]> bhash = new HashMap<byte[], byte[]>();
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<String> expected = new ArrayList<String>();
expected.add("bar");
expected.add("foo");
List<String> values = jedis.lrange("foo",0,-1);
assertEquals(expected, values);
// Binary
size = jedis.rpush(bfoo, bbar, bfoo);
assertEquals(2, size);
List<byte[]> bexpected = new ArrayList<byte[]>();
bexpected.add(bbar);
bexpected.add(bfoo);
long size = jedis.rpush("foo", "bar", "foo");
assertEquals(2, size);
List<byte[]> bvalues = jedis.lrange(bfoo, 0, -1);
assertEquals(bexpected, bvalues);
List<String> expected = new ArrayList<String>();
expected.add("bar");
expected.add("foo");
List<String> values = jedis.lrange("foo", 0, -1);
assertEquals(expected, values);
// Binary
size = jedis.rpush(bfoo, bbar, bfoo);
assertEquals(2, size);
List<byte[]> bexpected = new ArrayList<byte[]>();
bexpected.add(bbar);
bexpected.add(bfoo);
List<byte[]> 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<String> expected = new ArrayList<String>();
expected.add("foo");
expected.add("bar");
List<String> values = jedis.lrange("foo",0,-1);
assertEquals(expected, values);
// Binary
size = jedis.lpush(bfoo, bbar, bfoo);
assertEquals(2, size);
List<byte[]> bexpected = new ArrayList<byte[]>();
bexpected.add(bfoo);
bexpected.add(bbar);
long size = jedis.lpush("foo", "bar", "foo");
assertEquals(2, size);
List<String> expected = new ArrayList<String>();
expected.add("foo");
expected.add("bar");
List<String> values = jedis.lrange("foo", 0, -1);
assertEquals(expected, values);
// Binary
size = jedis.lpush(bfoo, bbar, bfoo);
assertEquals(2, size);
List<byte[]> bexpected = new ArrayList<byte[]>();
bexpected.add(bfoo);
bexpected.add(bbar);
List<byte[]> bvalues = jedis.lrange(bfoo, 0, -1);
assertEquals(bexpected, bvalues);
List<byte[]> 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<Double, String> scoreMembers = new HashMap<Double, String>();
scoreMembers.put(1d, "bar");
scoreMembers.put(10d, "foo");
long status = jedis.zadd("foo", scoreMembers);
assertEquals(2, status);
Map<String, Double> scoreMembers = new HashMap<String, Double>();
scoreMembers.put("bar", 1d);
scoreMembers.put("foo", 10d);
scoreMembers.clear();
scoreMembers.put(0.1d, "car");
scoreMembers.put(2d, "bar");
status = jedis.zadd("foo", scoreMembers);
assertEquals(1, status);
long status = jedis.zadd("foo", scoreMembers);
assertEquals(2, status);
Map<Double, byte[]> bscoreMembers = new HashMap<Double, byte[]>();
bscoreMembers.put(1d, bbar);
bscoreMembers.put(10d, bfoo);
status = jedis.zadd(bfoo, bscoreMembers);
assertEquals(2, status);
scoreMembers.clear();
scoreMembers.put("car", 0.1d);
scoreMembers.put("bar", 2d);
bscoreMembers.clear();
bscoreMembers.put(0.1d, bcar);
bscoreMembers.put(2d, bbar);
status = jedis.zadd(bfoo, bscoreMembers);
assertEquals(1, status);
status = jedis.zadd("foo", scoreMembers);
assertEquals(1, status);
Map<byte[], Double> bscoreMembers = new HashMap<byte[], Double>();
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<String> expected = new LinkedHashSet<String>();
expected.add("foo1");
Set<String> expected = new LinkedHashSet<String>();
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<byte[]> bexpected = new LinkedHashSet<byte[]>();
bexpected.add(bfoo);
status = jedis.zrem(bfoo, bbar, bcar);
assertEquals(2, status);
assertEquals(bexpected, jedis.zrange(bfoo, 0, 100));
Set<byte[]> bexpected = new LinkedHashSet<byte[]>();
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);
}
}

View File

@@ -0,0 +1,128 @@
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<HostAndPort> 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<String> 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<String> 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<HostAndPort> slaves) {
List<Map<String, String>> 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<Map<String, String>> slavesMap, HostAndPort slave) {
for (Map<String, String> slaveMap : slavesMap) {
HostAndPort sentinelSlave = new HostAndPort(slaveMap.get("ip"),
Integer.parseInt(slaveMap.get("port")));
if (sentinelSlave.equals(slave))
return true;
}
return false;
}
}