Replace tabs with spaces

This commit is contained in:
2015-09-01 13:13:24 +01:00
parent cdd16a53af
commit 3817f4c7ed
117 changed files with 12749 additions and 12749 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

@@ -14,31 +14,31 @@ public class ConnectionCloseTest extends Assert {
@Before
public void setUp() throws Exception {
client = new Connection();
client = new Connection();
}
@After
public void tearDown() throws Exception {
client.close();
client.close();
}
@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.setTimeoutInfinite();
client.setHost("localhost");
client.setPort(6379);
client.setTimeoutInfinite();
}
}

View File

@@ -13,39 +13,39 @@ 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.setTimeoutInfinite();
client.setHost("localhost");
client.setPort(6379);
client.setTimeoutInfinite();
}
@Test
public void checkCloseable() {
client.setHost("localhost");
client.setPort(6379);
client.connect();
client.close();
client.setHost("localhost");
client.setPort(6379);
client.connect();
client.close();
}
}

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

@@ -12,93 +12,93 @@ public class HostAndPortUtil {
private static List<HostAndPort> clusterHostAndPortList = new ArrayList<HostAndPort>();
static {
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 1));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 2));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 3));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 4));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 5));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 6));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 1));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 2));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 3));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 4));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 5));
redisHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_PORT + 6));
sentinelHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_SENTINEL_PORT));
sentinelHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_SENTINEL_PORT + 1));
sentinelHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_SENTINEL_PORT + 2));
sentinelHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_SENTINEL_PORT + 3));
sentinelHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_SENTINEL_PORT));
sentinelHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_SENTINEL_PORT + 1));
sentinelHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_SENTINEL_PORT + 2));
sentinelHostAndPortList.add(new HostAndPort("localhost",
Protocol.DEFAULT_SENTINEL_PORT + 3));
clusterHostAndPortList.add(new HostAndPort("localhost", 7379));
clusterHostAndPortList.add(new HostAndPort("localhost", 7380));
clusterHostAndPortList.add(new HostAndPort("localhost", 7381));
clusterHostAndPortList.add(new HostAndPort("localhost", 7382));
clusterHostAndPortList.add(new HostAndPort("localhost", 7383));
clusterHostAndPortList.add(new HostAndPort("localhost", 7384));
clusterHostAndPortList.add(new HostAndPort("localhost", 7379));
clusterHostAndPortList.add(new HostAndPort("localhost", 7380));
clusterHostAndPortList.add(new HostAndPort("localhost", 7381));
clusterHostAndPortList.add(new HostAndPort("localhost", 7382));
clusterHostAndPortList.add(new HostAndPort("localhost", 7383));
clusterHostAndPortList.add(new HostAndPort("localhost", 7384));
String envRedisHosts = System.getProperty("redis-hosts");
String envSentinelHosts = System.getProperty("sentinel-hosts");
String envClusterHosts = System.getProperty("cluster-hosts");
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);
redisHostAndPortList = parseHosts(envRedisHosts, redisHostAndPortList);
sentinelHostAndPortList = parseHosts(envSentinelHosts,
sentinelHostAndPortList);
clusterHostAndPortList = parseHosts(envClusterHosts,
clusterHostAndPortList);
}
public static List<HostAndPort> parseHosts(String envHosts,
List<HostAndPort> existingHostsAndPorts) {
List<HostAndPort> existingHostsAndPorts) {
if (null != envHosts && 0 < envHosts.length()) {
if (null != envHosts && 0 < envHosts.length()) {
String[] hostDefs = envHosts.split(",");
String[] hostDefs = envHosts.split(",");
if (null != hostDefs && 2 <= hostDefs.length) {
if (null != hostDefs && 2 <= hostDefs.length) {
List<HostAndPort> envHostsAndPorts = new ArrayList<HostAndPort>(
hostDefs.length);
List<HostAndPort> envHostsAndPorts = new ArrayList<HostAndPort>(
hostDefs.length);
for (String hostDef : hostDefs) {
for (String hostDef : hostDefs) {
String[] hostAndPort = hostDef.split(":");
String[] hostAndPort = hostDef.split(":");
if (null != hostAndPort && 2 == hostAndPort.length) {
String host = hostAndPort[0];
int port = Protocol.DEFAULT_PORT;
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) {
}
try {
port = Integer.parseInt(hostAndPort[1]);
} catch (final NumberFormatException nfe) {
}
envHostsAndPorts.add(new HostAndPort(host, port));
}
}
envHostsAndPorts.add(new HostAndPort(host, port));
}
}
return envHostsAndPorts;
}
}
return envHostsAndPorts;
}
}
return existingHostsAndPorts;
return existingHostsAndPorts;
}
public static List<HostAndPort> getRedisServers() {
return redisHostAndPortList;
return redisHostAndPortList;
}
public static List<HostAndPort> getSentinelServers() {
return sentinelHostAndPortList;
return sentinelHostAndPortList;
}
public static List<HostAndPort> getClusterServers() {
return clusterHostAndPortList;
return clusterHostAndPortList;
}
}

View File

@@ -13,52 +13,52 @@ public class JedisClusterNodeInformationParserTest extends Assert {
@Before
public void setUp() {
parser = new ClusterNodeInformationParser();
parser = new ClusterNodeInformationParser();
}
@Test
public void testParseNodeMyself() {
String nodeInfo = "9b0d2ab38ee31482c95fdb2c7847a0d40e88d518 :7379 myself,master - 0 0 1 connected 0-5460";
HostAndPort current = new HostAndPort("localhost", 7379);
ClusterNodeInformation clusterNodeInfo = parser
.parse(nodeInfo, current);
assertEquals(clusterNodeInfo.getNode(), current);
String nodeInfo = "9b0d2ab38ee31482c95fdb2c7847a0d40e88d518 :7379 myself,master - 0 0 1 connected 0-5460";
HostAndPort current = new HostAndPort("localhost", 7379);
ClusterNodeInformation clusterNodeInfo = parser
.parse(nodeInfo, current);
assertEquals(clusterNodeInfo.getNode(), current);
}
@Test
public void testParseNormalState() {
String nodeInfo = "5f4a2236d00008fba7ac0dd24b95762b446767bd 192.168.0.3:7380 master - 0 1400598804016 2 connected 5461-10922";
HostAndPort current = new HostAndPort("localhost", 7379);
ClusterNodeInformation clusterNodeInfo = parser
.parse(nodeInfo, current);
assertNotEquals(clusterNodeInfo.getNode(), current);
assertEquals(clusterNodeInfo.getNode(), new HostAndPort("192.168.0.3",
7380));
String nodeInfo = "5f4a2236d00008fba7ac0dd24b95762b446767bd 192.168.0.3:7380 master - 0 1400598804016 2 connected 5461-10922";
HostAndPort current = new HostAndPort("localhost", 7379);
ClusterNodeInformation clusterNodeInfo = parser
.parse(nodeInfo, current);
assertNotEquals(clusterNodeInfo.getNode(), current);
assertEquals(clusterNodeInfo.getNode(), new HostAndPort("192.168.0.3",
7380));
for (int slot = 5461; slot <= 10922; slot++) {
assertTrue(clusterNodeInfo.getAvailableSlots().contains(slot));
}
for (int slot = 5461; slot <= 10922; slot++) {
assertTrue(clusterNodeInfo.getAvailableSlots().contains(slot));
}
assertTrue(clusterNodeInfo.getSlotsBeingImported().isEmpty());
assertTrue(clusterNodeInfo.getSlotsBeingMigrated().isEmpty());
assertTrue(clusterNodeInfo.getSlotsBeingImported().isEmpty());
assertTrue(clusterNodeInfo.getSlotsBeingMigrated().isEmpty());
}
@Test
public void testParseSlotBeingMigrated() {
String nodeInfo = "5f4a2236d00008fba7ac0dd24b95762b446767bd :7379 myself,master - 0 0 1 connected 0-5459 [5460->-5f4a2236d00008fba7ac0dd24b95762b446767bd] [5461-<-5f4a2236d00008fba7ac0dd24b95762b446767bd]";
HostAndPort current = new HostAndPort("localhost", 7379);
ClusterNodeInformation clusterNodeInfo = parser
.parse(nodeInfo, current);
assertEquals(clusterNodeInfo.getNode(), current);
String nodeInfo = "5f4a2236d00008fba7ac0dd24b95762b446767bd :7379 myself,master - 0 0 1 connected 0-5459 [5460->-5f4a2236d00008fba7ac0dd24b95762b446767bd] [5461-<-5f4a2236d00008fba7ac0dd24b95762b446767bd]";
HostAndPort current = new HostAndPort("localhost", 7379);
ClusterNodeInformation clusterNodeInfo = parser
.parse(nodeInfo, current);
assertEquals(clusterNodeInfo.getNode(), current);
for (int slot = 0; slot <= 5459; slot++) {
assertTrue(clusterNodeInfo.getAvailableSlots().contains(slot));
}
for (int slot = 0; slot <= 5459; slot++) {
assertTrue(clusterNodeInfo.getAvailableSlots().contains(slot));
}
assertEquals(1, clusterNodeInfo.getSlotsBeingMigrated().size());
assertTrue(clusterNodeInfo.getSlotsBeingMigrated().contains(5460));
assertEquals(1, clusterNodeInfo.getSlotsBeingImported().size());
assertTrue(clusterNodeInfo.getSlotsBeingImported().contains(5461));
assertEquals(1, clusterNodeInfo.getSlotsBeingMigrated().size());
assertTrue(clusterNodeInfo.getSlotsBeingMigrated().contains(5460));
assertEquals(1, clusterNodeInfo.getSlotsBeingImported().size());
assertTrue(clusterNodeInfo.getSlotsBeingImported().contains(5461));
}
}

View File

@@ -49,110 +49,110 @@ public class JedisClusterTest extends Assert {
@Before
public void setUp() throws InterruptedException {
node1 = new Jedis(nodeInfo1.getHost(), nodeInfo1.getPort());
node1.connect();
node1.flushAll();
node1 = new Jedis(nodeInfo1.getHost(), nodeInfo1.getPort());
node1.connect();
node1.flushAll();
node2 = new Jedis(nodeInfo2.getHost(), nodeInfo2.getPort());
node2.connect();
node2.flushAll();
node2 = new Jedis(nodeInfo2.getHost(), nodeInfo2.getPort());
node2.connect();
node2.flushAll();
node3 = new Jedis(nodeInfo3.getHost(), nodeInfo3.getPort());
node3.connect();
node3.flushAll();
node3 = new Jedis(nodeInfo3.getHost(), nodeInfo3.getPort());
node3.connect();
node3.flushAll();
node4 = new Jedis(nodeInfo4.getHost(), nodeInfo4.getPort());
node4.connect();
node4.flushAll();
node4 = new Jedis(nodeInfo4.getHost(), nodeInfo4.getPort());
node4.connect();
node4.flushAll();
// ---- configure cluster
// ---- configure cluster
// add nodes to cluster
node1.clusterMeet(localHost, nodeInfo2.getPort());
node1.clusterMeet(localHost, nodeInfo3.getPort());
// add nodes to cluster
node1.clusterMeet(localHost, nodeInfo2.getPort());
node1.clusterMeet(localHost, nodeInfo3.getPort());
// split available slots across the three nodes
int slotsPerNode = JedisCluster.HASHSLOTS / 3;
int[] node1Slots = new int[slotsPerNode];
int[] node2Slots = new int[slotsPerNode + 1];
int[] node3Slots = new int[slotsPerNode];
for (int i = 0, slot1 = 0, slot2 = 0, slot3 = 0; i < JedisCluster.HASHSLOTS; i++) {
if (i < slotsPerNode) {
node1Slots[slot1++] = i;
} else if (i > slotsPerNode * 2) {
node3Slots[slot3++] = i;
} else {
node2Slots[slot2++] = i;
}
}
// split available slots across the three nodes
int slotsPerNode = JedisCluster.HASHSLOTS / 3;
int[] node1Slots = new int[slotsPerNode];
int[] node2Slots = new int[slotsPerNode + 1];
int[] node3Slots = new int[slotsPerNode];
for (int i = 0, slot1 = 0, slot2 = 0, slot3 = 0; i < JedisCluster.HASHSLOTS; i++) {
if (i < slotsPerNode) {
node1Slots[slot1++] = i;
} else if (i > slotsPerNode * 2) {
node3Slots[slot3++] = i;
} else {
node2Slots[slot2++] = i;
}
}
node1.clusterAddSlots(node1Slots);
node2.clusterAddSlots(node2Slots);
node3.clusterAddSlots(node3Slots);
node1.clusterAddSlots(node1Slots);
node2.clusterAddSlots(node2Slots);
node3.clusterAddSlots(node3Slots);
JedisClusterTestUtil.waitForClusterReady(node1, node2, node3);
JedisClusterTestUtil.waitForClusterReady(node1, node2, node3);
}
@AfterClass
public static void cleanUp() {
node1.flushDB();
node2.flushDB();
node3.flushDB();
node4.flushDB();
node1.clusterReset(Reset.SOFT);
node2.clusterReset(Reset.SOFT);
node3.clusterReset(Reset.SOFT);
node4.clusterReset(Reset.SOFT);
node1.flushDB();
node2.flushDB();
node3.flushDB();
node4.flushDB();
node1.clusterReset(Reset.SOFT);
node2.clusterReset(Reset.SOFT);
node3.clusterReset(Reset.SOFT);
node4.clusterReset(Reset.SOFT);
}
@After
public void tearDown() throws InterruptedException {
cleanUp();
cleanUp();
}
@Test(expected = JedisMovedDataException.class)
public void testThrowMovedException() {
node1.set("foo", "bar");
node1.set("foo", "bar");
}
@Test
public void testMovedExceptionParameters() {
try {
node1.set("foo", "bar");
} catch (JedisMovedDataException jme) {
assertEquals(12182, jme.getSlot());
assertEquals(new HostAndPort("127.0.0.1", 7381),
jme.getTargetNode());
return;
}
fail();
try {
node1.set("foo", "bar");
} catch (JedisMovedDataException jme) {
assertEquals(12182, jme.getSlot());
assertEquals(new HostAndPort("127.0.0.1", 7381),
jme.getTargetNode());
return;
}
fail();
}
@Test(expected = JedisAskDataException.class)
public void testThrowAskException() {
int keySlot = JedisClusterCRC16.getSlot("test");
String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes());
node2.clusterSetSlotMigrating(keySlot, node3Id);
node2.get("test");
int keySlot = JedisClusterCRC16.getSlot("test");
String node3Id = JedisClusterTestUtil.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(3, jc.getClusterNodes().size());
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode);
assertEquals(3, jc.getClusterNodes().size());
}
@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"));
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"));
}
/**
@@ -160,389 +160,389 @@ public class JedisClusterTest extends Assert {
*/
@Test
public void testMigrate() {
log.info("test migrate slot");
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(nodeInfo1);
JedisCluster jc = new JedisCluster(jedisClusterNode);
String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes());
String node2Id = JedisClusterTestUtil.getNodeId(node2.clusterNodes());
node3.clusterSetSlotMigrating(15363, node2Id);
node2.clusterSetSlotImporting(15363, node3Id);
try {
node2.set("e", "e");
} catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()),
jme.getTargetNode());
}
log.info("test migrate slot");
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(nodeInfo1);
JedisCluster jc = new JedisCluster(jedisClusterNode);
String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes());
String node2Id = JedisClusterTestUtil.getNodeId(node2.clusterNodes());
node3.clusterSetSlotMigrating(15363, node2Id);
node2.clusterSetSlotImporting(15363, node3Id);
try {
node2.set("e", "e");
} catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()),
jme.getTargetNode());
}
try {
node3.set("e", "e");
} catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo2.getPort()),
jae.getTargetNode());
}
try {
node3.set("e", "e");
} catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo2.getPort()),
jae.getTargetNode());
}
jc.set("e", "e");
jc.set("e", "e");
try {
node2.get("e");
} catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()),
jme.getTargetNode());
}
try {
node3.get("e");
} catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo2.getPort()),
jae.getTargetNode());
}
try {
node2.get("e");
} catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()),
jme.getTargetNode());
}
try {
node3.get("e");
} catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo2.getPort()),
jae.getTargetNode());
}
assertEquals("e", jc.get("e"));
assertEquals("e", jc.get("e"));
node2.clusterSetSlotNode(15363, node2Id);
node3.clusterSetSlotNode(15363, node2Id);
// assertEquals("e", jc.get("e"));
assertEquals("e", node2.get("e"));
node2.clusterSetSlotNode(15363, node2Id);
node3.clusterSetSlotNode(15363, node2Id);
// assertEquals("e", jc.get("e"));
assertEquals("e", node2.get("e"));
// assertEquals("e", node3.get("e"));
// assertEquals("e", node3.get("e"));
}
@Test
public void testMigrateToNewNode() throws InterruptedException {
log.info("test migrate slot to new node");
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(nodeInfo1);
JedisCluster jc = new JedisCluster(jedisClusterNode);
node4.clusterMeet(localHost, nodeInfo1.getPort());
log.info("test migrate slot to new node");
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(nodeInfo1);
JedisCluster jc = new JedisCluster(jedisClusterNode);
node4.clusterMeet(localHost, nodeInfo1.getPort());
String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes());
String node4Id = JedisClusterTestUtil.getNodeId(node4.clusterNodes());
JedisClusterTestUtil.waitForClusterReady(node4);
node3.clusterSetSlotMigrating(15363, node4Id);
node4.clusterSetSlotImporting(15363, node3Id);
try {
node4.set("e", "e");
} catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()),
jme.getTargetNode());
}
String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes());
String node4Id = JedisClusterTestUtil.getNodeId(node4.clusterNodes());
JedisClusterTestUtil.waitForClusterReady(node4);
node3.clusterSetSlotMigrating(15363, node4Id);
node4.clusterSetSlotImporting(15363, node3Id);
try {
node4.set("e", "e");
} catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()),
jme.getTargetNode());
}
try {
node3.set("e", "e");
} catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo4.getPort()),
jae.getTargetNode());
}
try {
node3.set("e", "e");
} catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo4.getPort()),
jae.getTargetNode());
}
jc.set("e", "e");
jc.set("e", "e");
try {
node4.get("e");
} catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()),
jme.getTargetNode());
}
try {
node3.get("e");
} catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo4.getPort()),
jae.getTargetNode());
}
try {
node4.get("e");
} catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()),
jme.getTargetNode());
}
try {
node3.get("e");
} catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo4.getPort()),
jae.getTargetNode());
}
assertEquals("e", jc.get("e"));
assertEquals("e", jc.get("e"));
node4.clusterSetSlotNode(15363, node4Id);
node3.clusterSetSlotNode(15363, node4Id);
// assertEquals("e", jc.get("e"));
assertEquals("e", node4.get("e"));
node4.clusterSetSlotNode(15363, node4Id);
node3.clusterSetSlotNode(15363, node4Id);
// assertEquals("e", jc.get("e"));
assertEquals("e", node4.get("e"));
// assertEquals("e", node3.get("e"));
// assertEquals("e", node3.get("e"));
}
@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);
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);
JedisClusterTestUtil.waitForClusterReady(node1, node2, node3);
jc.set("51", "foo");
assertEquals("foo", jc.get("51"));
JedisClusterTestUtil.waitForClusterReady(node1, node2, node3);
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,
JedisClusterTestUtil.getNodeId(node2.clusterNodes()));
node2.clusterSetSlotMigrating(slot51,
JedisClusterTestUtil.getNodeId(node3.clusterNodes()));
jc.set("51", "foo");
assertEquals("foo", jc.get("51"));
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,
JedisClusterTestUtil.getNodeId(node2.clusterNodes()));
node2.clusterSetSlotMigrating(slot51,
JedisClusterTestUtil.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();
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,
JedisClusterTestUtil.getNodeId(node3.clusterNodes()));
jc.set("51", "foo");
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,
JedisClusterTestUtil.getNodeId(node3.clusterNodes()));
jc.set("51", "foo");
}
@Test
public void testRedisHashtag() {
assertEquals(JedisClusterCRC16.getSlot("{bar"),
JedisClusterCRC16.getSlot("foo{{bar}}zap"));
assertEquals(JedisClusterCRC16.getSlot("{user1000}.following"),
JedisClusterCRC16.getSlot("{user1000}.followers"));
assertNotEquals(JedisClusterCRC16.getSlot("foo{}{bar}"),
JedisClusterCRC16.getSlot("bar"));
assertEquals(JedisClusterCRC16.getSlot("foo{bar}{zap}"),
JedisClusterCRC16.getSlot("bar"));
assertEquals(JedisClusterCRC16.getSlot("{bar"),
JedisClusterCRC16.getSlot("foo{{bar}}zap"));
assertEquals(JedisClusterCRC16.getSlot("{user1000}.following"),
JedisClusterCRC16.getSlot("{user1000}.followers"));
assertNotEquals(JedisClusterCRC16.getSlot("foo{}{bar}"),
JedisClusterCRC16.getSlot("bar"));
assertEquals(JedisClusterCRC16.getSlot("foo{bar}{zap}"),
JedisClusterCRC16.getSlot("bar"));
}
@Test
public void testClusterForgetNode() throws InterruptedException {
// at first, join node4 to cluster
node1.clusterMeet("127.0.0.1", nodeInfo4.getPort());
// at first, join node4 to cluster
node1.clusterMeet("127.0.0.1", nodeInfo4.getPort());
String node7Id = JedisClusterTestUtil.getNodeId(node4.clusterNodes());
String node7Id = JedisClusterTestUtil.getNodeId(node4.clusterNodes());
JedisClusterTestUtil.assertNodeIsKnown(node3, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsKnown(node2, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsKnown(node1, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsKnown(node3, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsKnown(node2, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsKnown(node1, node7Id, 1000);
assertNodeHandshakeEnded(node3, 1000);
assertNodeHandshakeEnded(node2, 1000);
assertNodeHandshakeEnded(node1, 1000);
assertNodeHandshakeEnded(node3, 1000);
assertNodeHandshakeEnded(node2, 1000);
assertNodeHandshakeEnded(node1, 1000);
assertEquals(4, node1.clusterNodes().split("\n").length);
assertEquals(4, node2.clusterNodes().split("\n").length);
assertEquals(4, node3.clusterNodes().split("\n").length);
assertEquals(4, node1.clusterNodes().split("\n").length);
assertEquals(4, node2.clusterNodes().split("\n").length);
assertEquals(4, node3.clusterNodes().split("\n").length);
// do cluster forget
node1.clusterForget(node7Id);
node2.clusterForget(node7Id);
node3.clusterForget(node7Id);
// do cluster forget
node1.clusterForget(node7Id);
node2.clusterForget(node7Id);
node3.clusterForget(node7Id);
JedisClusterTestUtil.assertNodeIsUnknown(node1, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsUnknown(node2, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsUnknown(node3, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsUnknown(node1, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsUnknown(node2, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsUnknown(node3, node7Id, 1000);
assertEquals(3, node1.clusterNodes().split("\n").length);
assertEquals(3, node2.clusterNodes().split("\n").length);
assertEquals(3, node3.clusterNodes().split("\n").length);
assertEquals(3, node1.clusterNodes().split("\n").length);
assertEquals(3, node2.clusterNodes().split("\n").length);
assertEquals(3, node3.clusterNodes().split("\n").length);
}
@Test
public void testClusterFlushSlots() {
String slotRange = getNodeServingSlotRange(node1.clusterNodes());
assertNotNull(slotRange);
String slotRange = getNodeServingSlotRange(node1.clusterNodes());
assertNotNull(slotRange);
try {
node1.clusterFlushSlots();
assertNull(getNodeServingSlotRange(node1.clusterNodes()));
} finally {
// rollback
String[] rangeInfo = slotRange.split("-");
int lower = Integer.parseInt(rangeInfo[0]);
int upper = Integer.parseInt(rangeInfo[1]);
try {
node1.clusterFlushSlots();
assertNull(getNodeServingSlotRange(node1.clusterNodes()));
} finally {
// rollback
String[] rangeInfo = slotRange.split("-");
int lower = Integer.parseInt(rangeInfo[0]);
int upper = Integer.parseInt(rangeInfo[1]);
int[] node1Slots = new int[upper - lower + 1];
for (int i = 0; lower <= upper;) {
node1Slots[i++] = lower++;
}
node1.clusterAddSlots(node1Slots);
}
int[] node1Slots = new int[upper - lower + 1];
for (int i = 0; lower <= upper;) {
node1Slots[i++] = lower++;
}
node1.clusterAddSlots(node1Slots);
}
}
@Test
public void testClusterKeySlot() {
// It assumes JedisClusterCRC16 is correctly implemented
assertEquals(node1.clusterKeySlot("foo{bar}zap}").intValue(),
JedisClusterCRC16.getSlot("foo{bar}zap"));
assertEquals(node1.clusterKeySlot("{user1000}.following").intValue(),
JedisClusterCRC16.getSlot("{user1000}.following"));
// It assumes JedisClusterCRC16 is correctly implemented
assertEquals(node1.clusterKeySlot("foo{bar}zap}").intValue(),
JedisClusterCRC16.getSlot("foo{bar}zap"));
assertEquals(node1.clusterKeySlot("{user1000}.following").intValue(),
JedisClusterCRC16.getSlot("{user1000}.following"));
}
@Test
public void testClusterCountKeysInSlot() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1
.getPort()));
JedisCluster jc = new JedisCluster(jedisClusterNode);
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1
.getPort()));
JedisCluster jc = new JedisCluster(jedisClusterNode);
for (int index = 0; index < 5; index++) {
jc.set("foo{bar}" + index, "hello");
}
for (int index = 0; index < 5; index++) {
jc.set("foo{bar}" + index, "hello");
}
int slot = JedisClusterCRC16.getSlot("foo{bar}");
assertEquals(5, node1.clusterCountKeysInSlot(slot).intValue());
int slot = JedisClusterCRC16.getSlot("foo{bar}");
assertEquals(5, node1.clusterCountKeysInSlot(slot).intValue());
}
@Test
public void testStableSlotWhenMigratingNodeOrImportingNodeIsNotSpecified()
throws InterruptedException {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1
.getPort()));
JedisCluster jc = new JedisCluster(jedisClusterNode);
throws InterruptedException {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1
.getPort()));
JedisCluster jc = new JedisCluster(jedisClusterNode);
int slot51 = JedisClusterCRC16.getSlot("51");
jc.set("51", "foo");
// node2 is responsible of taking care of slot51 (7186)
int slot51 = JedisClusterCRC16.getSlot("51");
jc.set("51", "foo");
// node2 is responsible of taking care of slot51 (7186)
node3.clusterSetSlotImporting(slot51,
JedisClusterTestUtil.getNodeId(node2.clusterNodes()));
assertEquals("foo", jc.get("51"));
node3.clusterSetSlotStable(slot51);
assertEquals("foo", jc.get("51"));
node3.clusterSetSlotImporting(slot51,
JedisClusterTestUtil.getNodeId(node2.clusterNodes()));
assertEquals("foo", jc.get("51"));
node3.clusterSetSlotStable(slot51);
assertEquals("foo", jc.get("51"));
node2.clusterSetSlotMigrating(slot51,
JedisClusterTestUtil.getNodeId(node3.clusterNodes()));
// assertEquals("foo", jc.get("51")); // it leads Max Redirections
node2.clusterSetSlotStable(slot51);
assertEquals("foo", jc.get("51"));
node2.clusterSetSlotMigrating(slot51,
JedisClusterTestUtil.getNodeId(node3.clusterNodes()));
// assertEquals("foo", jc.get("51")); // it leads Max Redirections
node2.clusterSetSlotStable(slot51);
assertEquals("foo", jc.get("51"));
}
@Test(expected = JedisConnectionException.class)
public void testIfPoolConfigAppliesToClusterPools() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(0);
config.setMaxWaitMillis(2000);
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode, config);
jc.set("52", "poolTestValue");
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(0);
config.setMaxWaitMillis(2000);
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode, config);
jc.set("52", "poolTestValue");
}
@Test
public void testCloseable() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1
.getPort()));
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1
.getPort()));
JedisCluster jc = null;
try {
jc = new JedisCluster(jedisClusterNode);
jc.set("51", "foo");
} finally {
if (jc != null) {
jc.close();
}
}
JedisCluster jc = null;
try {
jc = new JedisCluster(jedisClusterNode);
jc.set("51", "foo");
} finally {
if (jc != null) {
jc.close();
}
}
Iterator<JedisPool> poolIterator = jc.getClusterNodes().values()
.iterator();
while (poolIterator.hasNext()) {
JedisPool pool = poolIterator.next();
try {
pool.getResource();
fail("JedisCluster's internal pools should be already destroyed");
} catch (JedisConnectionException e) {
// ok to go...
}
}
Iterator<JedisPool> poolIterator = jc.getClusterNodes().values()
.iterator();
while (poolIterator.hasNext()) {
JedisPool pool = poolIterator.next();
try {
pool.getResource();
fail("JedisCluster's internal pools should be already destroyed");
} catch (JedisConnectionException e) {
// ok to go...
}
}
}
@Test
public void testJedisClusterRunsWithMultithreaded()
throws InterruptedException, ExecutionException {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
final JedisCluster jc = new JedisCluster(jedisClusterNode);
jc.set("foo", "bar");
throws InterruptedException, ExecutionException {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
final JedisCluster jc = new JedisCluster(jedisClusterNode);
jc.set("foo", "bar");
ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 100, 0,
TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));
List<Future<String>> futures = new ArrayList<Future<String>>();
for (int i = 0; i < 50; i++) {
executor.submit(new Callable<String>() {
@Override
public String call() throws Exception {
// FIXME : invalidate slot cache from JedisCluster to test
// random connection also does work
return jc.get("foo");
}
});
}
ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 100, 0,
TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));
List<Future<String>> futures = new ArrayList<Future<String>>();
for (int i = 0; i < 50; i++) {
executor.submit(new Callable<String>() {
@Override
public String call() throws Exception {
// FIXME : invalidate slot cache from JedisCluster to test
// random connection also does work
return jc.get("foo");
}
});
}
for (Future<String> future : futures) {
String value = future.get();
assertEquals("bar", value);
}
for (Future<String> future : futures) {
String value = future.get();
assertEquals("bar", value);
}
jc.close();
jc.close();
}
private static String getNodeServingSlotRange(String infoOutput) {
// f4f3dc4befda352a4e0beccf29f5e8828438705d 127.0.0.1:7380 master - 0
// 1394372400827 0 connected 5461-10922
for (String infoLine : infoOutput.split("\n")) {
if (infoLine.contains("myself")) {
try {
return infoLine.split(" ")[8];
} catch (ArrayIndexOutOfBoundsException e) {
return null;
}
}
}
return null;
// f4f3dc4befda352a4e0beccf29f5e8828438705d 127.0.0.1:7380 master - 0
// 1394372400827 0 connected 5461-10922
for (String infoLine : infoOutput.split("\n")) {
if (infoLine.contains("myself")) {
try {
return infoLine.split(" ")[8];
} catch (ArrayIndexOutOfBoundsException e) {
return null;
}
}
}
return null;
}
private void assertNodeHandshakeEnded(Jedis node, int timeoutMs) {
int sleepInterval = 100;
for (int sleepTime = 0; sleepTime <= timeoutMs; sleepTime += sleepInterval) {
boolean isHandshaking = isAnyNodeHandshaking(node);
if (!isHandshaking)
return;
int sleepInterval = 100;
for (int sleepTime = 0; sleepTime <= timeoutMs; sleepTime += sleepInterval) {
boolean isHandshaking = isAnyNodeHandshaking(node);
if (!isHandshaking)
return;
try {
Thread.sleep(sleepInterval);
} catch (InterruptedException e) {
}
}
try {
Thread.sleep(sleepInterval);
} catch (InterruptedException e) {
}
}
throw new JedisException("Node handshaking is not ended");
throw new JedisException("Node handshaking is not ended");
}
private boolean isAnyNodeHandshaking(Jedis node) {
String infoOutput = node.clusterNodes();
for (String infoLine : infoOutput.split("\n")) {
if (infoLine.contains("handshake")) {
return true;
}
}
return false;
String infoOutput = node.clusterNodes();
for (String infoLine : infoOutput.split("\n")) {
if (infoLine.contains("handshake")) {
return true;
}
}
return false;
}
}

View File

@@ -24,191 +24,191 @@ public class JedisPoolTest extends Assert {
@Test
public void checkConnections() {
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000);
Jedis jedis = pool.getResource();
jedis.auth("foobared");
jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo"));
pool.returnResource(jedis);
pool.destroy();
assertTrue(pool.isClosed());
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();
assertTrue(pool.isClosed());
}
@Test
public void checkCloseableConnections() throws Exception {
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.close();
assertTrue(pool.isClosed());
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.close();
assertTrue(pool.isClosed());
}
@Test
public void checkConnectionWithDefaultPort() {
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort());
Jedis jedis = pool.getResource();
jedis.auth("foobared");
jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo"));
pool.returnResource(jedis);
pool.destroy();
assertTrue(pool.isClosed());
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();
assertTrue(pool.isClosed());
}
@Test
public void checkJedisIsReusedWhenReturned() {
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort());
Jedis jedis = pool.getResource();
jedis.auth("foobared");
jedis.set("foo", "0");
pool.returnResource(jedis);
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort());
Jedis jedis = pool.getResource();
jedis.auth("foobared");
jedis.set("foo", "0");
pool.returnResource(jedis);
jedis = pool.getResource();
jedis.auth("foobared");
jedis.incr("foo");
pool.returnResource(jedis);
pool.destroy();
assertTrue(pool.isClosed());
jedis = pool.getResource();
jedis.auth("foobared");
jedis.incr("foo");
pool.returnResource(jedis);
pool.destroy();
assertTrue(pool.isClosed());
}
@Test
public void checkPoolRepairedWhenJedisIsBroken() {
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort());
Jedis jedis = pool.getResource();
jedis.auth("foobared");
jedis.quit();
pool.returnBrokenResource(jedis);
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort());
Jedis jedis = pool.getResource();
jedis.auth("foobared");
jedis.quit();
pool.returnBrokenResource(jedis);
jedis = pool.getResource();
jedis.auth("foobared");
jedis.incr("foo");
pool.returnResource(jedis);
pool.destroy();
assertTrue(pool.isClosed());
jedis = pool.getResource();
jedis.auth("foobared");
jedis.incr("foo");
pool.returnResource(jedis);
pool.destroy();
assertTrue(pool.isClosed());
}
@Test(expected = JedisConnectionException.class)
public void checkPoolOverflow() {
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");
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.getHost(), hnp.getPort(),
2000, "foobared");
Jedis jedis = pool.getResource();
jedis.set("foo", "bar");
pool.returnResource(jedis);
pool.destroy();
assertTrue(pool.isClosed());
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();
assertTrue(pool.isClosed());
}
@Test
public void nonDefaultDatabase() {
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();
assertTrue(pool0.isClosed());
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();
assertTrue(pool0.isClosed());
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();
assertTrue(pool1.isClosed());
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();
assertTrue(pool1.isClosed());
}
@Test
public void startWithUrlString() {
Jedis j = new Jedis("localhost", 6380);
j.auth("foobared");
j.select(2);
j.set("foo", "bar");
JedisPool pool = new JedisPool("redis://:foobared@localhost:6380/2");
Jedis jedis = pool.getResource();
assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo"));
Jedis j = new Jedis("localhost", 6380);
j.auth("foobared");
j.select(2);
j.set("foo", "bar");
JedisPool pool = new JedisPool("redis://:foobared@localhost:6380/2");
Jedis jedis = pool.getResource();
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.select(2);
j.set("foo", "bar");
JedisPool pool = new JedisPool(new URI(
"redis://:foobared@localhost:6380/2"));
Jedis jedis = pool.getResource();
assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo"));
Jedis j = new Jedis("localhost", 6380);
j.auth("foobared");
j.select(2);
j.set("foo", "bar");
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 allowUrlWithNoDBAndNoPassword() throws URISyntaxException {
new JedisPool("redis://localhost:6380");
new JedisPool(new URI("redis://localhost:6380"));
new JedisPool("redis://localhost:6380");
new JedisPool(new URI("redis://localhost:6380"));
}
@Test
public void selectDatabaseOnActivation() {
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000, "foobared");
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000, "foobared");
Jedis jedis0 = pool.getResource();
assertEquals(0L, jedis0.getDB().longValue());
Jedis jedis0 = pool.getResource();
assertEquals(0L, jedis0.getDB().longValue());
jedis0.select(1);
assertEquals(1L, jedis0.getDB().longValue());
jedis0.select(1);
assertEquals(1L, jedis0.getDB().longValue());
pool.returnResource(jedis0);
pool.returnResource(jedis0);
Jedis jedis1 = pool.getResource();
assertTrue("Jedis instance was not reused", jedis1 == jedis0);
assertEquals(0L, jedis1.getDB().longValue());
Jedis jedis1 = pool.getResource();
assertTrue("Jedis instance was not reused", jedis1 == jedis0);
assertEquals(0L, jedis1.getDB().longValue());
pool.returnResource(jedis1);
pool.destroy();
assertTrue(pool.isClosed());
pool.returnResource(jedis1);
pool.destroy();
assertTrue(pool.isClosed());
}
@Test
public void customClientName() {
JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 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();
assertTrue(pool0.isClosed());
pool0.returnResource(jedis);
pool0.destroy();
assertTrue(pool0.isClosed());
}
@Test
@@ -263,99 +263,99 @@ public class JedisPoolTest extends Assert {
@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");
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(),
2000, "foobared");
Jedis jedis = pool.getResource();
try {
jedis.set("hello", "jedis");
Transaction t = jedis.multi();
t.set("hello", "world");
} finally {
jedis.close();
}
Jedis jedis = pool.getResource();
try {
jedis.set("hello", "jedis");
Transaction t = jedis.multi();
t.set("hello", "world");
} finally {
jedis.close();
}
Jedis jedis2 = pool.getResource();
try {
assertTrue(jedis == jedis2);
assertEquals("jedis", jedis2.get("hello"));
} finally {
jedis2.close();
}
Jedis jedis2 = pool.getResource();
try {
assertTrue(jedis == jedis2);
assertEquals("jedis", jedis2.get("hello"));
} finally {
jedis2.close();
}
pool.destroy();
assertTrue(pool.isClosed());
pool.destroy();
assertTrue(pool.isClosed());
}
@Test
public void checkResourceIsCloseable() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(),
2000, "foobared");
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(),
2000, "foobared");
Jedis jedis = pool.getResource();
try {
jedis.set("hello", "jedis");
} finally {
jedis.close();
}
Jedis jedis = pool.getResource();
try {
jedis.set("hello", "jedis");
} finally {
jedis.close();
}
Jedis jedis2 = pool.getResource();
try {
assertEquals(jedis, jedis2);
} finally {
jedis2.close();
}
Jedis jedis2 = pool.getResource();
try {
assertEquals(jedis, jedis2);
} finally {
jedis2.close();
}
}
@Test
public void returnNullObjectShouldNotFail() {
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000, "foobared", 0, "my_shiny_client_name");
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000, "foobared", 0, "my_shiny_client_name");
pool.returnBrokenResource(null);
pool.returnResource(null);
pool.returnResourceObject(null);
pool.returnBrokenResource(null);
pool.returnResource(null);
pool.returnResourceObject(null);
}
@Test
public void getNumActiveIsNegativeWhenPoolIsClosed() {
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000, "foobared", 0, "my_shiny_client_name");
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost(),
hnp.getPort(), 2000, "foobared", 0, "my_shiny_client_name");
pool.destroy();
assertTrue(pool.getNumActive() < 0);
pool.destroy();
assertTrue(pool.getNumActive() < 0);
}
@Test
public void getNumActiveReturnsTheCorrectNumber() {
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"));
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"));
assertEquals(1, pool.getNumActive());
assertEquals(1, pool.getNumActive());
Jedis jedis2 = pool.getResource();
jedis.auth("foobared");
jedis.set("foo", "bar");
Jedis jedis2 = pool.getResource();
jedis.auth("foobared");
jedis.set("foo", "bar");
assertEquals(2, pool.getNumActive());
assertEquals(2, pool.getNumActive());
pool.returnResource(jedis);
assertEquals(1, pool.getNumActive());
pool.returnResource(jedis);
assertEquals(1, pool.getNumActive());
pool.returnResource(jedis2);
pool.returnResource(jedis2);
assertEquals(0, pool.getNumActive());
assertEquals(0, pool.getNumActive());
pool.destroy();
pool.destroy();
}
}

View File

@@ -19,14 +19,14 @@ public class JedisSentinelPoolTest extends JedisTestBase {
private static final String MASTER_NAME = "mymaster";
protected static HostAndPort master = HostAndPortUtil.getRedisServers()
.get(2);
.get(2);
protected static HostAndPort slave1 = HostAndPortUtil.getRedisServers()
.get(3);
.get(3);
protected static HostAndPort sentinel1 = HostAndPortUtil
.getSentinelServers().get(1);
.getSentinelServers().get(1);
protected static HostAndPort sentinel2 = HostAndPortUtil
.getSentinelServers().get(3);
.getSentinelServers().get(3);
protected static Jedis sentinelJedis1;
protected static Jedis sentinelJedis2;
@@ -35,188 +35,188 @@ public class JedisSentinelPoolTest extends JedisTestBase {
@Before
public void setUp() throws Exception {
sentinels.add(sentinel1.toString());
sentinels.add(sentinel2.toString());
sentinels.add(sentinel1.toString());
sentinels.add(sentinel2.toString());
sentinelJedis1 = new Jedis(sentinel1.getHost(), sentinel1.getPort());
sentinelJedis2 = new Jedis(sentinel2.getHost(), sentinel2.getPort());
sentinelJedis1 = new Jedis(sentinel1.getHost(), sentinel1.getPort());
sentinelJedis2 = new Jedis(sentinel2.getHost(), sentinel2.getPort());
}
@Test(expected = JedisConnectionException.class)
public void initializeWithNotAvailableSentinelsShouldThrowException() {
Set<String> wrongSentinels = new HashSet<String>();
wrongSentinels.add(new HostAndPort("localhost", 65432).toString());
wrongSentinels.add(new HostAndPort("localhost", 65431).toString());
Set<String> wrongSentinels = new HashSet<String>();
wrongSentinels.add(new HostAndPort("localhost", 65432).toString());
wrongSentinels.add(new HostAndPort("localhost", 65431).toString());
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME,
wrongSentinels);
pool.destroy();
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME,
wrongSentinels);
pool.destroy();
}
@Test(expected = JedisException.class)
public void initializeWithNotMonitoredMasterNameShouldThrowException() {
final String wrongMasterName = "wrongMasterName";
JedisSentinelPool pool = new JedisSentinelPool(wrongMasterName,
sentinels);
pool.destroy();
final String wrongMasterName = "wrongMasterName";
JedisSentinelPool pool = new JedisSentinelPool(wrongMasterName,
sentinels);
pool.destroy();
}
@Test
public void checkCloseableConnections() throws Exception {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
config, 1000, "foobared", 2);
Jedis jedis = pool.getResource();
jedis.auth("foobared");
jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo"));
pool.returnResource(jedis);
pool.close();
assertTrue(pool.isClosed());
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
config, 1000, "foobared", 2);
Jedis jedis = pool.getResource();
jedis.auth("foobared");
jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo"));
pool.returnResource(jedis);
pool.close();
assertTrue(pool.isClosed());
}
@Test
public void ensureSafeTwiceFailover() throws InterruptedException {
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
new GenericObjectPoolConfig(), 1000, "foobared", 2);
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
new GenericObjectPoolConfig(), 1000, "foobared", 2);
forceFailover(pool);
// after failover sentinel needs a bit of time to stabilize before a new
// failover
Thread.sleep(100);
forceFailover(pool);
forceFailover(pool);
// after failover sentinel needs a bit of time to stabilize before a new
// failover
Thread.sleep(100);
forceFailover(pool);
// you can test failover as much as possible
// you can test failover as much as possible
}
@Test
public void returnResourceShouldResetState() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
config, 1000, "foobared", 2);
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
config, 1000, "foobared", 2);
Jedis jedis = pool.getResource();
Jedis jedis2 = null;
Jedis jedis = pool.getResource();
Jedis jedis2 = null;
try {
jedis.set("hello", "jedis");
Transaction t = jedis.multi();
t.set("hello", "world");
pool.returnResource(jedis);
try {
jedis.set("hello", "jedis");
Transaction t = jedis.multi();
t.set("hello", "world");
pool.returnResource(jedis);
jedis2 = pool.getResource();
jedis2 = pool.getResource();
assertTrue(jedis == jedis2);
assertEquals("jedis", jedis2.get("hello"));
} catch (JedisConnectionException e) {
if (jedis2 != null) {
pool.returnBrokenResource(jedis2);
jedis2 = null;
}
} finally {
if (jedis2 != null)
pool.returnResource(jedis2);
assertTrue(jedis == jedis2);
assertEquals("jedis", jedis2.get("hello"));
} catch (JedisConnectionException e) {
if (jedis2 != null) {
pool.returnBrokenResource(jedis2);
jedis2 = null;
}
} finally {
if (jedis2 != null)
pool.returnResource(jedis2);
pool.destroy();
}
pool.destroy();
}
}
@Test
public void checkResourceIsCloseable() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
config, 1000, "foobared", 2);
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
config, 1000, "foobared", 2);
Jedis jedis = pool.getResource();
try {
jedis.set("hello", "jedis");
} finally {
jedis.close();
}
Jedis jedis = pool.getResource();
try {
jedis.set("hello", "jedis");
} finally {
jedis.close();
}
Jedis jedis2 = pool.getResource();
try {
assertEquals(jedis, jedis2);
} finally {
jedis2.close();
}
Jedis jedis2 = pool.getResource();
try {
assertEquals(jedis, jedis2);
} finally {
jedis2.close();
}
}
@Test
public void returnResourceWithNullResource() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
config, 1000, "foobared", 2);
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
config, 1000, "foobared", 2);
Jedis nullJedis = null;
pool.returnResource(nullJedis);
pool.destroy();
Jedis nullJedis = null;
pool.returnResource(nullJedis);
pool.destroy();
}
@Test
public void returnBrokenResourceWithNullResource() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
config, 1000, "foobared", 2);
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
config, 1000, "foobared", 2);
Jedis nullJedis = null;
pool.returnBrokenResource(nullJedis);
pool.destroy();
Jedis nullJedis = null;
pool.returnBrokenResource(nullJedis);
pool.destroy();
}
private void forceFailover(JedisSentinelPool pool)
throws InterruptedException {
HostAndPort oldMaster = pool.getCurrentHostMaster();
throws InterruptedException {
HostAndPort oldMaster = pool.getCurrentHostMaster();
// jedis connection should be master
Jedis beforeFailoverJedis = pool.getResource();
assertEquals("PONG", beforeFailoverJedis.ping());
// jedis connection should be master
Jedis beforeFailoverJedis = pool.getResource();
assertEquals("PONG", beforeFailoverJedis.ping());
waitForFailover(pool, oldMaster);
waitForFailover(pool, oldMaster);
Jedis afterFailoverJedis = pool.getResource();
assertEquals("PONG", afterFailoverJedis.ping());
assertEquals("foobared", afterFailoverJedis.configGet("requirepass")
.get(1));
assertEquals(2, afterFailoverJedis.getDB().intValue());
Jedis afterFailoverJedis = pool.getResource();
assertEquals("PONG", afterFailoverJedis.ping());
assertEquals("foobared", afterFailoverJedis.configGet("requirepass")
.get(1));
assertEquals(2, afterFailoverJedis.getDB().intValue());
// returning both connections to the pool should not throw
beforeFailoverJedis.close();
afterFailoverJedis.close();
// returning both connections to the pool should not throw
beforeFailoverJedis.close();
afterFailoverJedis.close();
}
private void waitForFailover(JedisSentinelPool pool, HostAndPort oldMaster)
throws InterruptedException {
HostAndPort newMaster = JedisSentinelTestUtil.waitForNewPromotedMaster(
MASTER_NAME, sentinelJedis1, sentinelJedis2);
throws InterruptedException {
HostAndPort newMaster = JedisSentinelTestUtil.waitForNewPromotedMaster(
MASTER_NAME, sentinelJedis1, sentinelJedis2);
waitForJedisSentinelPoolRecognizeNewMaster(pool, newMaster);
waitForJedisSentinelPoolRecognizeNewMaster(pool, newMaster);
}
private void waitForJedisSentinelPoolRecognizeNewMaster(
JedisSentinelPool pool, HostAndPort newMaster)
throws InterruptedException {
JedisSentinelPool pool, HostAndPort newMaster)
throws InterruptedException {
while (true) {
HostAndPort currentHostMaster = pool.getCurrentHostMaster();
while (true) {
HostAndPort currentHostMaster = pool.getCurrentHostMaster();
if (newMaster.equals(currentHostMaster))
break;
if (newMaster.equals(currentHostMaster))
break;
System.out
.println("JedisSentinelPool's master is not yet changed, sleep...");
System.out
.println("JedisSentinelPool's master is not yet changed, sleep...");
Thread.sleep(100);
}
Thread.sleep(100);
}
}
}

View File

@@ -21,16 +21,16 @@ public class JedisSentinelTest extends JedisTestBase {
private static final String MASTER_IP = "127.0.0.1";
protected static HostAndPort master = HostAndPortUtil.getRedisServers()
.get(0);
.get(0);
protected static HostAndPort slave = HostAndPortUtil.getRedisServers().get(
4);
4);
protected static HostAndPort sentinel = HostAndPortUtil
.getSentinelServers().get(0);
.getSentinelServers().get(0);
protected static HostAndPort sentinelForFailover = HostAndPortUtil
.getSentinelServers().get(2);
.getSentinelServers().get(2);
protected static HostAndPort masterForFailover = HostAndPortUtil
.getRedisServers().get(5);
.getRedisServers().get(5);
@Before
public void setup() throws InterruptedException {
@@ -38,173 +38,173 @@ public class JedisSentinelTest extends JedisTestBase {
@After
public void clear() throws InterruptedException {
// New Sentinel (after 2.8.1)
// when slave promoted to master (slave of no one), New Sentinel force
// to restore it (demote)
// so, promote(slaveof) slave to master has no effect, not same to old
// Sentinel's behavior
ensureRemoved(MONITOR_MASTER_NAME);
ensureRemoved(REMOVE_MASTER_NAME);
// 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
ensureRemoved(MONITOR_MASTER_NAME);
ensureRemoved(REMOVE_MASTER_NAME);
}
@Test
public void sentinel() {
Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());
Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());
try {
List<Map<String, String>> masters = j.sentinelMasters();
try {
List<Map<String, String>> masters = j.sentinelMasters();
boolean inMasters = false;
for (Map<String, String> master : masters)
if (MASTER_NAME.equals(master.get("name")))
inMasters = true;
boolean inMasters = false;
for (Map<String, String> master : masters)
if (MASTER_NAME.equals(master.get("name")))
inMasters = true;
assertTrue(inMasters);
assertTrue(inMasters);
List<String> masterHostAndPort = j
.sentinelGetMasterAddrByName(MASTER_NAME);
HostAndPort masterFromSentinel = new HostAndPort(
masterHostAndPort.get(0),
Integer.parseInt(masterHostAndPort.get(1)));
assertEquals(master, masterFromSentinel);
List<String> masterHostAndPort = j
.sentinelGetMasterAddrByName(MASTER_NAME);
HostAndPort masterFromSentinel = new HostAndPort(
masterHostAndPort.get(0),
Integer.parseInt(masterHostAndPort.get(1)));
assertEquals(master, masterFromSentinel);
List<Map<String, String>> slaves = j.sentinelSlaves(MASTER_NAME);
assertTrue(slaves.size() > 0);
assertEquals(master.getPort(),
Integer.parseInt(slaves.get(0).get("master-port")));
List<Map<String, String>> slaves = j.sentinelSlaves(MASTER_NAME);
assertTrue(slaves.size() > 0);
assertEquals(master.getPort(),
Integer.parseInt(slaves.get(0).get("master-port")));
// DO NOT RE-RUN TEST TOO FAST, RESET TAKES SOME TIME TO... RESET
assertEquals(Long.valueOf(1), j.sentinelReset(MASTER_NAME));
assertEquals(Long.valueOf(0), j.sentinelReset("woof" + MASTER_NAME));
} finally {
j.close();
}
// DO NOT RE-RUN TEST TOO FAST, RESET TAKES SOME TIME TO... RESET
assertEquals(Long.valueOf(1), j.sentinelReset(MASTER_NAME));
assertEquals(Long.valueOf(0), j.sentinelReset("woof" + MASTER_NAME));
} finally {
j.close();
}
}
@Test
public void sentinelFailover() throws InterruptedException {
Jedis j = new Jedis(sentinelForFailover.getHost(),
sentinelForFailover.getPort());
Jedis j2 = new Jedis(sentinelForFailover.getHost(),
sentinelForFailover.getPort());
Jedis j = new Jedis(sentinelForFailover.getHost(),
sentinelForFailover.getPort());
Jedis j2 = new Jedis(sentinelForFailover.getHost(),
sentinelForFailover.getPort());
try {
List<String> masterHostAndPort = j
.sentinelGetMasterAddrByName(FAILOVER_MASTER_NAME);
HostAndPort currentMaster = new HostAndPort(
masterHostAndPort.get(0),
Integer.parseInt(masterHostAndPort.get(1)));
try {
List<String> masterHostAndPort = j
.sentinelGetMasterAddrByName(FAILOVER_MASTER_NAME);
HostAndPort currentMaster = new HostAndPort(
masterHostAndPort.get(0),
Integer.parseInt(masterHostAndPort.get(1)));
JedisSentinelTestUtil.waitForNewPromotedMaster(
FAILOVER_MASTER_NAME, j, j2);
JedisSentinelTestUtil.waitForNewPromotedMaster(
FAILOVER_MASTER_NAME, j, j2);
masterHostAndPort = j
.sentinelGetMasterAddrByName(FAILOVER_MASTER_NAME);
HostAndPort newMaster = new HostAndPort(masterHostAndPort.get(0),
Integer.parseInt(masterHostAndPort.get(1)));
masterHostAndPort = j
.sentinelGetMasterAddrByName(FAILOVER_MASTER_NAME);
HostAndPort newMaster = new HostAndPort(masterHostAndPort.get(0),
Integer.parseInt(masterHostAndPort.get(1)));
assertNotEquals(newMaster, currentMaster);
} finally {
j.close();
}
assertNotEquals(newMaster, currentMaster);
} finally {
j.close();
}
}
@Test
public void sentinelMonitor() {
Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());
Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());
try {
// monitor new master
String result = j.sentinelMonitor(MONITOR_MASTER_NAME, MASTER_IP,
master.getPort(), 1);
assertEquals("OK", result);
try {
// monitor new master
String result = j.sentinelMonitor(MONITOR_MASTER_NAME, MASTER_IP,
master.getPort(), 1);
assertEquals("OK", result);
// already monitored
try {
j.sentinelMonitor(MONITOR_MASTER_NAME, MASTER_IP,
master.getPort(), 1);
fail();
} catch (JedisDataException e) {
// pass
}
} finally {
j.close();
}
// already monitored
try {
j.sentinelMonitor(MONITOR_MASTER_NAME, MASTER_IP,
master.getPort(), 1);
fail();
} catch (JedisDataException e) {
// pass
}
} finally {
j.close();
}
}
@Test
public void sentinelRemove() {
Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());
Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());
try {
ensureMonitored(sentinel, REMOVE_MASTER_NAME, MASTER_IP,
master.getPort(), 1);
try {
ensureMonitored(sentinel, REMOVE_MASTER_NAME, MASTER_IP,
master.getPort(), 1);
String result = j.sentinelRemove(REMOVE_MASTER_NAME);
assertEquals("OK", result);
String result = j.sentinelRemove(REMOVE_MASTER_NAME);
assertEquals("OK", result);
// not exist
try {
result = j.sentinelRemove(REMOVE_MASTER_NAME);
assertNotEquals("OK", result);
fail();
} catch (JedisDataException e) {
// pass
}
} finally {
j.close();
}
// not exist
try {
result = j.sentinelRemove(REMOVE_MASTER_NAME);
assertNotEquals("OK", result);
fail();
} catch (JedisDataException e) {
// pass
}
} finally {
j.close();
}
}
@Test
public void sentinelSet() {
Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());
Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());
try {
Map<String, String> parameterMap = new HashMap<String, String>();
parameterMap.put("down-after-milliseconds", String.valueOf(1234));
parameterMap.put("parallel-syncs", String.valueOf(3));
parameterMap.put("quorum", String.valueOf(2));
j.sentinelSet(MASTER_NAME, parameterMap);
try {
Map<String, String> parameterMap = new HashMap<String, String>();
parameterMap.put("down-after-milliseconds", String.valueOf(1234));
parameterMap.put("parallel-syncs", String.valueOf(3));
parameterMap.put("quorum", String.valueOf(2));
j.sentinelSet(MASTER_NAME, parameterMap);
List<Map<String, String>> masters = j.sentinelMasters();
for (Map<String, String> master : masters) {
if (master.get("name").equals(MASTER_NAME)) {
assertEquals(1234, Integer.parseInt(master
.get("down-after-milliseconds")));
assertEquals(3,
Integer.parseInt(master.get("parallel-syncs")));
assertEquals(2, Integer.parseInt(master.get("quorum")));
}
}
List<Map<String, String>> masters = j.sentinelMasters();
for (Map<String, String> master : masters) {
if (master.get("name").equals(MASTER_NAME)) {
assertEquals(1234, Integer.parseInt(master
.get("down-after-milliseconds")));
assertEquals(3,
Integer.parseInt(master.get("parallel-syncs")));
assertEquals(2, Integer.parseInt(master.get("quorum")));
}
}
parameterMap.put("quorum", String.valueOf(1));
j.sentinelSet(MASTER_NAME, parameterMap);
} finally {
j.close();
}
parameterMap.put("quorum", String.valueOf(1));
j.sentinelSet(MASTER_NAME, parameterMap);
} finally {
j.close();
}
}
private void ensureMonitored(HostAndPort sentinel, String masterName,
String ip, int port, int quorum) {
Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());
try {
j.sentinelMonitor(masterName, ip, port, quorum);
} catch (JedisDataException e) {
} finally {
j.close();
}
String ip, int port, int quorum) {
Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());
try {
j.sentinelMonitor(masterName, ip, port, quorum);
} catch (JedisDataException e) {
} finally {
j.close();
}
}
private void ensureRemoved(String masterName) {
Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());
try {
j.sentinelRemove(masterName);
} catch (JedisDataException e) {
} finally {
j.close();
}
Jedis j = new Jedis(sentinel.getHost(), sentinel.getPort());
try {
j.sentinelRemove(masterName);
} catch (JedisDataException e) {
} finally {
j.close();
}
}
}

View File

@@ -20,107 +20,107 @@ import redis.clients.util.SafeEncoder;
public class JedisTest extends JedisCommandTestBase {
@Test
public void useWithoutConnecting() {
Jedis jedis = new Jedis("localhost");
jedis.auth("foobared");
jedis.dbSize();
Jedis jedis = new Jedis("localhost");
jedis.auth("foobared");
jedis.dbSize();
}
@Test
public void checkBinaryData() {
byte[] bigdata = new byte[1777];
for (int b = 0; b < bigdata.length; b++) {
bigdata[b] = (byte) ((byte) b % 255);
}
Map<String, String> hash = new HashMap<String, String>();
hash.put("data", SafeEncoder.encode(bigdata));
byte[] bigdata = new byte[1777];
for (int b = 0; b < bigdata.length; b++) {
bigdata[b] = (byte) ((byte) b % 255);
}
Map<String, String> hash = new HashMap<String, String>();
hash.put("data", SafeEncoder.encode(bigdata));
String status = jedis.hmset("foo", hash);
assertEquals("OK", status);
assertEquals(hash, jedis.hgetAll("foo"));
String status = jedis.hmset("foo", hash);
assertEquals("OK", status);
assertEquals(hash, jedis.hgetAll("foo"));
}
@Test
public void connectWithShardInfo() {
JedisShardInfo shardInfo = new JedisShardInfo("localhost",
Protocol.DEFAULT_PORT);
shardInfo.setPassword("foobared");
Jedis jedis = new Jedis(shardInfo);
jedis.get("foo");
JedisShardInfo shardInfo = new JedisShardInfo("localhost",
Protocol.DEFAULT_PORT);
shardInfo.setPassword("foobared");
Jedis jedis = new Jedis(shardInfo);
jedis.get("foo");
}
@Test(expected = JedisConnectionException.class)
public void timeoutConnection() throws Exception {
jedis = new Jedis("localhost", 6379, 15000);
jedis.auth("foobared");
jedis.configSet("timeout", "1");
Thread.sleep(2000);
jedis.hmget("foobar", "foo");
jedis = new Jedis("localhost", 6379, 15000);
jedis.auth("foobared");
jedis.configSet("timeout", "1");
Thread.sleep(2000);
jedis.hmget("foobar", "foo");
}
@Test(expected = JedisConnectionException.class)
public void timeoutConnectionWithURI() throws Exception {
jedis = new Jedis(new URI("redis://:foobared@localhost:6380/2"), 15000);
jedis.configSet("timeout", "1");
Thread.sleep(2000);
jedis.hmget("foobar", "foo");
jedis = new Jedis(new URI("redis://:foobared@localhost:6380/2"), 15000);
jedis.configSet("timeout", "1");
Thread.sleep(2000);
jedis.hmget("foobar", "foo");
}
@Test(expected = JedisDataException.class)
public void failWhenSendingNullValues() {
jedis.set("foo", null);
jedis.set("foo", null);
}
@Test
public void shouldReconnectToSameDB() throws IOException {
jedis.select(1);
jedis.set("foo", "bar");
jedis.getClient().getSocket().shutdownInput();
jedis.getClient().getSocket().shutdownOutput();
assertEquals("bar", jedis.get("foo"));
jedis.select(1);
jedis.set("foo", "bar");
jedis.getClient().getSocket().shutdownInput();
jedis.getClient().getSocket().shutdownOutput();
assertEquals("bar", jedis.get("foo"));
}
@Test
public void startWithUrlString() {
Jedis j = new Jedis("localhost", 6380);
j.auth("foobared");
j.select(2);
j.set("foo", "bar");
Jedis jedis = new Jedis("redis://:foobared@localhost:6380/2");
assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo"));
Jedis j = new Jedis("localhost", 6380);
j.auth("foobared");
j.select(2);
j.set("foo", "bar");
Jedis jedis = new Jedis("redis://:foobared@localhost:6380/2");
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.select(2);
j.set("foo", "bar");
Jedis jedis = new Jedis(new URI("redis://:foobared@localhost:6380/2"));
assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo"));
Jedis j = new Jedis("localhost", 6380);
j.auth("foobared");
j.select(2);
j.set("foo", "bar");
Jedis jedis = new Jedis(new URI("redis://:foobared@localhost:6380/2"));
assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo"));
}
@Test
public void allowUrlWithNoDBAndNoPassword() {
Jedis jedis = new Jedis("redis://localhost:6380");
jedis.auth("foobared");
assertEquals(jedis.getClient().getHost(), "localhost");
assertEquals(jedis.getClient().getPort(), 6380);
assertEquals(jedis.getDB(), (Long) 0L);
Jedis jedis = new Jedis("redis://localhost:6380");
jedis.auth("foobared");
assertEquals(jedis.getClient().getHost(), "localhost");
assertEquals(jedis.getClient().getPort(), 6380);
assertEquals(jedis.getDB(), (Long) 0L);
jedis = new Jedis("redis://localhost:6380/");
jedis.auth("foobared");
assertEquals(jedis.getClient().getHost(), "localhost");
assertEquals(jedis.getClient().getPort(), 6380);
assertEquals(jedis.getDB(), (Long) 0L);
jedis = new Jedis("redis://localhost:6380/");
jedis.auth("foobared");
assertEquals(jedis.getClient().getHost(), "localhost");
assertEquals(jedis.getClient().getPort(), 6380);
assertEquals(jedis.getDB(), (Long) 0L);
}
@Test
public void checkCloseable() {
jedis.close();
BinaryJedis bj = new BinaryJedis("localhost");
bj.connect();
bj.close();
jedis.close();
BinaryJedis bj = new BinaryJedis("localhost");
bj.connect();
bj.close();
}
}

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

@@ -27,453 +27,453 @@ public class PipeliningTest extends Assert {
@Before
public void setUp() throws Exception {
jedis = new Jedis(hnp.getHost(), hnp.getPort(), 500);
jedis.connect();
jedis.auth("foobared");
jedis.flushAll();
jedis = new Jedis(hnp.getHost(), hnp.getPort(), 500);
jedis.connect();
jedis.auth("foobared");
jedis.flushAll();
}
@Test
public void pipeline() throws UnsupportedEncodingException {
Pipeline p = jedis.pipelined();
p.set("foo", "bar");
p.get("foo");
List<Object> results = p.syncAndReturnAll();
Pipeline 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.setrange("setrange", 0, "0123456789");
byte[] bytesForSetRange = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
jedis.setrange("setrangebytes".getBytes(), 0, bytesForSetRange);
jedis.set("string", "foo");
jedis.lpush("list", "foo");
jedis.hset("hash", "foo", "bar");
jedis.zadd("zset", 1, "foo");
jedis.sadd("set", "foo");
jedis.setrange("setrange", 0, "0123456789");
byte[] bytesForSetRange = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
jedis.setrange("setrangebytes".getBytes(), 0, bytesForSetRange);
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);
Response<String> getrange = p.getrange("setrange", 1, 3);
Response<byte[]> getrangeBytes = p.getrange("setrangebytes".getBytes(),
6, 8);
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);
Response<String> getrange = p.getrange("setrange", 1, 3);
Response<byte[]> getrangeBytes = p.getrange("setrangebytes".getBytes(),
6, 8);
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("123", getrange.get());
byte[] expectedGetRangeBytes = { 6, 7, 8 };
assertArrayEquals(expectedGetRangeBytes, getrangeBytes.get());
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("123", getrange.get());
byte[] expectedGetRangeBytes = { 6, 7, 8 };
assertArrayEquals(expectedGetRangeBytes, getrangeBytes.get());
}
@Test
public void pipelineResponseWithData() {
jedis.zadd("zset", 1, "foo");
jedis.zadd("zset", 1, "foo");
Pipeline p = jedis.pipelined();
Response<Double> score = p.zscore("zset", "foo");
p.sync();
Pipeline p = jedis.pipelined();
Response<Double> score = p.zscore("zset", "foo");
p.sync();
assertNotNull(score.get());
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));
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");
jedis.zadd("zset", 1, "foo");
Pipeline p = jedis.pipelined();
Response<Double> score = p.zscore("zset", "bar");
p.sync();
Pipeline p = jedis.pipelined();
Response<Double> score = p.zscore("zset", "bar");
p.sync();
assertNull(score.get());
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());
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();
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();
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(new Long(-1), r1.get());
assertEquals(new Long(-3), r2.get());
assertEquals(4, result.size());
assertEquals(4, result.size());
assertEquals("OK", result.get(0));
assertEquals("QUEUED", result.get(1));
assertEquals("QUEUED", result.get(2));
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));
// 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));
assertEquals(new Long(-1), r3.get().get(0));
assertEquals(new Long(-3), r3.get().get(1));
}
@Test
public void multiWithSync() {
jedis.set("foo", "314");
jedis.set("bar", "foo");
jedis.set("hello", "world");
Pipeline p = jedis.pipelined();
Response<String> r1 = p.get("bar");
p.multi();
Response<String> r2 = p.get("foo");
p.exec();
Response<String> r3 = p.get("hello");
p.sync();
jedis.set("foo", "314");
jedis.set("bar", "foo");
jedis.set("hello", "world");
Pipeline p = jedis.pipelined();
Response<String> r1 = p.get("bar");
p.multi();
Response<String> r2 = p.get("foo");
p.exec();
Response<String> r3 = p.get("hello");
p.sync();
// before multi
assertEquals("foo", r1.get());
// It should be readable whether exec's response was built or not
assertEquals("314", r2.get());
// after multi
assertEquals("world", r3.get());
// before multi
assertEquals("foo", r1.get());
// It should be readable whether exec's response was built or not
assertEquals("314", r2.get());
// after multi
assertEquals("world", r3.get());
}
@Test(expected = JedisDataException.class)
public void pipelineExecShoudThrowJedisDataExceptionWhenNotInMulti() {
Pipeline pipeline = jedis.pipelined();
pipeline.exec();
Pipeline pipeline = jedis.pipelined();
pipeline.exec();
}
@Test(expected = JedisDataException.class)
public void pipelineDiscardShoudThrowJedisDataExceptionWhenNotInMulti() {
Pipeline pipeline = jedis.pipelined();
pipeline.discard();
Pipeline pipeline = jedis.pipelined();
pipeline.discard();
}
@Test(expected = JedisDataException.class)
public void pipelineMultiShoudThrowJedisDataExceptionWhenAlreadyInMulti() {
Pipeline pipeline = jedis.pipelined();
pipeline.multi();
pipeline.set("foo", "3");
pipeline.multi();
Pipeline pipeline = jedis.pipelined();
pipeline.multi();
pipeline.set("foo", "3");
pipeline.multi();
}
@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!'";
String script = "return 'success!'";
Pipeline p = jedis.pipelined();
Response<String> result = p.eval(script);
p.sync();
Pipeline p = jedis.pipelined();
Response<String> result = p.eval(script);
p.sync();
assertEquals("success!", result.get());
assertEquals("success!", result.get());
}
@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])";
String key = "test";
String arg = "3";
String script = "redis.call('INCRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[1], ARGV[1])";
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();
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();
assertNull(result0.get());
assertNull(result1.get());
assertEquals("13", result2.get());
assertNull(result0.get());
assertNull(result1.get());
assertEquals("13", result2.get());
}
@Test
public void testEvalsha() {
String script = "return 'success!'";
String sha1 = jedis.scriptLoad(script);
String script = "return 'success!'";
String sha1 = jedis.scriptLoad(script);
assertTrue(jedis.scriptExists(sha1));
assertTrue(jedis.scriptExists(sha1));
Pipeline p = jedis.pipelined();
Response<String> result = p.evalsha(sha1);
p.sync();
Pipeline p = jedis.pipelined();
Response<String> result = p.evalsha(sha1);
p.sync();
assertEquals("success!", result.get());
assertEquals("success!", result.get());
}
@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);
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);
assertTrue(jedis.scriptExists(sha1));
assertTrue(jedis.scriptExists(sha1));
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();
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());
assertNull(result0.get());
assertNull(result1.get());
assertEquals("13", result2.get());
}
@Test
public void testPipelinedTransactionResponse() {
String key1 = "key1";
String val1 = "val1";
String key1 = "key1";
String val1 = "val1";
String key2 = "key2";
String val2 = "val2";
String key2 = "key2";
String val2 = "val2";
String key3 = "key3";
String field1 = "field1";
String field2 = "field2";
String field3 = "field3";
String field4 = "field4";
String key3 = "key3";
String field1 = "field1";
String field2 = "field2";
String field3 = "field3";
String field4 = "field4";
String value1 = "value1";
String value2 = "value2";
String value3 = "value3";
String value4 = "value4";
String value1 = "value1";
String value2 = "value2";
String value3 = "value3";
String value4 = "value4";
Map<String, String> hashMap = new HashMap<String, String>();
hashMap.put(field1, value1);
hashMap.put(field2, value2);
Map<String, String> hashMap = new HashMap<String, String>();
hashMap.put(field1, value1);
hashMap.put(field2, value2);
String key4 = "key4";
Map<String, String> hashMap1 = new HashMap<String, String>();
hashMap1.put(field3, value3);
hashMap1.put(field4, value4);
String key4 = "key4";
Map<String, String> hashMap1 = new HashMap<String, String>();
hashMap1.put(field3, value3);
hashMap1.put(field4, value4);
jedis.set(key1, val1);
jedis.set(key2, val2);
jedis.hmset(key3, hashMap);
jedis.hmset(key4, hashMap1);
jedis.set(key1, val1);
jedis.set(key2, val2);
jedis.hmset(key3, hashMap);
jedis.hmset(key4, hashMap1);
Pipeline pipeline = jedis.pipelined();
pipeline.multi();
Pipeline pipeline = jedis.pipelined();
pipeline.multi();
pipeline.get(key1);
pipeline.hgetAll(key2);
pipeline.hgetAll(key3);
pipeline.get(key4);
pipeline.get(key1);
pipeline.hgetAll(key2);
pipeline.hgetAll(key3);
pipeline.get(key4);
Response<List<Object>> response = pipeline.exec();
pipeline.sync();
Response<List<Object>> response = pipeline.exec();
pipeline.sync();
List<Object> result = response.get();
List<Object> result = response.get();
assertEquals(4, result.size());
assertEquals(4, result.size());
assertEquals("val1", result.get(0));
assertEquals("val1", result.get(0));
assertTrue(result.get(1) instanceof JedisDataException);
assertTrue(result.get(1) instanceof JedisDataException);
Map<String, String> hashMapReceived = (Map<String, String>) result
.get(2);
Iterator<String> iterator = hashMapReceived.keySet().iterator();
String mapKey1 = iterator.next();
String mapKey2 = iterator.next();
assertFalse(iterator.hasNext());
verifyHasBothValues(mapKey1, mapKey2, field1, field2);
String mapValue1 = hashMapReceived.get(mapKey1);
String mapValue2 = hashMapReceived.get(mapKey2);
verifyHasBothValues(mapValue1, mapValue2, value1, value2);
Map<String, String> hashMapReceived = (Map<String, String>) result
.get(2);
Iterator<String> iterator = hashMapReceived.keySet().iterator();
String mapKey1 = iterator.next();
String mapKey2 = iterator.next();
assertFalse(iterator.hasNext());
verifyHasBothValues(mapKey1, mapKey2, field1, field2);
String mapValue1 = hashMapReceived.get(mapKey1);
String mapValue2 = hashMapReceived.get(mapKey2);
verifyHasBothValues(mapValue1, mapValue2, value1, value2);
assertTrue(result.get(3) instanceof JedisDataException);
assertTrue(result.get(3) instanceof JedisDataException);
}
@Test
public void testSyncWithNoCommandQueued() {
// we need to test with fresh instance of Jedis
Jedis jedis2 = new Jedis(hnp.getHost(), hnp.getPort(), 500);
Pipeline pipeline = jedis2.pipelined();
pipeline.sync();
jedis2.close();
jedis2 = new Jedis(hnp.getHost(), hnp.getPort(), 500);
pipeline = jedis2.pipelined();
List<Object> resp = pipeline.syncAndReturnAll();
assertTrue(resp.isEmpty());
jedis2.close();
// we need to test with fresh instance of Jedis
Jedis jedis2 = new Jedis(hnp.getHost(), hnp.getPort(), 500);
Pipeline pipeline = jedis2.pipelined();
pipeline.sync();
jedis2.close();
jedis2 = new Jedis(hnp.getHost(), hnp.getPort(), 500);
pipeline = jedis2.pipelined();
List<Object> resp = pipeline.syncAndReturnAll();
assertTrue(resp.isEmpty());
jedis2.close();
}
private void verifyHasBothValues(String firstKey, String secondKey,
String value1, String value2) {
assertFalse(firstKey.equals(secondKey));
assertTrue(firstKey.equals(value1) || firstKey.equals(value2));
assertTrue(secondKey.equals(value1) || secondKey.equals(value2));
String value1, String value2) {
assertFalse(firstKey.equals(secondKey));
assertTrue(firstKey.equals(value1) || firstKey.equals(value2));
assertTrue(secondKey.equals(value1) || secondKey.equals(value2));
}
}

View File

@@ -20,108 +20,108 @@ 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(expected = IOException.class)
public void writeOverflow() throws IOException {
RedisOutputStream ros = new RedisOutputStream(new OutputStream() {
RedisOutputStream ros = new RedisOutputStream(new OutputStream() {
@Override
public void write(int b) throws IOException {
throw new IOException("thrown exception");
@Override
public void write(int b) throws IOException {
throw new IOException("thrown exception");
}
});
}
});
ros.write(new byte[8191]);
ros.write(new byte[8191]);
try {
ros.write((byte) '*');
} catch (IOException ioe) {
}
try {
ros.write((byte) '*');
} catch (IOException ioe) {
}
ros.write((byte) '*');
ros.write((byte) '*');
}
@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

@@ -29,135 +29,135 @@ import redis.clients.jedis.exceptions.JedisDataException;
public class ShardedJedisPipelineTest {
private static HostAndPort redis1 = HostAndPortUtil.getRedisServers()
.get(0);
.get(0);
private static HostAndPort redis2 = HostAndPortUtil.getRedisServers()
.get(1);
.get(1);
private ShardedJedis jedis;
@Before
public void setUp() throws Exception {
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();
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.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);
}
@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());
}
@Test
public void testSyncWithNoCommandQueued() {
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);
ShardedJedis jedis2 = new ShardedJedis(shards);
ShardedJedisPipeline pipeline = jedis2.pipelined();
pipeline.sync();
jedis2.close();
jedis2 = new ShardedJedis(shards);
pipeline = jedis2.pipelined();
List<Object> resp = pipeline.syncAndReturnAll();
assertTrue(resp.isEmpty());
jedis2.close();
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);
ShardedJedis jedis2 = new ShardedJedis(shards);
ShardedJedisPipeline pipeline = jedis2.pipelined();
pipeline.sync();
jedis2.close();
jedis2 = new ShardedJedis(shards);
pipeline = jedis2.pipelined();
List<Object> resp = pipeline.syncAndReturnAll();
assertTrue(resp.isEmpty());
jedis2.close();
}
}

View File

@@ -20,295 +20,295 @@ import redis.clients.jedis.exceptions.JedisConnectionException;
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.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();
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 GenericObjectPoolConfig(), 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 checkCloseableConnections() throws Exception {
ShardedJedisPool pool = new ShardedJedisPool(
new GenericObjectPoolConfig(), shards);
ShardedJedis jedis = pool.getResource();
jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo"));
pool.returnResource(jedis);
pool.close();
assertTrue(pool.isClosed());
ShardedJedisPool pool = new ShardedJedisPool(
new GenericObjectPoolConfig(), shards);
ShardedJedis jedis = pool.getResource();
jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo"));
pool.returnResource(jedis);
pool.close();
assertTrue(pool.isClosed());
}
@Test
public void checkConnectionWithDefaultPort() {
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();
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 GenericObjectPoolConfig(), 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 GenericObjectPoolConfig(), 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() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
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() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(2);
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 GenericObjectPoolConfig(), 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() {
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("localhost", 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("localhost", 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");
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");
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"));
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo("redis://:foobared@localhost:6380"));
shards.add(new JedisShardInfo("redis://:foobared@localhost:6379"));
GenericObjectPoolConfig redisConfig = new GenericObjectPoolConfig();
ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards);
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 jedis = jedises[0];
assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo"));
jedis = jedises[1];
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");
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");
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")));
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")));
GenericObjectPoolConfig redisConfig = new GenericObjectPoolConfig();
ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards);
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 jedis = jedises[0];
assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo"));
jedis = jedises[1];
assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo"));
jedis = jedises[1];
assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo"));
}
@Test
public void returnResourceShouldResetState() throws URISyntaxException {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
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")));
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")));
ShardedJedisPool pool = new ShardedJedisPool(config, shards);
ShardedJedisPool pool = new ShardedJedisPool(config, shards);
ShardedJedis jedis = pool.getResource();
jedis.set("pipelined", String.valueOf(0));
jedis.set("pipelined2", String.valueOf(0));
ShardedJedis jedis = pool.getResource();
jedis.set("pipelined", String.valueOf(0));
jedis.set("pipelined2", String.valueOf(0));
ShardedJedisPipeline pipeline = jedis.pipelined();
ShardedJedisPipeline pipeline = jedis.pipelined();
pipeline.incr("pipelined");
pipeline.incr("pipelined2");
pipeline.incr("pipelined");
pipeline.incr("pipelined2");
jedis.resetState();
jedis.resetState();
pipeline = jedis.pipelined();
pipeline.incr("pipelined");
pipeline.incr("pipelined2");
List<Object> results = pipeline.syncAndReturnAll();
pipeline = jedis.pipelined();
pipeline.incr("pipelined");
pipeline.incr("pipelined2");
List<Object> results = pipeline.syncAndReturnAll();
assertEquals(2, results.size());
pool.returnResource(jedis);
pool.destroy();
assertEquals(2, results.size());
pool.returnResource(jedis);
pool.destroy();
}
@Test
public void checkResourceIsCloseable() throws URISyntaxException {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
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")));
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")));
ShardedJedisPool pool = new ShardedJedisPool(config, shards);
ShardedJedisPool pool = new ShardedJedisPool(config, shards);
ShardedJedis jedis = pool.getResource();
try {
jedis.set("hello", "jedis");
} finally {
jedis.close();
}
ShardedJedis jedis = pool.getResource();
try {
jedis.set("hello", "jedis");
} finally {
jedis.close();
}
ShardedJedis jedis2 = pool.getResource();
try {
assertEquals(jedis, jedis2);
} finally {
jedis2.close();
}
ShardedJedis jedis2 = pool.getResource();
try {
assertEquals(jedis, jedis2);
} finally {
jedis2.close();
}
}
}

View File

@@ -18,278 +18,278 @@ 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.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);
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.getHost(),
redis1.getPort());
si.setPassword("foobared");
shards.add(si);
si = new JedisShardInfo(redis2.getHost(), redis2.getPort());
si.setPassword("foobared");
shards.add(si);
ShardedJedis jedis = new ShardedJedis(shards);
jedis.set("a", "bar");
JedisShardInfo s1 = jedis.getShardInfo("a");
jedis.set("b", "bar1");
JedisShardInfo s2 = jedis.getShardInfo("b");
jedis.disconnect();
List<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.getHost(),
redis1.getPort());
si.setPassword("foobared");
shards.add(si);
si = new JedisShardInfo(redis2.getHost(), redis2.getPort());
si.setPassword("foobared");
shards.add(si);
ShardedJedis jedis = new ShardedJedis(shards, Hashing.MURMUR_HASH);
jedis.set("a", "bar");
JedisShardInfo s1 = jedis.getShardInfo("a");
jedis.set("b", "bar1");
JedisShardInfo s2 = jedis.getShardInfo("b");
jedis.disconnect();
List<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.getHost(), redis1.getPort()));
shards.add(new JedisShardInfo(redis2.getHost(), redis2.getPort()));
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 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());
}
}
@Test
public void checkCloseable() {
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");
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 jedisShard = new ShardedJedis(shards);
try {
jedisShard.set("shard_closeable", "true");
} finally {
jedisShard.close();
}
ShardedJedis jedisShard = new ShardedJedis(shards);
try {
jedisShard.set("shard_closeable", "true");
} finally {
jedisShard.close();
}
for (Jedis jedis : jedisShard.getAllShards()) {
assertTrue(!jedis.isConnected());
}
for (Jedis jedis : jedisShard.getAllShards()) {
assertTrue(!jedis.isConnected());
}
}
}

View File

@@ -8,19 +8,19 @@ public class CRC16Benchmark {
private static final int TOTAL_OPERATIONS = 100000000;
private static String[] TEST_SET = { "", "123456789", "sfger132515",
"hae9Napahngaikeethievubaibogiech", "AAAAAAAAAAAAAAAAAAAAAA",
"Hello, World!" };
"hae9Napahngaikeethievubaibogiech", "AAAAAAAAAAAAAAAAAAAAAA",
"Hello, World!" };
public static void main(String[] args) {
long begin = Calendar.getInstance().getTimeInMillis();
long begin = Calendar.getInstance().getTimeInMillis();
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
JedisClusterCRC16.getSlot(TEST_SET[n % TEST_SET.length]);
}
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
JedisClusterCRC16.getSlot(TEST_SET[n % TEST_SET.length]);
}
long elapsed = Calendar.getInstance().getTimeInMillis() - begin;
long elapsed = Calendar.getInstance().getTimeInMillis() - begin;
System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed) + " ops");
System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed) + " ops");
}
}

View File

@@ -13,24 +13,24 @@ public class GetSetBenchmark {
private static final int TOTAL_OPERATIONS = 100000;
public static void main(String[] args) throws UnknownHostException,
IOException {
Jedis jedis = new Jedis(hnp.getHost(), hnp.getPort());
jedis.connect();
jedis.auth("foobared");
jedis.flushAll();
IOException {
Jedis jedis = new Jedis(hnp.getHost(), hnp.getPort());
jedis.connect();
jedis.auth("foobared");
jedis.flushAll();
long begin = Calendar.getInstance().getTimeInMillis();
long begin = Calendar.getInstance().getTimeInMillis();
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

@@ -19,33 +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.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();
}
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

@@ -14,26 +14,26 @@ public class PipelinedGetSetBenchmark {
private static final int TOTAL_OPERATIONS = 200000;
public static void main(String[] args) throws UnknownHostException,
IOException {
Jedis jedis = new Jedis(hnp.getHost(), hnp.getPort());
jedis.connect();
jedis.auth("foobared");
jedis.flushAll();
IOException {
Jedis jedis = new Jedis(hnp.getHost(), hnp.getPort());
jedis.connect();
jedis.auth("foobared");
jedis.flushAll();
long begin = Calendar.getInstance().getTimeInMillis();
long begin = Calendar.getInstance().getTimeInMillis();
Pipeline p = jedis.pipelined();
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
String key = "foo" + n;
p.set(key, "bar" + n);
p.get(key);
}
p.sync();
Pipeline p = jedis.pipelined();
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
String key = "foo" + n;
p.set(key, "bar" + n);
p.get(key);
}
p.sync();
long elapsed = Calendar.getInstance().getTimeInMillis() - begin;
long elapsed = Calendar.getInstance().getTimeInMillis() - begin;
jedis.disconnect();
jedis.disconnect();
System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops");
System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops");
}
}

View File

@@ -16,49 +16,49 @@ public class PoolBenchmark {
private static final int TOTAL_OPERATIONS = 100000;
public static void main(String[] args) throws Exception {
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");
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 GenericObjectPoolConfig(),
hnp.getHost(), hnp.getPort(), 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

@@ -17,89 +17,89 @@ public class ProtocolBenchmark {
private static final int TOTAL_OPERATIONS = 500000;
public static void main(String[] args) throws Exception,
IOException {
long total = 0;
for (int at = 0; at != 10; ++at) {
long elapsed = measureInputMulti();
long ops = ((1000 * 2 * TOTAL_OPERATIONS) / TimeUnit.NANOSECONDS.toMillis(elapsed));
if (at >= 5) {
total += ops;
}
}
System.out.println((total / 5) + " avg");
IOException {
long total = 0;
for (int at = 0; at != 10; ++at) {
long elapsed = measureInputMulti();
long ops = ((1000 * 2 * TOTAL_OPERATIONS) / TimeUnit.NANOSECONDS.toMillis(elapsed));
if (at >= 5) {
total += ops;
}
}
System.out.println((total / 5) + " avg");
total = 0;
for (int at = 0; at != 10; ++at) {
long elapsed = measureInputStatus();
long ops = ((1000 * 2 * TOTAL_OPERATIONS) / TimeUnit.NANOSECONDS.toMillis(elapsed));
if (at >= 5) {
total += ops;
}
}
total = 0;
for (int at = 0; at != 10; ++at) {
long elapsed = measureInputStatus();
long ops = ((1000 * 2 * TOTAL_OPERATIONS) / TimeUnit.NANOSECONDS.toMillis(elapsed));
if (at >= 5) {
total += ops;
}
}
System.out.println((total / 5) + " avg");
System.out.println((total / 5) + " avg");
total = 0;
for (int at = 0; at != 10; ++at) {
long elapsed = measureCommand();
long ops = ((1000 * 2 * TOTAL_OPERATIONS) / TimeUnit.NANOSECONDS.toMillis(elapsed));
if (at >= 5) {
total += ops;
}
}
total = 0;
for (int at = 0; at != 10; ++at) {
long elapsed = measureCommand();
long ops = ((1000 * 2 * TOTAL_OPERATIONS) / TimeUnit.NANOSECONDS.toMillis(elapsed));
if (at >= 5) {
total += ops;
}
}
System.out.println((total / 5) + " avg");
System.out.println((total / 5) + " avg");
}
private static long measureInputMulti() throws Exception {
long duration = 0;
long duration = 0;
InputStream is = new ByteArrayInputStream(
"*4\r\n$3\r\nfoo\r\n$13\r\nbarbarbarfooz\r\n$5\r\nHello\r\n$5\r\nWorld\r\n"
.getBytes());
InputStream is = new ByteArrayInputStream(
"*4\r\n$3\r\nfoo\r\n$13\r\nbarbarbarfooz\r\n$5\r\nHello\r\n$5\r\nWorld\r\n"
.getBytes());
RedisInputStream in = new RedisInputStream(is);
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
long start = System.nanoTime();
Protocol.read(in);
duration += (System.nanoTime() - start);
in.reset();
}
RedisInputStream in = new RedisInputStream(is);
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
long start = System.nanoTime();
Protocol.read(in);
duration += (System.nanoTime() - start);
in.reset();
}
return duration;
return duration;
}
private static long measureInputStatus() throws Exception {
long duration = 0;
long duration = 0;
InputStream is = new ByteArrayInputStream(
"+OK\r\n"
.getBytes());
InputStream is = new ByteArrayInputStream(
"+OK\r\n"
.getBytes());
RedisInputStream in = new RedisInputStream(is);
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
long start = System.nanoTime();
Protocol.read(in);
duration += (System.nanoTime() - start);
in.reset();
}
RedisInputStream in = new RedisInputStream(is);
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
long start = System.nanoTime();
Protocol.read(in);
duration += (System.nanoTime() - start);
in.reset();
}
return duration;
return duration;
}
private static long measureCommand() throws Exception {
long duration = 0;
long duration = 0;
byte[] KEY = "123456789".getBytes();
byte[] VAL = "FooBar".getBytes();
byte[] KEY = "123456789".getBytes();
byte[] VAL = "FooBar".getBytes();
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
RedisOutputStream out = new RedisOutputStream(new ByteArrayOutputStream(8192));
long start = System.nanoTime();
Protocol.sendCommand(out, Protocol.Command.SET, KEY, VAL);
duration += (System.nanoTime() - start);
}
for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
RedisOutputStream out = new RedisOutputStream(new ByteArrayOutputStream(8192));
long start = System.nanoTime();
Protocol.sendCommand(out, Protocol.Command.SET, KEY, VAL);
duration += (System.nanoTime() - start);
}
return duration;
return duration;
}
}

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

@@ -30,560 +30,560 @@ 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() {
long ttl = jedis.ttl("foo");
assertEquals(-2, ttl);
long ttl = jedis.ttl("foo");
assertEquals(-2, ttl);
jedis.set("foo", "bar");
ttl = jedis.ttl("foo");
assertEquals(-1, ttl);
jedis.set("foo", "bar");
ttl = jedis.ttl("foo");
assertEquals(-1, ttl);
jedis.expire("foo", 20);
ttl = jedis.ttl("foo");
assertTrue(ttl >= 0 && ttl <= 20);
jedis.expire("foo", 20);
ttl = jedis.ttl("foo");
assertTrue(ttl >= 0 && ttl <= 20);
// Binary
long bttl = jedis.ttl(bfoo);
assertEquals(-2, bttl);
// Binary
long bttl = jedis.ttl(bfoo);
assertEquals(-2, bttl);
jedis.set(bfoo, bbar);
bttl = jedis.ttl(bfoo);
assertEquals(-1, bttl);
jedis.set(bfoo, bbar);
bttl = jedis.ttl(bfoo);
assertEquals(-1, bttl);
jedis.expire(bfoo, 20);
bttl = jedis.ttl(bfoo);
assertTrue(bttl >= 0 && bttl <= 20);
jedis.expire(bfoo, 20);
bttl = jedis.ttl(bfoo);
assertTrue(bttl >= 0 && bttl <= 20);
}
@Test
public void select() {
jedis.set("foo", "bar");
String status = jedis.select(1);
assertEquals("OK", status);
assertEquals(null, jedis.get("foo"));
status = jedis.select(0);
assertEquals("OK", status);
assertEquals("bar", jedis.get("foo"));
// Binary
jedis.set(bfoo, bbar);
String bstatus = jedis.select(1);
assertEquals("OK", bstatus);
assertEquals(null, jedis.get(bfoo));
bstatus = jedis.select(0);
assertEquals("OK", bstatus);
assertArrayEquals(bbar, jedis.get(bfoo));
jedis.set("foo", "bar");
String status = jedis.select(1);
assertEquals("OK", status);
assertEquals(null, jedis.get("foo"));
status = jedis.select(0);
assertEquals("OK", status);
assertEquals("bar", jedis.get("foo"));
// Binary
jedis.set(bfoo, bbar);
String bstatus = jedis.select(1);
assertEquals("OK", bstatus);
assertEquals(null, jedis.get(bfoo));
bstatus = jedis.select(0);
assertEquals("OK", bstatus);
assertArrayEquals(bbar, jedis.get(bfoo));
}
@Test
public void getDB() {
assertEquals(0, jedis.getDB().longValue());
jedis.select(1);
assertEquals(1, jedis.getDB().longValue());
assertEquals(0, jedis.getDB().longValue());
jedis.select(1);
assertEquals(1, jedis.getDB().longValue());
}
@Test
public void move() {
long status = jedis.move("foo", 1);
assertEquals(0, status);
long status = jedis.move("foo", 1);
assertEquals(0, status);
jedis.set("foo", "bar");
status = jedis.move("foo", 1);
assertEquals(1, status);
assertEquals(null, jedis.get("foo"));
jedis.set("foo", "bar");
status = jedis.move("foo", 1);
assertEquals(1, status);
assertEquals(null, jedis.get("foo"));
jedis.select(1);
assertEquals("bar", jedis.get("foo"));
jedis.select(1);
assertEquals("bar", jedis.get("foo"));
// Binary
jedis.select(0);
long bstatus = jedis.move(bfoo, 1);
assertEquals(0, bstatus);
// Binary
jedis.select(0);
long bstatus = jedis.move(bfoo, 1);
assertEquals(0, bstatus);
jedis.set(bfoo, bbar);
bstatus = jedis.move(bfoo, 1);
assertEquals(1, bstatus);
assertEquals(null, jedis.get(bfoo));
jedis.set(bfoo, bbar);
bstatus = jedis.move(bfoo, 1);
assertEquals(1, bstatus);
assertEquals(null, jedis.get(bfoo));
jedis.select(1);
assertArrayEquals(bbar, jedis.get(bfoo));
jedis.select(1);
assertArrayEquals(bbar, jedis.get(bfoo));
}
@Test
public void flushDB() {
jedis.set("foo", "bar");
assertEquals(1, jedis.dbSize().intValue());
jedis.set("bar", "foo");
jedis.move("bar", 1);
String status = jedis.flushDB();
assertEquals("OK", status);
assertEquals(0, jedis.dbSize().intValue());
jedis.select(1);
assertEquals(1, jedis.dbSize().intValue());
jedis.del("bar");
jedis.set("foo", "bar");
assertEquals(1, jedis.dbSize().intValue());
jedis.set("bar", "foo");
jedis.move("bar", 1);
String status = jedis.flushDB();
assertEquals("OK", status);
assertEquals(0, jedis.dbSize().intValue());
jedis.select(1);
assertEquals(1, jedis.dbSize().intValue());
jedis.del("bar");
// Binary
jedis.select(0);
jedis.set(bfoo, bbar);
assertEquals(1, jedis.dbSize().intValue());
jedis.set(bbar, bfoo);
jedis.move(bbar, 1);
String bstatus = jedis.flushDB();
assertEquals("OK", bstatus);
assertEquals(0, jedis.dbSize().intValue());
jedis.select(1);
assertEquals(1, jedis.dbSize().intValue());
// Binary
jedis.select(0);
jedis.set(bfoo, bbar);
assertEquals(1, jedis.dbSize().intValue());
jedis.set(bbar, bfoo);
jedis.move(bbar, 1);
String bstatus = jedis.flushDB();
assertEquals("OK", bstatus);
assertEquals(0, jedis.dbSize().intValue());
jedis.select(1);
assertEquals(1, jedis.dbSize().intValue());
}
@Test
public void flushAll() {
jedis.set("foo", "bar");
assertEquals(1, jedis.dbSize().intValue());
jedis.set("bar", "foo");
jedis.move("bar", 1);
String status = jedis.flushAll();
assertEquals("OK", status);
assertEquals(0, jedis.dbSize().intValue());
jedis.select(1);
assertEquals(0, jedis.dbSize().intValue());
jedis.set("foo", "bar");
assertEquals(1, jedis.dbSize().intValue());
jedis.set("bar", "foo");
jedis.move("bar", 1);
String status = jedis.flushAll();
assertEquals("OK", status);
assertEquals(0, jedis.dbSize().intValue());
jedis.select(1);
assertEquals(0, jedis.dbSize().intValue());
// Binary
jedis.select(0);
jedis.set(bfoo, bbar);
assertEquals(1, jedis.dbSize().intValue());
jedis.set(bbar, bfoo);
jedis.move(bbar, 1);
String bstatus = jedis.flushAll();
assertEquals("OK", bstatus);
assertEquals(0, jedis.dbSize().intValue());
jedis.select(1);
assertEquals(0, jedis.dbSize().intValue());
// Binary
jedis.select(0);
jedis.set(bfoo, bbar);
assertEquals(1, jedis.dbSize().intValue());
jedis.set(bbar, bfoo);
jedis.move(bbar, 1);
String bstatus = jedis.flushAll();
assertEquals("OK", bstatus);
assertEquals(0, jedis.dbSize().intValue());
jedis.select(1);
assertEquals(0, jedis.dbSize().intValue());
}
@Test
public void persist() {
jedis.setex("foo", 60 * 60, "bar");
assertTrue(jedis.ttl("foo") > 0);
long status = jedis.persist("foo");
assertEquals(1, status);
assertEquals(-1, jedis.ttl("foo").intValue());
jedis.setex("foo", 60 * 60, "bar");
assertTrue(jedis.ttl("foo") > 0);
long status = jedis.persist("foo");
assertEquals(1, status);
assertEquals(-1, jedis.ttl("foo").intValue());
// Binary
jedis.setex(bfoo, 60 * 60, bbar);
assertTrue(jedis.ttl(bfoo) > 0);
long bstatus = jedis.persist(bfoo);
assertEquals(1, bstatus);
assertEquals(-1, jedis.ttl(bfoo).intValue());
// Binary
jedis.setex(bfoo, 60 * 60, bbar);
assertTrue(jedis.ttl(bfoo) > 0);
long bstatus = jedis.persist(bfoo);
assertEquals(1, bstatus);
assertEquals(-1, jedis.ttl(bfoo).intValue());
}
@Test
public void echo() {
String result = jedis.echo("hello world");
assertEquals("hello world", result);
String result = jedis.echo("hello world");
assertEquals("hello world", result);
// Binary
byte[] bresult = jedis.echo(SafeEncoder.encode("hello world"));
assertArrayEquals(SafeEncoder.encode("hello world"), bresult);
// Binary
byte[] bresult = jedis.echo(SafeEncoder.encode("hello world"));
assertArrayEquals(SafeEncoder.encode("hello world"), bresult);
}
@Test
public void dumpAndRestore() {
jedis.set("foo1", "bar1");
byte[] sv = jedis.dump("foo1");
jedis.restore("foo2", 0, sv);
assertTrue(jedis.exists("foo2"));
jedis.set("foo1", "bar1");
byte[] sv = jedis.dump("foo1");
jedis.restore("foo2", 0, sv);
assertTrue(jedis.exists("foo2"));
}
@Test
public void pexpire() {
long status = jedis.pexpire("foo", 10000);
assertEquals(0, status);
long status = jedis.pexpire("foo", 10000);
assertEquals(0, status);
jedis.set("foo1", "bar1");
status = jedis.pexpire("foo1", 10000);
assertEquals(1, status);
jedis.set("foo1", "bar1");
status = jedis.pexpire("foo1", 10000);
assertEquals(1, status);
jedis.set("foo2", "bar2");
status = jedis.pexpire("foo2", 200000000000L);
assertEquals(1, status);
jedis.set("foo2", "bar2");
status = jedis.pexpire("foo2", 200000000000L);
assertEquals(1, status);
long pttl = jedis.pttl("foo2");
assertTrue(pttl > 100000000000L);
long pttl = jedis.pttl("foo2");
assertTrue(pttl > 100000000000L);
}
@Test
public void pexpireAt() {
long unixTime = (System.currentTimeMillis()) + 10000;
long unixTime = (System.currentTimeMillis()) + 10000;
long status = jedis.pexpireAt("foo", unixTime);
assertEquals(0, status);
long status = jedis.pexpireAt("foo", unixTime);
assertEquals(0, status);
jedis.set("foo", "bar");
unixTime = (System.currentTimeMillis()) + 10000;
status = jedis.pexpireAt("foo", unixTime);
assertEquals(1, status);
jedis.set("foo", "bar");
unixTime = (System.currentTimeMillis()) + 10000;
status = jedis.pexpireAt("foo", unixTime);
assertEquals(1, status);
}
@Test
public void pttl() {
long pttl = jedis.pttl("foo");
assertEquals(-2, pttl);
long pttl = jedis.pttl("foo");
assertEquals(-2, pttl);
jedis.set("foo", "bar");
pttl = jedis.pttl("foo");
assertEquals(-1, pttl);
jedis.set("foo", "bar");
pttl = jedis.pttl("foo");
assertEquals(-1, pttl);
jedis.pexpire("foo", 20000);
pttl = jedis.pttl("foo");
assertTrue(pttl >= 0 && pttl <= 20000);
jedis.pexpire("foo", 20000);
pttl = jedis.pttl("foo");
assertTrue(pttl >= 0 && pttl <= 20000);
}
@Test
public void scan() {
jedis.set("b", "b");
jedis.set("a", "a");
jedis.set("b", "b");
jedis.set("a", "a");
ScanResult<String> result = jedis.scan(SCAN_POINTER_START);
ScanResult<String> result = jedis.scan(SCAN_POINTER_START);
assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty());
assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty());
// binary
ScanResult<byte[]> bResult = jedis.scan(SCAN_POINTER_START_BINARY);
// binary
ScanResult<byte[]> bResult = jedis.scan(SCAN_POINTER_START_BINARY);
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty());
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty());
}
@Test
public void scanMatch() {
ScanParams params = new ScanParams();
params.match("a*");
ScanParams params = new ScanParams();
params.match("a*");
jedis.set("b", "b");
jedis.set("a", "a");
jedis.set("aa", "aa");
ScanResult<String> result = jedis.scan(SCAN_POINTER_START, params);
jedis.set("b", "b");
jedis.set("a", "a");
jedis.set("aa", "aa");
ScanResult<String> result = jedis.scan(SCAN_POINTER_START, params);
assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty());
assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty());
// binary
params = new ScanParams();
params.match(bfoostar);
// binary
params = new ScanParams();
params.match(bfoostar);
jedis.set(bfoo1, bbar);
jedis.set(bfoo2, bbar);
jedis.set(bfoo3, bbar);
jedis.set(bfoo1, bbar);
jedis.set(bfoo2, bbar);
jedis.set(bfoo3, bbar);
ScanResult<byte[]> bResult = jedis.scan(SCAN_POINTER_START_BINARY,
params);
ScanResult<byte[]> bResult = jedis.scan(SCAN_POINTER_START_BINARY,
params);
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty());
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty());
}
@Test
public void scanCount() {
ScanParams params = new ScanParams();
params.count(2);
ScanParams params = new ScanParams();
params.count(2);
for (int i = 0; i < 10; i++) {
jedis.set("a" + i, "a" + i);
}
for (int i = 0; i < 10; i++) {
jedis.set("a" + i, "a" + i);
}
ScanResult<String> result = jedis.scan(SCAN_POINTER_START, params);
ScanResult<String> result = jedis.scan(SCAN_POINTER_START, params);
assertFalse(result.getResult().isEmpty());
assertFalse(result.getResult().isEmpty());
// binary
params = new ScanParams();
params.count(2);
// binary
params = new ScanParams();
params.count(2);
jedis.set(bfoo1, bbar);
jedis.set(bfoo2, bbar);
jedis.set(bfoo3, bbar);
jedis.set(bfoo1, bbar);
jedis.set(bfoo2, bbar);
jedis.set(bfoo3, bbar);
ScanResult<byte[]> bResult = jedis.scan(SCAN_POINTER_START_BINARY,
params);
ScanResult<byte[]> bResult = jedis.scan(SCAN_POINTER_START_BINARY,
params);
assertFalse(bResult.getResult().isEmpty());
assertFalse(bResult.getResult().isEmpty());
}
}

View File

@@ -23,260 +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

@@ -9,189 +9,189 @@ import redis.clients.jedis.Protocol;
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 bitpos() {
String foo = "foo";
String foo = "foo";
jedis.set(foo, String.valueOf(0));
jedis.set(foo, String.valueOf(0));
jedis.setbit(foo, 3, true);
jedis.setbit(foo, 7, true);
jedis.setbit(foo, 13, true);
jedis.setbit(foo, 39, true);
jedis.setbit(foo, 3, true);
jedis.setbit(foo, 7, true);
jedis.setbit(foo, 13, true);
jedis.setbit(foo, 39, true);
/*
* byte: 0 1 2 3 4 bit: 00010001 / 00000100 / 00000000 / 00000000 /
* 00000001
*/
long offset = jedis.bitpos(foo, true);
assertEquals(2, offset);
offset = jedis.bitpos(foo, false);
assertEquals(0, offset);
/*
* byte: 0 1 2 3 4 bit: 00010001 / 00000100 / 00000000 / 00000000 /
* 00000001
*/
long offset = jedis.bitpos(foo, true);
assertEquals(2, offset);
offset = jedis.bitpos(foo, false);
assertEquals(0, offset);
offset = jedis.bitpos(foo, true, new BitPosParams(1));
assertEquals(13, offset);
offset = jedis.bitpos(foo, false, new BitPosParams(1));
assertEquals(8, offset);
offset = jedis.bitpos(foo, true, new BitPosParams(1));
assertEquals(13, offset);
offset = jedis.bitpos(foo, false, new BitPosParams(1));
assertEquals(8, offset);
offset = jedis.bitpos(foo, true, new BitPosParams(2, 3));
assertEquals(-1, offset);
offset = jedis.bitpos(foo, false, new BitPosParams(2, 3));
assertEquals(16, offset);
offset = jedis.bitpos(foo, true, new BitPosParams(2, 3));
assertEquals(-1, offset);
offset = jedis.bitpos(foo, false, new BitPosParams(2, 3));
assertEquals(16, offset);
offset = jedis.bitpos(foo, true, new BitPosParams(3, 4));
assertEquals(39, offset);
offset = jedis.bitpos(foo, true, new BitPosParams(3, 4));
assertEquals(39, offset);
}
@Test
public void bitposBinary() {
// binary
byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 };
// binary
byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 };
jedis.set(bfoo, Protocol.toByteArray(0));
jedis.set(bfoo, Protocol.toByteArray(0));
jedis.setbit(bfoo, 3, true);
jedis.setbit(bfoo, 7, true);
jedis.setbit(bfoo, 13, true);
jedis.setbit(bfoo, 39, true);
jedis.setbit(bfoo, 3, true);
jedis.setbit(bfoo, 7, true);
jedis.setbit(bfoo, 13, true);
jedis.setbit(bfoo, 39, true);
/*
* byte: 0 1 2 3 4 bit: 00010001 / 00000100 / 00000000 / 00000000 /
* 00000001
*/
long offset = jedis.bitpos(bfoo, true);
assertEquals(2, offset);
offset = jedis.bitpos(bfoo, false);
assertEquals(0, offset);
/*
* byte: 0 1 2 3 4 bit: 00010001 / 00000100 / 00000000 / 00000000 /
* 00000001
*/
long offset = jedis.bitpos(bfoo, true);
assertEquals(2, offset);
offset = jedis.bitpos(bfoo, false);
assertEquals(0, offset);
offset = jedis.bitpos(bfoo, true, new BitPosParams(1));
assertEquals(13, offset);
offset = jedis.bitpos(bfoo, false, new BitPosParams(1));
assertEquals(8, offset);
offset = jedis.bitpos(bfoo, true, new BitPosParams(1));
assertEquals(13, offset);
offset = jedis.bitpos(bfoo, false, new BitPosParams(1));
assertEquals(8, offset);
offset = jedis.bitpos(bfoo, true, new BitPosParams(2, 3));
assertEquals(-1, offset);
offset = jedis.bitpos(bfoo, false, new BitPosParams(2, 3));
assertEquals(16, offset);
offset = jedis.bitpos(bfoo, true, new BitPosParams(2, 3));
assertEquals(-1, offset);
offset = jedis.bitpos(bfoo, false, new BitPosParams(2, 3));
assertEquals(16, offset);
offset = jedis.bitpos(bfoo, true, new BitPosParams(3, 4));
assertEquals(39, offset);
offset = jedis.bitpos(bfoo, true, new BitPosParams(3, 4));
assertEquals(39, offset);
}
@Test
public void bitposWithNoMatchingBitExist() {
String foo = "foo";
String foo = "foo";
jedis.set(foo, String.valueOf(0));
for (int idx = 0; idx < 8; idx++) {
jedis.setbit(foo, idx, true);
}
jedis.set(foo, String.valueOf(0));
for (int idx = 0; idx < 8; idx++) {
jedis.setbit(foo, idx, true);
}
/*
* byte: 0 bit: 11111111
*/
long offset = jedis.bitpos(foo, false);
// offset should be last index + 1
assertEquals(8, offset);
/*
* byte: 0 bit: 11111111
*/
long offset = jedis.bitpos(foo, false);
// offset should be last index + 1
assertEquals(8, offset);
}
@Test
public void bitposWithNoMatchingBitExistWithinRange() {
String foo = "foo";
String foo = "foo";
jedis.set(foo, String.valueOf(0));
for (int idx = 0; idx < 8 * 5; idx++) {
jedis.setbit(foo, idx, true);
}
jedis.set(foo, String.valueOf(0));
for (int idx = 0; idx < 8 * 5; idx++) {
jedis.setbit(foo, idx, true);
}
/*
* byte: 0 1 2 3 4 bit: 11111111 / 11111111 / 11111111 / 11111111 /
* 11111111
*/
long offset = jedis.bitpos(foo, false, new BitPosParams(2, 3));
// offset should be -1
assertEquals(-1, offset);
/*
* byte: 0 1 2 3 4 bit: 11111111 / 11111111 / 11111111 / 11111111 /
* 11111111
*/
long offset = jedis.bitpos(foo, false, new BitPosParams(2, 3));
// offset should be -1
assertEquals(-1, offset);
}
@Test
public void setAndgetrange() {
jedis.set("key1", "Hello World");
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");
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);
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

@@ -24,134 +24,134 @@ public class ClusterCommandsTest extends JedisTestBase {
@Before
public void setUp() throws Exception {
node1 = new Jedis(nodeInfo1.getHost(), nodeInfo1.getPort());
node1.connect();
node1.flushAll();
node1 = new Jedis(nodeInfo1.getHost(), nodeInfo1.getPort());
node1.connect();
node1.flushAll();
node2 = new Jedis(nodeInfo2.getHost(), nodeInfo2.getPort());
node2.connect();
node2.flushAll();
node2 = new Jedis(nodeInfo2.getHost(), nodeInfo2.getPort());
node2.connect();
node2.flushAll();
}
@After
public void tearDown() {
node1.disconnect();
node2.disconnect();
node1.disconnect();
node2.disconnect();
}
@AfterClass
public static void removeSlots() throws InterruptedException {
node1.clusterReset(Reset.SOFT);
node2.clusterReset(Reset.SOFT);
node1.clusterReset(Reset.SOFT);
node2.clusterReset(Reset.SOFT);
}
@Test
public void testClusterSoftReset() {
node1.clusterMeet("127.0.0.1", nodeInfo2.getPort());
assertTrue(node1.clusterNodes().split("\n").length > 1);
node1.clusterReset(Reset.SOFT);
assertEquals(1, node1.clusterNodes().split("\n").length);
node1.clusterMeet("127.0.0.1", nodeInfo2.getPort());
assertTrue(node1.clusterNodes().split("\n").length > 1);
node1.clusterReset(Reset.SOFT);
assertEquals(1, node1.clusterNodes().split("\n").length);
}
@Test
public void testClusterHardReset() {
String nodeId = JedisClusterTestUtil.getNodeId(node1.clusterNodes());
node1.clusterReset(Reset.HARD);
String newNodeId = JedisClusterTestUtil.getNodeId(node1.clusterNodes());
assertNotEquals(nodeId, newNodeId);
String nodeId = JedisClusterTestUtil.getNodeId(node1.clusterNodes());
node1.clusterReset(Reset.HARD);
String newNodeId = JedisClusterTestUtil.getNodeId(node1.clusterNodes());
assertNotEquals(nodeId, newNodeId);
}
@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);
node2.clusterAddSlots(6000);
String[] nodes = node1.clusterNodes().split("\n");
String nodeId = nodes[0].split(" ")[0];
String status = node1.clusterSetSlotImporting(6000, nodeId);
assertEquals("OK", status);
}
@Test
public void clusterNodes() {
String nodes = node1.clusterNodes();
assertTrue(nodes.split("\n").length > 0);
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);
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);
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);
node1.clusterAddSlots(900);
String status = node1.clusterDelSlots(900);
assertEquals("OK", status);
}
@Test
public void clusterInfo() {
String info = node1.clusterInfo();
assertNotNull(info);
String info = node1.clusterInfo();
assertNotNull(info);
}
@Test
public void clusterGetKeysInSlot() {
node1.clusterAddSlots(500);
List<String> keys = node1.clusterGetKeysInSlot(500, 1);
assertEquals(0, keys.size());
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);
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);
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 clusterSlots() {
// please see cluster slot output format from below commit
// @see:
// https://github.com/antirez/redis/commit/e14829de3025ffb0d3294e5e5a1553afd9f10b60
String status = node1.clusterAddSlots(3000, 3001, 3002);
assertEquals("OK", status);
status = node2.clusterAddSlots(4000, 4001, 4002);
assertEquals("OK", status);
// please see cluster slot output format from below commit
// @see:
// https://github.com/antirez/redis/commit/e14829de3025ffb0d3294e5e5a1553afd9f10b60
String status = node1.clusterAddSlots(3000, 3001, 3002);
assertEquals("OK", status);
status = node2.clusterAddSlots(4000, 4001, 4002);
assertEquals("OK", status);
List<Object> slots = node1.clusterSlots();
assertNotNull(slots);
assertTrue(slots.size() > 0);
List<Object> slots = node1.clusterSlots();
assertNotNull(slots);
assertTrue(slots.size() > 0);
for (Object slotInfoObj : slots) {
List<Object> slotInfo = (List<Object>) slotInfoObj;
assertNotNull(slots);
assertTrue(slots.size() >= 2);
for (Object slotInfoObj : slots) {
List<Object> slotInfo = (List<Object>) slotInfoObj;
assertNotNull(slots);
assertTrue(slots.size() >= 2);
assertTrue(slotInfo.get(0) instanceof Long);
assertTrue(slotInfo.get(1) instanceof Long);
assertTrue(slotInfo.get(0) instanceof Long);
assertTrue(slotInfo.get(1) instanceof Long);
if (slots.size() > 2) {
// assigned slots
assertTrue(slotInfo.get(2) instanceof List);
}
}
if (slots.size() > 2) {
// assigned slots
assertTrue(slotInfo.get(2) instanceof List);
}
}
}
}

View File

@@ -11,12 +11,12 @@ public class ConnectionHandlingCommandsTest extends JedisCommandTestBase {
@Test
public void quit() {
assertEquals("OK", jedis.quit());
assertEquals("OK", jedis.quit());
}
@Test
public void binary_quit() {
BinaryJedis bj = new BinaryJedis(hnp.getHost());
assertEquals("OK", bj.quit());
BinaryJedis bj = new BinaryJedis(hnp.getHost());
assertEquals("OK", bj.quit());
}
}

View File

@@ -12,115 +12,115 @@ import redis.clients.jedis.exceptions.JedisDataException;
public class ControlCommandsTest extends JedisCommandTestBase {
@Test
public void save() {
try {
String status = jedis.save();
assertEquals("OK", status);
} catch (JedisDataException e) {
assertTrue("ERR Background save already in progress"
.equalsIgnoreCase(e.getMessage()));
}
try {
String status = jedis.save();
assertEquals("OK", status);
} catch (JedisDataException e) {
assertTrue("ERR Background save already in progress"
.equalsIgnoreCase(e.getMessage()));
}
}
@Test
public void bgsave() {
try {
String status = jedis.bgsave();
assertEquals("Background saving started", status);
} catch (JedisDataException e) {
assertTrue("ERR Background save already in progress"
.equalsIgnoreCase(e.getMessage()));
}
try {
String status = jedis.bgsave();
assertEquals("Background saving started", status);
} catch (JedisDataException e) {
assertTrue("ERR Background save already in progress"
.equalsIgnoreCase(e.getMessage()));
}
}
@Test
public void bgrewriteaof() {
String scheduled = "Background append only file rewriting scheduled";
String started = "Background append only file rewriting started";
String scheduled = "Background append only file rewriting scheduled";
String started = "Background append only file rewriting started";
String status = jedis.bgrewriteaof();
String status = jedis.bgrewriteaof();
boolean ok = status.equals(scheduled) || status.equals(started);
assertTrue(ok);
boolean ok = status.equals(scheduled) || status.equals(started);
assertTrue(ok);
}
@Test
public void lastsave() throws InterruptedException {
long saved = jedis.lastsave();
assertTrue(saved > 0);
long saved = jedis.lastsave();
assertTrue(saved > 0);
}
@Test
public void info() {
String info = jedis.info();
assertNotNull(info);
info = jedis.info("server");
assertNotNull(info);
String info = jedis.info();
assertNotNull(info);
info = jedis.info("server");
assertNotNull(info);
}
@Test
public void monitor() {
new Thread(new Runnable() {
public void run() {
try {
// sleep 100ms to make sure that monitor thread runs first
Thread.sleep(100);
} catch (InterruptedException e) {
}
Jedis j = new Jedis("localhost");
j.auth("foobared");
for (int i = 0; i < 5; i++) {
j.incr("foobared");
}
j.disconnect();
}
}).start();
new Thread(new Runnable() {
public void run() {
try {
// sleep 100ms to make sure that monitor thread runs first
Thread.sleep(100);
} catch (InterruptedException e) {
}
Jedis j = new Jedis("localhost");
j.auth("foobared");
for (int i = 0; i < 5; i++) {
j.incr("foobared");
}
j.disconnect();
}
}).start();
jedis.monitor(new JedisMonitor() {
private int count = 0;
jedis.monitor(new JedisMonitor() {
private int count = 0;
public void onCommand(String command) {
if (command.contains("INCR")) {
count++;
}
if (count == 5) {
client.disconnect();
}
}
});
public void onCommand(String command) {
if (command.contains("INCR")) {
count++;
}
if (count == 5) {
client.disconnect();
}
}
});
}
@Test
public void configGet() {
List<String> info = jedis.configGet("m*");
assertNotNull(info);
List<String> info = jedis.configGet("m*");
assertNotNull(info);
}
@Test
public void configSet() {
List<String> info = jedis.configGet("maxmemory");
String memory = info.get(1);
String status = jedis.configSet("maxmemory", "200");
assertEquals("OK", status);
jedis.configSet("maxmemory", memory);
List<String> info = jedis.configGet("maxmemory");
String memory = info.get(1);
String status = jedis.configSet("maxmemory", "200");
assertEquals("OK", status);
jedis.configSet("maxmemory", memory);
}
@Test
public void sync() {
jedis.sync();
jedis.sync();
}
@Test
public void debug() {
jedis.set("foo", "bar");
String resp = jedis.debug(DebugParams.OBJECT("foo"));
assertNotNull(resp);
resp = jedis.debug(DebugParams.RELOAD());
assertNotNull(resp);
jedis.set("foo", "bar");
String resp = jedis.debug(DebugParams.OBJECT("foo"));
assertNotNull(resp);
resp = jedis.debug(DebugParams.RELOAD());
assertNotNull(resp);
}
@Test
public void waitReplicas() {
Long replicas = jedis.waitReplicas(1, 100);
assertEquals(1, replicas.longValue());
Long replicas = jedis.waitReplicas(1, 100);
assertEquals(1, replicas.longValue());
}
}

View File

@@ -30,388 +30,388 @@ 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 hincrByFloat() {
Double value = jedis.hincrByFloat("foo", "bar", 1.5d);
assertEquals((Double) 1.5d, value);
value = jedis.hincrByFloat("foo", "bar", -1.5d);
assertEquals((Double) 0d, value);
value = jedis.hincrByFloat("foo", "bar", -10.7d);
assertEquals(Double.compare(-10.7d, value), 0);
Double value = jedis.hincrByFloat("foo", "bar", 1.5d);
assertEquals((Double) 1.5d, value);
value = jedis.hincrByFloat("foo", "bar", -1.5d);
assertEquals((Double) 0d, value);
value = jedis.hincrByFloat("foo", "bar", -10.7d);
assertEquals(Double.compare(-10.7d, value), 0);
// Binary
double bvalue = jedis.hincrByFloat(bfoo, bbar, 1.5d);
assertEquals(Double.compare(1.5d, bvalue), 0);
bvalue = jedis.hincrByFloat(bfoo, bbar, -1.5d);
assertEquals(Double.compare(0d, bvalue), 0);
bvalue = jedis.hincrByFloat(bfoo, bbar, -10.7d);
assertEquals(Double.compare(-10.7d, value), 0);
// Binary
double bvalue = jedis.hincrByFloat(bfoo, bbar, 1.5d);
assertEquals(Double.compare(1.5d, bvalue), 0);
bvalue = jedis.hincrByFloat(bfoo, bbar, -1.5d);
assertEquals(Double.compare(0d, bvalue), 0);
bvalue = jedis.hincrByFloat(bfoo, bbar, -10.7d);
assertEquals(Double.compare(-10.7d, value), 0);
}
@Test
public void hexists() {
Map<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 hgetAllPipeline() {
Map<byte[], byte[]> bh = new HashMap<byte[], byte[]>();
bh.put(bbar, bcar);
bh.put(bcar, bbar);
jedis.hmset(bfoo, bh);
Pipeline pipeline = jedis.pipelined();
Response<Map<byte[], byte[]>> bhashResponse = pipeline.hgetAll(bfoo);
pipeline.sync();
Map<byte[], byte[]> bhash = bhashResponse.get();
Map<byte[], byte[]> bh = new HashMap<byte[], byte[]>();
bh.put(bbar, bcar);
bh.put(bcar, bbar);
jedis.hmset(bfoo, bh);
Pipeline pipeline = jedis.pipelined();
Response<Map<byte[], byte[]>> bhashResponse = pipeline.hgetAll(bfoo);
pipeline.sync();
Map<byte[], byte[]> bhash = bhashResponse.get();
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");
jedis.hset("foo", "b", "b");
jedis.hset("foo", "a", "a");
ScanResult<Map.Entry<String, String>> result = jedis.hscan("foo",
SCAN_POINTER_START);
ScanResult<Map.Entry<String, String>> result = jedis.hscan("foo",
SCAN_POINTER_START);
assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty());
assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty());
// binary
jedis.hset(bfoo, bbar, bcar);
// binary
jedis.hset(bfoo, bbar, bcar);
ScanResult<Map.Entry<byte[], byte[]>> bResult = jedis.hscan(bfoo,
SCAN_POINTER_START_BINARY);
ScanResult<Map.Entry<byte[], byte[]>> bResult = jedis.hscan(bfoo,
SCAN_POINTER_START_BINARY);
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty());
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty());
}
@Test
public void hscanMatch() {
ScanParams params = new ScanParams();
params.match("a*");
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",
SCAN_POINTER_START, params);
jedis.hset("foo", "b", "b");
jedis.hset("foo", "a", "a");
jedis.hset("foo", "aa", "aa");
ScanResult<Map.Entry<String, String>> result = jedis.hscan("foo",
SCAN_POINTER_START, params);
assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty());
assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty());
// binary
params = new ScanParams();
params.match(bbarstar);
// binary
params = new ScanParams();
params.match(bbarstar);
jedis.hset(bfoo, bbar, bcar);
jedis.hset(bfoo, bbar1, bcar);
jedis.hset(bfoo, bbar2, bcar);
jedis.hset(bfoo, bbar3, bcar);
jedis.hset(bfoo, bbar, bcar);
jedis.hset(bfoo, bbar1, bcar);
jedis.hset(bfoo, bbar2, bcar);
jedis.hset(bfoo, bbar3, bcar);
ScanResult<Map.Entry<byte[], byte[]>> bResult = jedis.hscan(bfoo,
SCAN_POINTER_START_BINARY, params);
ScanResult<Map.Entry<byte[], byte[]>> bResult = jedis.hscan(bfoo,
SCAN_POINTER_START_BINARY, params);
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty());
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty());
}
@Test
public void hscanCount() {
ScanParams params = new ScanParams();
params.count(2);
ScanParams params = new ScanParams();
params.count(2);
for (int i = 0; i < 10; i++) {
jedis.hset("foo", "a" + i, "a" + i);
}
for (int i = 0; i < 10; i++) {
jedis.hset("foo", "a" + i, "a" + i);
}
ScanResult<Map.Entry<String, String>> result = jedis.hscan("foo",
SCAN_POINTER_START, params);
ScanResult<Map.Entry<String, String>> result = jedis.hscan("foo",
SCAN_POINTER_START, params);
assertFalse(result.getResult().isEmpty());
assertFalse(result.getResult().isEmpty());
// binary
params = new ScanParams();
params.count(2);
// binary
params = new ScanParams();
params.count(2);
jedis.hset(bfoo, bbar, bcar);
jedis.hset(bfoo, bbar1, bcar);
jedis.hset(bfoo, bbar2, bcar);
jedis.hset(bfoo, bbar3, bcar);
jedis.hset(bfoo, bbar, bcar);
jedis.hset(bfoo, bbar1, bcar);
jedis.hset(bfoo, bbar2, bcar);
jedis.hset(bfoo, bbar3, bcar);
ScanResult<Map.Entry<byte[], byte[]>> bResult = jedis.hscan(bfoo,
SCAN_POINTER_START_BINARY, params);
ScanResult<Map.Entry<byte[], byte[]>> bResult = jedis.hscan(bfoo,
SCAN_POINTER_START_BINARY, params);
assertFalse(bResult.getResult().isEmpty());
assertFalse(bResult.getResult().isEmpty());
}
}

View File

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

View File

@@ -20,77 +20,77 @@ public abstract class JedisCommandTestBase extends JedisTestBase {
protected Jedis jedis;
public JedisCommandTestBase() {
super();
super();
}
@Before
public void setUp() throws Exception {
jedis = new Jedis(hnp.getHost(), hnp.getPort(), 500);
jedis.connect();
jedis.auth("foobared");
jedis.configSet("timeout", "300");
jedis.flushAll();
jedis = new Jedis(hnp.getHost(), hnp.getPort(), 500);
jedis.connect();
jedis.auth("foobared");
jedis.configSet("timeout", "300");
jedis.flushAll();
}
@After
public void tearDown() {
jedis.disconnect();
jedis.disconnect();
}
protected Jedis createJedis() {
Jedis j = new Jedis(hnp.getHost(), hnp.getPort());
j.connect();
j.auth("foobared");
j.flushAll();
return j;
Jedis j = new Jedis(hnp.getHost(), hnp.getPort());
j.connect();
j.auth("foobared");
j.flushAll();
return j;
}
protected void assertEquals(List<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,559 +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);
jedis.lpush("foo", "bar");
result = jedis.blpop(1, "foo");
jedis.lpush("foo", "bar");
result = jedis.blpop(1, "foo");
assertNotNull(result);
assertEquals(2, result.size());
assertEquals("foo", result.get(0));
assertEquals("bar", result.get(1));
assertNotNull(result);
assertEquals(2, result.size());
assertEquals("foo", result.get(0));
assertEquals("bar", result.get(1));
// Binary
jedis.lpush(bfoo, bbar);
List<byte[]> bresult = jedis.blpop(1, bfoo);
// Binary
jedis.lpush(bfoo, bbar);
List<byte[]> 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);
jedis.lpush("foo", "bar");
result = jedis.brpop(1, "foo");
assertNotNull(result);
assertEquals(2, result.size());
assertEquals("foo", result.get(0));
assertEquals("bar", result.get(1));
jedis.lpush("foo", "bar");
result = jedis.brpop(1, "foo");
assertNotNull(result);
assertEquals(2, result.size());
assertEquals("foo", result.get(0));
assertEquals("bar", result.get(1));
// Binary
// Binary
jedis.lpush(bfoo, bbar);
List<byte[]> 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(100);
Jedis j = createJedis();
j.lpush("foo", "a");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
})).start();
(new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(100);
Jedis j = createJedis();
j.lpush("foo", "a");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
})).start();
String element = jedis.brpoplpush("foo", "bar", 0);
String element = jedis.brpoplpush("foo", "bar", 0);
assertEquals("a", element);
assertEquals(1, jedis.llen("bar").longValue());
assertEquals("a", jedis.lrange("bar", 0, -1).get(0));
assertEquals("a", element);
assertEquals(1, jedis.llen("bar").longValue());
assertEquals("a", jedis.lrange("bar", 0, -1).get(0));
(new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(100);
Jedis j = createJedis();
j.lpush("foo", "a");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
})).start();
(new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(100);
Jedis j = createJedis();
j.lpush("foo", "a");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
})).start();
byte[] brpoplpush = jedis.brpoplpush("foo".getBytes(),
"bar".getBytes(), 0);
byte[] brpoplpush = jedis.brpoplpush("foo".getBytes(),
"bar".getBytes(), 0);
assertTrue(Arrays.equals("a".getBytes(), brpoplpush));
assertEquals(1, jedis.llen("bar").longValue());
assertEquals("a", jedis.lrange("bar", 0, -1).get(0));
assertTrue(Arrays.equals("a".getBytes(), brpoplpush));
assertEquals(1, jedis.llen("bar").longValue());
assertEquals("a", jedis.lrange("bar", 0, -1).get(0));
}
}

View File

@@ -11,36 +11,36 @@ public class ObjectCommandsTest extends JedisCommandTestBase {
@Test
public void objectRefcount() {
jedis.lpush(key, "hello world");
Long refcount = jedis.objectRefcount(key);
assertEquals(new Long(1), refcount);
jedis.lpush(key, "hello world");
Long refcount = jedis.objectRefcount(key);
assertEquals(new Long(1), refcount);
// Binary
refcount = jedis.objectRefcount(binaryKey);
assertEquals(new Long(1), refcount);
// Binary
refcount = jedis.objectRefcount(binaryKey);
assertEquals(new Long(1), refcount);
}
@Test
public void objectEncoding() {
jedis.lpush(key, "hello world");
String encoding = jedis.objectEncoding(key);
assertEquals("ziplist", encoding);
jedis.lpush(key, "hello world");
String encoding = jedis.objectEncoding(key);
assertEquals("ziplist", encoding);
// Binary
encoding = SafeEncoder.encode(jedis.objectEncoding(binaryKey));
assertEquals("ziplist", encoding);
// Binary
encoding = SafeEncoder.encode(jedis.objectEncoding(binaryKey));
assertEquals("ziplist", encoding);
}
@Test
public void objectIdletime() throws InterruptedException {
jedis.lpush(key, "hello world");
jedis.lpush(key, "hello world");
Long time = jedis.objectIdletime(key);
assertEquals(new Long(0), time);
Long time = jedis.objectIdletime(key);
assertEquals(new Long(0), time);
// Binary
time = jedis.objectIdletime(binaryKey);
assertEquals(new Long(0), time);
// Binary
time = jedis.objectIdletime(binaryKey);
assertEquals(new Long(0), time);
}
}

View File

@@ -16,374 +16,374 @@ 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();
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 {
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);
// now that I'm subscribed... publish
publishOne("foo", "exit");
}
// now that I'm subscribed... publish
publishOne("foo", "exit");
}
public void onUnsubscribe(String channel, int subscribedChannels) {
assertEquals("foo", channel);
assertEquals(0, subscribedChannels);
}
}, "foo");
public void onUnsubscribe(String channel, int subscribedChannels) {
assertEquals("foo", channel);
assertEquals(0, subscribedChannels);
}
}, "foo");
}
@Test
public void pubSubChannels() {
final List<String> expectedActiveChannels = Arrays.asList("testchan1",
"testchan2", "testchan3");
jedis.subscribe(new JedisPubSub() {
private int count = 0;
final List<String> expectedActiveChannels = Arrays.asList("testchan1",
"testchan2", "testchan3");
jedis.subscribe(new JedisPubSub() {
private int count = 0;
@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();
}
}
}, "testchan1", "testchan2", "testchan3");
@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();
}
}
}, "testchan1", "testchan2", "testchan3");
}
@Test
public void pubSubNumPat() {
jedis.psubscribe(new JedisPubSub() {
private int count = 0;
jedis.psubscribe(new JedisPubSub() {
private int count = 0;
@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 onPSubscribe(String pattern, int subscribedChannels) {
count++;
if (count == 3) {
Jedis otherJedis = createJedis();
Long numPatterns = otherJedis.pubsubNumPat();
assertEquals(new Long(2l), numPatterns);
punsubscribe();
}
}
}, "test*", "test*", "chan*");
}, "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;
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 onSubscribe(String channel, int subscribedChannels) {
count++;
if (count == 2) {
Jedis otherJedis = createJedis();
Map<String, String> numSub = otherJedis.pubsubNumSub(
"testchannel1", "testchannel2");
assertEquals(expectedNumSub, numSub);
unsubscribe();
}
}
}, "testchannel1", "testchannel2");
@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();
}
}
}, "testchannel1", "testchannel2");
}
@Test
public void subscribeMany() throws UnknownHostException, IOException,
InterruptedException {
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) {
publishOne(channel, "exit");
}
public void onSubscribe(String channel, int subscribedChannels) {
publishOne(channel, "exit");
}
}, "foo", "bar");
}, "foo", "bar");
}
@Test
public void psubscribe() throws UnknownHostException, IOException,
InterruptedException {
jedis.psubscribe(new JedisPubSub() {
public void onPSubscribe(String pattern, int subscribedChannels) {
assertEquals("foo.*", pattern);
assertEquals(1, subscribedChannels);
publishOne("foo.bar", "exit");
InterruptedException {
jedis.psubscribe(new JedisPubSub() {
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 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.*");
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 {
jedis.psubscribe(new JedisPubSub() {
public void onPSubscribe(String pattern, int subscribedChannels) {
publishOne(pattern.replace("*", "123"), "exit");
}
InterruptedException {
jedis.psubscribe(new JedisPubSub() {
public void onPSubscribe(String pattern, int subscribedChannels) {
publishOne(pattern.replace("*", "123"), "exit");
}
public void onPMessage(String pattern, String channel,
String message) {
punsubscribe(pattern);
}
}, "foo.*", "bar.*");
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) {
publishOne(channel, "exit");
if (!channel.equals("bar")) {
this.subscribe("bar");
this.psubscribe("bar.*");
}
}
public void onSubscribe(String channel, int subscribedChannels) {
publishOne(channel, "exit");
if (!channel.equals("bar")) {
this.subscribe("bar");
this.psubscribe("bar.*");
}
}
public void onPSubscribe(String pattern, int subscribedChannels) {
publishOne(pattern.replace("*", "123"), "exit");
}
public void onPSubscribe(String pattern, int subscribedChannels) {
publishOne(pattern.replace("*", "123"), "exit");
}
public void onPMessage(String pattern, String channel,
String message) {
punsubscribe(pattern);
}
};
public void onPMessage(String pattern, String channel,
String message) {
punsubscribe(pattern);
}
};
jedis.subscribe(pubsub, "foo");
jedis.subscribe(pubsub, "foo");
}
@Test
public void binarySubscribe() throws UnknownHostException, IOException,
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();
}
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);
publishOne(SafeEncoder.encode(channel), "exit");
}
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);
}
}, SafeEncoder.encode("foo"));
public void onUnsubscribe(byte[] channel, int subscribedChannels) {
assertTrue(Arrays.equals(SafeEncoder.encode("foo"), channel));
assertEquals(0, subscribedChannels);
}
}, SafeEncoder.encode("foo"));
}
@Test
public void binarySubscribeMany() throws UnknownHostException, IOException,
InterruptedException {
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) {
publishOne(SafeEncoder.encode(channel), "exit");
}
}, SafeEncoder.encode("foo"), SafeEncoder.encode("bar"));
public void onSubscribe(byte[] channel, int subscribedChannels) {
publishOne(SafeEncoder.encode(channel), "exit");
}
}, SafeEncoder.encode("foo"), SafeEncoder.encode("bar"));
}
@Test
public void binaryPsubscribe() throws UnknownHostException, IOException,
InterruptedException {
jedis.psubscribe(new BinaryJedisPubSub() {
public void onPSubscribe(byte[] pattern, int subscribedChannels) {
assertTrue(Arrays.equals(SafeEncoder.encode("foo.*"), pattern));
assertEquals(1, subscribedChannels);
publishOne(SafeEncoder.encode(pattern).replace("*", "bar"),
"exit");
}
InterruptedException {
jedis.psubscribe(new BinaryJedisPubSub() {
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.*"));
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 {
jedis.psubscribe(new BinaryJedisPubSub() {
public void onPSubscribe(byte[] pattern, int subscribedChannels) {
publishOne(SafeEncoder.encode(pattern).replace("*", "123"),
"exit");
}
IOException, InterruptedException {
jedis.psubscribe(new BinaryJedisPubSub() {
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);
}
}, SafeEncoder.encode("foo.*"), SafeEncoder.encode("bar.*"));
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) {
publishOne(SafeEncoder.encode(channel), "exit");
public void onSubscribe(byte[] channel, int subscribedChannels) {
publishOne(SafeEncoder.encode(channel), "exit");
if (!SafeEncoder.encode(channel).equals("bar")) {
this.subscribe(SafeEncoder.encode("bar"));
this.psubscribe(SafeEncoder.encode("bar.*"));
}
}
if (!SafeEncoder.encode(channel).equals("bar")) {
this.subscribe(SafeEncoder.encode("bar"));
this.psubscribe(SafeEncoder.encode("bar.*"));
}
}
public void onPSubscribe(byte[] pattern, int subscribedChannels) {
publishOne(SafeEncoder.encode(pattern).replace("*", "123"),
"exit");
}
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 onPMessage(byte[] pattern, byte[] channel,
byte[] message) {
punsubscribe(pattern);
}
};
jedis.subscribe(pubsub, SafeEncoder.encode("foo"));
jedis.subscribe(pubsub, SafeEncoder.encode("foo"));
}
@Test(expected = JedisConnectionException.class)
public void unsubscribeWhenNotSusbscribed() throws InterruptedException {
JedisPubSub pubsub = new JedisPubSub() {};
pubsub.unsubscribe();
JedisPubSub pubsub = new JedisPubSub() {};
pubsub.unsubscribe();
}
@Test(expected = JedisConnectionException.class)
public void handleClientOutputBufferLimitForSubscribeTooSlow()
throws InterruptedException {
final Jedis j = createJedis();
final AtomicBoolean exit = new AtomicBoolean(false);
throws InterruptedException {
final Jedis j = createJedis();
final AtomicBoolean exit = new AtomicBoolean(false);
final Thread t = new Thread(new Runnable() {
public void run() {
try {
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 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);
// 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);
}
// 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) {
}
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());
}
}
}, "foo");
} finally {
// exit the publisher thread. if exception is thrown, thread might
// still keep publishing things.
exit.set(true);
if (t.isAlive()) {
t.join();
}
}
fail(e.getMessage());
}
}
}, "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));
StringBuffer sb = new StringBuffer();
for (int i = 0; i < size; i++)
sb.append((char) ('a' + i % 26));
return sb.toString();
return sb.toString();
}
}

View File

@@ -18,193 +18,193 @@ public class ScriptingCommandsTest extends JedisCommandTestBase {
@SuppressWarnings("unchecked")
@Test
public void evalMultiBulk() {
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");
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");
List<String> args = new ArrayList<String>();
args.add("first");
args.add("second");
args.add("third");
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);
List<String> response = (List<String>) jedis.eval(script, keys, args);
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));
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());
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());
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");
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)));
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
public void evalBulk() {
String script = "return KEYS[1]";
List<String> keys = new ArrayList<String>();
keys.add("key1");
String script = "return KEYS[1]";
List<String> keys = new ArrayList<String>();
keys.add("key1");
List<String> args = new ArrayList<String>();
args.add("first");
List<String> args = new ArrayList<String>();
args.add("first");
String response = (String) jedis.eval(script, keys, args);
String response = (String) jedis.eval(script, keys, args);
assertEquals("key1", response);
assertEquals("key1", response);
}
@Test
public void evalInt() {
String script = "return 2";
List<String> keys = new ArrayList<String>();
keys.add("key1");
String script = "return 2";
List<String> keys = new ArrayList<String>();
keys.add("key1");
Long response = (Long) jedis
.eval(script, keys, new ArrayList<String>());
Long response = (Long) jedis
.eval(script, keys, new ArrayList<String>());
assertEquals(new Long(2), response);
assertEquals(new Long(2), response);
}
@Test
public void evalNestedLists() {
String script = "return { {KEYS[1]} , {2} }";
List<?> results = (List<?>) jedis.eval(script, 1, "key1");
String script = "return { {KEYS[1]} , {2} }";
List<?> results = (List<?>) jedis.eval(script, 1, "key1");
assertThat((List<String>) results.get(0), listWithItem("key1"));
assertThat((List<Long>) results.get(1), listWithItem(2L));
assertThat((List<String>) results.get(0), listWithItem("key1"));
assertThat((List<Long>) results.get(1), listWithItem(2L));
}
@Test
public void evalNoArgs() {
String script = "return KEYS[1]";
List<String> keys = new ArrayList<String>();
keys.add("key1");
String response = (String) jedis.eval(script, keys,
new ArrayList<String>());
String script = "return KEYS[1]";
List<String> keys = new ArrayList<String>();
keys.add("key1");
String response = (String) jedis.eval(script, keys,
new ArrayList<String>());
assertEquals("key1", response);
assertEquals("key1", response);
}
@Test
public void evalsha() {
jedis.set("foo", "bar");
jedis.eval("return redis.call('get','foo')");
String result = (String) jedis
.evalsha("6b1bf486c81ceb7edf3c093f4c48582e38c0e791");
jedis.set("foo", "bar");
jedis.eval("return redis.call('get','foo')");
String result = (String) jedis
.evalsha("6b1bf486c81ceb7edf3c093f4c48582e38c0e791");
assertEquals("bar", result);
assertEquals("bar", result);
}
@Test(expected = JedisDataException.class)
public void evalshaShaNotFound() {
jedis.evalsha("ffffffffffffffffffffffffffffffffffffffff");
jedis.evalsha("ffffffffffffffffffffffffffffffffffffffff");
}
@Test
public void scriptFlush() {
jedis.set("foo", "bar");
jedis.eval("return redis.call('get','foo')");
jedis.scriptFlush();
assertFalse(jedis
.scriptExists("6b1bf486c81ceb7edf3c093f4c48582e38c0e791"));
jedis.set("foo", "bar");
jedis.eval("return redis.call('get','foo')");
jedis.scriptFlush();
assertFalse(jedis
.scriptExists("6b1bf486c81ceb7edf3c093f4c48582e38c0e791"));
}
@Test
public void scriptExists() {
jedis.scriptLoad("return redis.call('get','foo')");
List<Boolean> exists = jedis.scriptExists(
"ffffffffffffffffffffffffffffffffffffffff",
"6b1bf486c81ceb7edf3c093f4c48582e38c0e791");
assertFalse(exists.get(0));
assertTrue(exists.get(1));
jedis.scriptLoad("return redis.call('get','foo')");
List<Boolean> exists = jedis.scriptExists(
"ffffffffffffffffffffffffffffffffffffffff",
"6b1bf486c81ceb7edf3c093f4c48582e38c0e791");
assertFalse(exists.get(0));
assertTrue(exists.get(1));
}
@Test
public void scriptExistsBinary() {
jedis.scriptLoad(SafeEncoder.encode("return redis.call('get','foo')"));
List<Long> exists = jedis.scriptExists(
SafeEncoder.encode("ffffffffffffffffffffffffffffffffffffffff"),
SafeEncoder.encode("6b1bf486c81ceb7edf3c093f4c48582e38c0e791"));
assertEquals(new Long(0), exists.get(0));
assertEquals(new Long(1), exists.get(1));
jedis.scriptLoad(SafeEncoder.encode("return redis.call('get','foo')"));
List<Long> exists = jedis.scriptExists(
SafeEncoder.encode("ffffffffffffffffffffffffffffffffffffffff"),
SafeEncoder.encode("6b1bf486c81ceb7edf3c093f4c48582e38c0e791"));
assertEquals(new Long(0), exists.get(0));
assertEquals(new Long(1), exists.get(1));
}
@Test
public void scriptLoad() {
jedis.scriptLoad("return redis.call('get','foo')");
assertTrue(jedis
.scriptExists("6b1bf486c81ceb7edf3c093f4c48582e38c0e791"));
jedis.scriptLoad("return redis.call('get','foo')");
assertTrue(jedis
.scriptExists("6b1bf486c81ceb7edf3c093f4c48582e38c0e791"));
}
@Test
public void scriptLoadBinary() {
jedis.scriptLoad(SafeEncoder.encode("return redis.call('get','foo')"));
List<Long> exists = jedis.scriptExists(SafeEncoder
.encode("6b1bf486c81ceb7edf3c093f4c48582e38c0e791"));
assertEquals(new Long(1), exists.get(0));
jedis.scriptLoad(SafeEncoder.encode("return redis.call('get','foo')"));
List<Long> exists = jedis.scriptExists(SafeEncoder
.encode("6b1bf486c81ceb7edf3c093f4c48582e38c0e791"));
assertEquals(new Long(1), exists.get(0));
}
@Test
public void scriptKill() {
try {
jedis.scriptKill();
} catch (JedisDataException e) {
assertTrue(e.getMessage().contains(
"No scripts in execution right now."));
}
try {
jedis.scriptKill();
} catch (JedisDataException e) {
assertTrue(e.getMessage().contains(
"No scripts in execution right now."));
}
}
@Test
public void scriptEvalReturnNullValues() {
String script = "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}";
List<String> results = (List<String>) jedis.eval(script, 2, "key1",
"key2", "1", "2");
assertEquals("key1", results.get(0));
assertEquals("key2", results.get(1));
assertEquals("1", results.get(2));
assertEquals("2", results.get(3));
String script = "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}";
List<String> results = (List<String>) jedis.eval(script, 2, "key1",
"key2", "1", "2");
assertEquals("key1", results.get(0));
assertEquals("key2", results.get(1));
assertEquals("1", results.get(2));
assertEquals("2", results.get(3));
}
@Test
public void scriptEvalShaReturnNullValues() {
String script = "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}";
String sha = jedis.scriptLoad(script);
List<String> results = (List<String>) jedis.evalsha(sha, 2, "key1",
"key2", "1", "2");
assertEquals("key1", results.get(0));
assertEquals("key2", results.get(1));
assertEquals("1", results.get(2));
assertEquals("2", results.get(3));
String script = "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}";
String sha = jedis.scriptLoad(script);
List<String> results = (List<String>) jedis.evalsha(sha, 2, "key1",
"key2", "1", "2");
assertEquals("key1", results.get(0));
assertEquals("key2", results.get(1));
assertEquals("1", results.get(2));
assertEquals("2", results.get(3));
}
private <T> Matcher<Iterable<? super T>> listWithItem(T expected) {
return CoreMatchers.<T> hasItem(equalTo(expected));
return CoreMatchers.<T> hasItem(equalTo(expected));
}
}

View File

@@ -29,501 +29,501 @@ 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());
assertTrue(Arrays.equals(ba, bmember) || Arrays.equals(bb, bmember));
assertEquals(2, jedis.smembers(bfoo).size());
bmember = jedis.srandmember(bbar);
assertNull(bmember);
bmember = jedis.srandmember(bbar);
assertNull(bmember);
}
@Test
public void sscan() {
jedis.sadd("foo", "a", "b");
jedis.sadd("foo", "a", "b");
ScanResult<String> result = jedis.sscan("foo", SCAN_POINTER_START);
ScanResult<String> result = jedis.sscan("foo", SCAN_POINTER_START);
assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty());
assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty());
// binary
jedis.sadd(bfoo, ba, bb);
// binary
jedis.sadd(bfoo, ba, bb);
ScanResult<byte[]> bResult = jedis.sscan(bfoo,
SCAN_POINTER_START_BINARY);
ScanResult<byte[]> bResult = jedis.sscan(bfoo,
SCAN_POINTER_START_BINARY);
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty());
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty());
}
@Test
public void sscanMatch() {
ScanParams params = new ScanParams();
params.match("a*");
ScanParams params = new ScanParams();
params.match("a*");
jedis.sadd("foo", "b", "a", "aa");
ScanResult<String> result = jedis.sscan("foo", SCAN_POINTER_START,
params);
jedis.sadd("foo", "b", "a", "aa");
ScanResult<String> result = jedis.sscan("foo", SCAN_POINTER_START,
params);
assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty());
assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty());
// binary
params = new ScanParams();
params.match(bbarstar);
// binary
params = new ScanParams();
params.match(bbarstar);
jedis.sadd(bfoo, bbar1, bbar2, bbar3);
ScanResult<byte[]> bResult = jedis.sscan(bfoo,
SCAN_POINTER_START_BINARY, params);
jedis.sadd(bfoo, bbar1, bbar2, bbar3);
ScanResult<byte[]> bResult = jedis.sscan(bfoo,
SCAN_POINTER_START_BINARY, params);
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty());
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty());
}
@Test
public void sscanCount() {
ScanParams params = new ScanParams();
params.count(2);
ScanParams params = new ScanParams();
params.count(2);
jedis.sadd("foo", "a1", "a2", "a3", "a4", "a5");
jedis.sadd("foo", "a1", "a2", "a3", "a4", "a5");
ScanResult<String> result = jedis.sscan("foo", SCAN_POINTER_START,
params);
ScanResult<String> result = jedis.sscan("foo", SCAN_POINTER_START,
params);
assertFalse(result.getResult().isEmpty());
assertFalse(result.getResult().isEmpty());
// binary
params = new ScanParams();
params.count(2);
// binary
params = new ScanParams();
params.count(2);
jedis.sadd(bfoo, bbar1, bbar2, bbar3);
ScanResult<byte[]> bResult = jedis.sscan(bfoo,
SCAN_POINTER_START_BINARY, params);
jedis.sadd(bfoo, bbar1, bbar2, bbar3);
ScanResult<byte[]> bResult = jedis.sscan(bfoo,
SCAN_POINTER_START_BINARY, params);
assertFalse(bResult.getResult().isEmpty());
assertFalse(bResult.getResult().isEmpty());
}
}

View File

@@ -10,39 +10,39 @@ public class SlowlogCommandsTest extends JedisCommandTestBase {
@Test
public void slowlog() {
// do something
jedis.configSet("slowlog-log-slower-than", "0");
jedis.set("foo", "bar");
jedis.set("foo2", "bar2");
// 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());
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());
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<byte[]> breducedLog = jedis.slowlogGetBinary(1);
assertEquals(1, breducedLog.size());
List<Slowlog> log1 = jedis.slowlogGet();
List<byte[]> blog1 = jedis.slowlogGetBinary();
List<Slowlog> log1 = jedis.slowlogGet();
List<byte[]> blog1 = jedis.slowlogGetBinary();
assertNotNull(log1);
assertNotNull(blog1);
assertNotNull(log1);
assertNotNull(blog1);
long len1 = jedis.slowlogLen();
long len1 = jedis.slowlogLen();
jedis.slowlogReset();
jedis.slowlogReset();
List<Slowlog> log2 = jedis.slowlogGet();
List<byte[]> blog2 = jedis.slowlogGetBinary();
long len2 = jedis.slowlogLen();
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());
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,206 +10,206 @@ 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 incrByFloatWrongValue() {
jedis.set("foo", "bar");
jedis.incrByFloat("foo", 2d);
jedis.set("foo", "bar");
jedis.incrByFloat("foo", 2d);
}
@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

@@ -29,278 +29,278 @@ public class TransactionCommandsTest extends JedisCommandTestBase {
@Before
public void setUp() throws Exception {
super.setUp();
super.setUp();
nj = new Jedis(hnp.getHost(), hnp.getPort(), 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 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.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");
Jedis jedis2 = createJedis();
jedis2.select(1);
jedis2.set("foo", "bar2");
List<Object> results = t.exec();
List<Object> results = t.exec();
assertNull(results);
assertNull(results);
}
@Test
public void testResetStateWhenInMulti() {
jedis.auth("foobared");
jedis.auth("foobared");
Transaction t = jedis.multi();
t.set("foooo", "barrr");
Transaction t = jedis.multi();
t.set("foooo", "barrr");
jedis.resetState();
assertEquals(null, jedis.get("foooo"));
jedis.resetState();
assertEquals(null, jedis.get("foooo"));
}
@Test
public void testResetStateWhenInMultiWithinPipeline() {
jedis.auth("foobared");
jedis.auth("foobared");
Pipeline p = jedis.pipelined();
p.multi();
p.set("foooo", "barrr");
Pipeline p = jedis.pipelined();
p.multi();
p.set("foooo", "barrr");
jedis.resetState();
assertEquals(null, jedis.get("foooo"));
jedis.resetState();
assertEquals(null, jedis.get("foooo"));
}
@Test
public void testResetStateWhenInWatch() {
jedis.watch("mykey", "somekey");
jedis.watch("mykey", "somekey");
// state reset : unwatch
jedis.resetState();
// state reset : unwatch
jedis.resetState();
Transaction t = jedis.multi();
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();
assertNotNull(resp);
assertEquals(1, resp.size());
assertEquals("foo", jedis.get("mykey"));
t.set("mykey", "foo");
List<Object> resp = t.exec();
assertNotNull(resp);
assertEquals(1, resp.size());
assertEquals("foo", jedis.get("mykey"));
}
}

View File

@@ -18,173 +18,173 @@ public class VariadicCommandsTest extends JedisCommandTestBase {
@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
public void rpush() {
long size = jedis.rpush("foo", "bar", "foo");
assertEquals(2, size);
long size = jedis.rpush("foo", "bar", "foo");
assertEquals(2, size);
List<String> expected = new ArrayList<String>();
expected.add("bar");
expected.add("foo");
List<String> expected = new ArrayList<String>();
expected.add("bar");
expected.add("foo");
List<String> values = jedis.lrange("foo", 0, -1);
assertEquals(expected, values);
List<String> values = jedis.lrange("foo", 0, -1);
assertEquals(expected, values);
// Binary
size = jedis.rpush(bfoo, bbar, bfoo);
assertEquals(2, size);
// Binary
size = jedis.rpush(bfoo, bbar, bfoo);
assertEquals(2, size);
List<byte[]> bexpected = new ArrayList<byte[]>();
bexpected.add(bbar);
bexpected.add(bfoo);
List<byte[]> bexpected = new ArrayList<byte[]>();
bexpected.add(bbar);
bexpected.add(bfoo);
List<byte[]> bvalues = jedis.lrange(bfoo, 0, -1);
assertEquals(bexpected, bvalues);
List<byte[]> bvalues = jedis.lrange(bfoo, 0, -1);
assertEquals(bexpected, bvalues);
}
@Test
public void lpush() {
long size = jedis.lpush("foo", "bar", "foo");
assertEquals(2, size);
long size = jedis.lpush("foo", "bar", "foo");
assertEquals(2, size);
List<String> expected = new ArrayList<String>();
expected.add("foo");
expected.add("bar");
List<String> expected = new ArrayList<String>();
expected.add("foo");
expected.add("bar");
List<String> values = jedis.lrange("foo", 0, -1);
assertEquals(expected, values);
List<String> values = jedis.lrange("foo", 0, -1);
assertEquals(expected, values);
// Binary
size = jedis.lpush(bfoo, bbar, bfoo);
assertEquals(2, size);
// Binary
size = jedis.lpush(bfoo, bbar, bfoo);
assertEquals(2, size);
List<byte[]> bexpected = new ArrayList<byte[]>();
bexpected.add(bfoo);
bexpected.add(bbar);
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
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
public void zadd() {
Map<String, Double> scoreMembers = new HashMap<String, Double>();
scoreMembers.put("bar", 1d);
scoreMembers.put("foo", 10d);
Map<String, Double> scoreMembers = new HashMap<String, Double>();
scoreMembers.put("bar", 1d);
scoreMembers.put("foo", 10d);
long status = jedis.zadd("foo", scoreMembers);
assertEquals(2, status);
long status = jedis.zadd("foo", scoreMembers);
assertEquals(2, status);
scoreMembers.clear();
scoreMembers.put("car", 0.1d);
scoreMembers.put("bar", 2d);
scoreMembers.clear();
scoreMembers.put("car", 0.1d);
scoreMembers.put("bar", 2d);
status = jedis.zadd("foo", scoreMembers);
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);
Map<byte[], Double> bscoreMembers = new HashMap<byte[], Double>();
bscoreMembers.put(bbar, 1d);
bscoreMembers.put(bfoo, 10d);
status = jedis.zadd(bfoo, bscoreMembers);
assertEquals(2, status);
status = jedis.zadd(bfoo, bscoreMembers);
assertEquals(2, status);
bscoreMembers.clear();
bscoreMembers.put(bcar, 0.1d);
bscoreMembers.put(bbar, 2d);
bscoreMembers.clear();
bscoreMembers.put(bcar, 0.1d);
bscoreMembers.put(bbar, 2d);
status = jedis.zadd(bfoo, bscoreMembers);
assertEquals(1, status);
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", "car");
assertEquals(0, status);
status = jedis.zrem("foo", "bar", "foo1");
assertEquals(1, status);
status = jedis.zrem("foo", "bar", "foo1");
assertEquals(1, status);
// Binary
jedis.zadd(bfoo, 1d, bbar);
jedis.zadd(bfoo, 2d, bcar);
jedis.zadd(bfoo, 3d, bfoo1);
// Binary
jedis.zadd(bfoo, 1d, bbar);
jedis.zadd(bfoo, 2d, bcar);
jedis.zadd(bfoo, 3d, bfoo1);
status = jedis.zrem(bfoo, bbar, bcar);
status = jedis.zrem(bfoo, bbar, bcar);
Set<byte[]> bexpected = new LinkedHashSet<byte[]>();
bexpected.add(bfoo);
Set<byte[]> bexpected = new LinkedHashSet<byte[]>();
bexpected.add(bfoo);
assertEquals(2, status);
assertEquals(bexpected, jedis.zrange(bfoo, 0, 100));
assertEquals(2, status);
assertEquals(bexpected, jedis.zrange(bfoo, 0, 100));
status = jedis.zrem(bfoo, bbar, bcar);
assertEquals(0, status);
status = jedis.zrem(bfoo, bbar, bcar);
assertEquals(0, status);
status = jedis.zrem(bfoo, bbar, bfoo1);
assertEquals(1, status);
status = jedis.zrem(bfoo, bbar, bfoo1);
assertEquals(1, status);
}
}

View File

@@ -4,14 +4,14 @@ public class FailoverAbortedException extends RuntimeException {
private static final long serialVersionUID = 1925110762858409954L;
public FailoverAbortedException(String message) {
super(message);
super(message);
}
public FailoverAbortedException(Throwable cause) {
super(cause);
super(cause);
}
public FailoverAbortedException(String message, Throwable cause) {
super(message, cause);
super(message, cause);
}
}

View File

@@ -15,33 +15,33 @@ public class JedisClusterCRC16Test {
@Test
public void testGetCRC16() throws Exception {
Map<String, Integer> solutions = prepareSolutionSet();
Map<String, Integer> solutions = prepareSolutionSet();
for (Entry<String, Integer> entry : solutions.entrySet()) {
// string version
assertEquals(entry.getValue().intValue(),
JedisClusterCRC16.getCRC16(entry.getKey()));
for (Entry<String, Integer> entry : solutions.entrySet()) {
// string version
assertEquals(entry.getValue().intValue(),
JedisClusterCRC16.getCRC16(entry.getKey()));
// byte array version
assertEquals(entry.getValue().intValue(),
JedisClusterCRC16.getCRC16(SafeEncoder.encode(entry
.getKey())));
}
// byte array version
assertEquals(entry.getValue().intValue(),
JedisClusterCRC16.getCRC16(SafeEncoder.encode(entry
.getKey())));
}
}
@Test
public void testGetSlot() {
assertEquals(7186, JedisClusterCRC16.getSlot("51"));
assertEquals(7186, JedisClusterCRC16.getSlot("51"));
}
private Map<String, Integer> prepareSolutionSet() {
Map<String, Integer> solutionMap = new HashMap<String, Integer>();
solutionMap.put("", 0x0);
solutionMap.put("123456789", 0x31C3);
solutionMap.put("sfger132515", 0xA45C);
solutionMap.put("hae9Napahngaikeethievubaibogiech", 0x58CE);
solutionMap.put("AAAAAAAAAAAAAAAAAAAAAA", 0x92cd);
solutionMap.put("Hello, World!", 0x4FD6);
return solutionMap;
Map<String, Integer> solutionMap = new HashMap<String, Integer>();
solutionMap.put("", 0x0);
solutionMap.put("123456789", 0x31C3);
solutionMap.put("sfger132515", 0xA45C);
solutionMap.put("hae9Napahngaikeethievubaibogiech", 0x58CE);
solutionMap.put("AAAAAAAAAAAAAAAAAAAAAA", 0x92cd);
solutionMap.put("Hello, World!", 0x4FD6);
return solutionMap;
}
}

View File

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

View File

@@ -8,39 +8,39 @@ import redis.clients.jedis.JedisPubSub;
public class JedisSentinelTestUtil {
public static HostAndPort waitForNewPromotedMaster(final String masterName,
final Jedis sentinelJedis, final Jedis commandJedis)
throws InterruptedException {
final Jedis sentinelJedis, final Jedis commandJedis)
throws InterruptedException {
final AtomicReference<String> newmaster = new AtomicReference<String>(
"");
final AtomicReference<String> newmaster = new AtomicReference<String>(
"");
sentinelJedis.psubscribe(new JedisPubSub() {
sentinelJedis.psubscribe(new JedisPubSub() {
@Override
public void onPMessage(String pattern, String channel,
String message) {
if (channel.equals("+switch-master")) {
newmaster.set(message);
punsubscribe();
} else if (channel.startsWith("-failover-abort")) {
punsubscribe();
throw new FailoverAbortedException(
"Unfortunately sentinel cannot failover... reason(channel) : "
+ channel + " / message : " + message);
}
}
@Override
public void onPMessage(String pattern, String channel,
String message) {
if (channel.equals("+switch-master")) {
newmaster.set(message);
punsubscribe();
} else if (channel.startsWith("-failover-abort")) {
punsubscribe();
throw new FailoverAbortedException(
"Unfortunately sentinel cannot failover... reason(channel) : "
+ channel + " / message : " + message);
}
}
@Override
public void onPSubscribe(String pattern, int subscribedChannels) {
commandJedis.sentinelFailover(masterName);
}
}, "*");
@Override
public void onPSubscribe(String pattern, int subscribedChannels) {
commandJedis.sentinelFailover(masterName);
}
}, "*");
String[] chunks = newmaster.get().split(" ");
HostAndPort newMaster = new HostAndPort(chunks[3],
Integer.parseInt(chunks[4]));
String[] chunks = newmaster.get().split(" ");
HostAndPort newMaster = new HostAndPort(chunks[3],
Integer.parseInt(chunks[4]));
return newMaster;
return newMaster;
}
}