Merge branch 'master' into introduce-new-sentinel-commands-added-to-Redis-2.8

Conflicts:
	Makefile
	src/main/java/redis/clients/jedis/Jedis.java
This commit is contained in:
Jungtaek Lim
2014-02-05 00:26:14 +09:00
100 changed files with 6206 additions and 5711 deletions

View File

@@ -208,8 +208,8 @@ start: cleanup
echo "$$REDIS_CLUSTER_NODE3_CONF" | redis-server - echo "$$REDIS_CLUSTER_NODE3_CONF" | redis-server -
cleanup: cleanup:
rm -vf /tmp/redis_cluster_node*.conf - rm -vf /tmp/redis_cluster_node*.conf 2>/dev/null
rm -vf /tmp/sentinel*.conf - rm dump.rdb appendonly.aof - 2>/dev/null
stop: stop:
kill `cat /tmp/redis1.pid` kill `cat /tmp/redis1.pid`

View File

@@ -73,7 +73,7 @@ Redis cluster [specification](http://redis.io/topics/cluster-spec) (still under
```java ```java
Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>(); Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>();
//Jedis Cluster will attempt to discover cluster nodes automatically //Jedis Cluster will attempt to discover cluster nodes automatically
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); jedisClusterNodes.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode); JedisCluster jc = new JedisCluster(jedisClusterNode);
jc.set("foo", "bar"); jc.set("foo", "bar");
String value = jc.get("foo"); String value = jc.get("foo");

View File

@@ -9,7 +9,7 @@
<packaging>jar</packaging> <packaging>jar</packaging>
<groupId>redis.clients</groupId> <groupId>redis.clients</groupId>
<artifactId>jedis</artifactId> <artifactId>jedis</artifactId>
<version>2.2.2-SNAPSHOT</version> <version>2.3.1-SNAPSHOT</version>
<name>Jedis</name> <name>Jedis</name>
<description>Jedis is a blazingly small and sane Redis java client.</description> <description>Jedis is a blazingly small and sane Redis java client.</description>
<url>https://github.com/xetorthio/jedis</url> <url>https://github.com/xetorthio/jedis</url>

View File

@@ -1,6 +1,5 @@
package redis.clients.jedis; package redis.clients.jedis;
import java.util.List; import java.util.List;
public interface AdvancedBinaryJedisCommands { public interface AdvancedBinaryJedisCommands {

View File

@@ -1,9 +1,8 @@
package redis.clients.jedis; package redis.clients.jedis;
import redis.clients.util.Slowlog;
import java.util.List; import java.util.List;
import redis.clients.util.Slowlog;
public interface AdvancedJedisCommands { public interface AdvancedJedisCommands {
List<String> configGet(String pattern); List<String> configGet(String pattern);

View File

@@ -1,6 +1,5 @@
package redis.clients.jedis; package redis.clients.jedis;
/** /**
* Pipelined responses for all of the low level, non key related commands * Pipelined responses for all of the low level, non key related commands
*/ */

View File

@@ -1,22 +1,26 @@
package redis.clients.jedis; package redis.clients.jedis;
import redis.clients.jedis.Protocol.Command; import static redis.clients.jedis.Protocol.toByteArray;
import redis.clients.jedis.Protocol.Keyword; import static redis.clients.jedis.Protocol.Command.*;
import redis.clients.util.SafeEncoder; import static redis.clients.jedis.Protocol.Keyword.ENCODING;
import static redis.clients.jedis.Protocol.Keyword.IDLETIME;
import static redis.clients.jedis.Protocol.Keyword.LEN;
import static redis.clients.jedis.Protocol.Keyword.LIMIT;
import static redis.clients.jedis.Protocol.Keyword.NO;
import static redis.clients.jedis.Protocol.Keyword.ONE;
import static redis.clients.jedis.Protocol.Keyword.REFCOUNT;
import static redis.clients.jedis.Protocol.Keyword.RESET;
import static redis.clients.jedis.Protocol.Keyword.STORE;
import static redis.clients.jedis.Protocol.Keyword.WITHSCORES;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import static redis.clients.jedis.Protocol.Command.*; import redis.clients.jedis.Protocol.Command;
import static redis.clients.jedis.Protocol.Command.EXISTS; import redis.clients.jedis.Protocol.Keyword;
import static redis.clients.jedis.Protocol.Command.PSUBSCRIBE; import redis.clients.util.SafeEncoder;
import static redis.clients.jedis.Protocol.Command.PUNSUBSCRIBE;
import static redis.clients.jedis.Protocol.Command.SUBSCRIBE;
import static redis.clients.jedis.Protocol.Command.UNSUBSCRIBE;
import static redis.clients.jedis.Protocol.Keyword.*;
import static redis.clients.jedis.Protocol.toByteArray;
public class BinaryClient extends Connection { public class BinaryClient extends Connection {
public enum LIST_POSITION { public enum LIST_POSITION {
@@ -34,10 +38,16 @@ public class BinaryClient extends Connection {
private long db; private long db;
private boolean isInWatch;
public boolean isInMulti() { public boolean isInMulti() {
return isInMulti; return isInMulti;
} }
public boolean isInWatch() {
return isInWatch;
}
public BinaryClient(final String host) { public BinaryClient(final String host) {
super(host); super(host);
} }
@@ -82,11 +92,11 @@ public class BinaryClient extends Connection {
sendCommand(Command.SET, key, value); sendCommand(Command.SET, key, value);
} }
public void set(final byte[] key, final byte[] value, final byte[] nxxx, final byte[] expx, final long time) { public void set(final byte[] key, final byte[] value, final byte[] nxxx,
final byte[] expx, final long time) {
sendCommand(Command.SET, key, value, nxxx, expx, toByteArray(time)); sendCommand(Command.SET, key, value, nxxx, expx, toByteArray(time));
} }
public void get(final byte[] key) { public void get(final byte[] key) {
sendCommand(Command.GET, key); sendCommand(Command.GET, key);
} }
@@ -377,15 +387,16 @@ public class BinaryClient extends Connection {
sendCommand(ZADD, key, toByteArray(score), member); sendCommand(ZADD, key, toByteArray(score), member);
} }
public void zaddBinary(final byte[] key, Map<Double, byte[]> scoreMembers) { public void zaddBinary(final byte[] key,
final Map<byte[], Double> scoreMembers) {
ArrayList<byte[]> args = new ArrayList<byte[]>( ArrayList<byte[]> args = new ArrayList<byte[]>(
scoreMembers.size() * 2 + 1); scoreMembers.size() * 2 + 1);
args.add(key); args.add(key);
for (Map.Entry<Double, byte[]> entry : scoreMembers.entrySet()) { for (Map.Entry<byte[], Double> entry : scoreMembers.entrySet()) {
args.add(toByteArray(entry.getKey())); args.add(toByteArray(entry.getValue()));
args.add(entry.getValue()); args.add(entry.getKey());
} }
byte[][] argsArray = new byte[args.size()][]; byte[][] argsArray = new byte[args.size()][];
@@ -447,19 +458,23 @@ public class BinaryClient extends Connection {
public void discard() { public void discard() {
sendCommand(DISCARD); sendCommand(DISCARD);
isInMulti = false; isInMulti = false;
isInWatch = false;
} }
public void exec() { public void exec() {
sendCommand(EXEC); sendCommand(EXEC);
isInMulti = false; isInMulti = false;
isInWatch = false;
} }
public void watch(final byte[]... keys) { public void watch(final byte[]... keys) {
sendCommand(WATCH, keys); sendCommand(WATCH, keys);
isInWatch = true;
} }
public void unwatch() { public void unwatch() {
sendCommand(UNWATCH); sendCommand(UNWATCH);
isInWatch = false;
} }
public void sort(final byte[] key) { public void sort(final byte[] key) {
@@ -546,10 +561,15 @@ public class BinaryClient extends Connection {
sendCommand(PUNSUBSCRIBE, patterns); sendCommand(PUNSUBSCRIBE, patterns);
} }
public void pubsub(final byte[]... args) {
sendCommand(PUBSUB, args);
}
public void zcount(final byte[] key, final double min, final double max) { public void zcount(final byte[] key, final double min, final double max) {
byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf"
byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); .getBytes() : toByteArray(min);
byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf"
.getBytes() : toByteArray(max);
sendCommand(ZCOUNT, key, byteArrayMin, byteArrayMax); sendCommand(ZCOUNT, key, byteArrayMin, byteArrayMax);
} }
@@ -565,8 +585,10 @@ public class BinaryClient extends Connection {
public void zrangeByScore(final byte[] key, final double min, public void zrangeByScore(final byte[] key, final double min,
final double max) { final double max) {
byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf"
byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); .getBytes() : toByteArray(min);
byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf"
.getBytes() : toByteArray(max);
sendCommand(ZRANGEBYSCORE, key, byteArrayMin, byteArrayMax); sendCommand(ZRANGEBYSCORE, key, byteArrayMin, byteArrayMax);
} }
@@ -584,8 +606,10 @@ public class BinaryClient extends Connection {
public void zrevrangeByScore(final byte[] key, final double max, public void zrevrangeByScore(final byte[] key, final double max,
final double min) { final double min) {
byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf"
byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); .getBytes() : toByteArray(min);
byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf"
.getBytes() : toByteArray(max);
sendCommand(ZREVRANGEBYSCORE, key, byteArrayMax, byteArrayMin); sendCommand(ZREVRANGEBYSCORE, key, byteArrayMax, byteArrayMin);
} }
@@ -603,11 +627,13 @@ public class BinaryClient extends Connection {
public void zrangeByScore(final byte[] key, final double min, public void zrangeByScore(final byte[] key, final double min,
final double max, final int offset, int count) { final double max, final int offset, int count) {
byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf"
byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); .getBytes() : toByteArray(min);
byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf"
.getBytes() : toByteArray(max);
sendCommand(ZRANGEBYSCORE, key, byteArrayMin, byteArrayMax, sendCommand(ZRANGEBYSCORE, key, byteArrayMin, byteArrayMax, LIMIT.raw,
LIMIT.raw, toByteArray(offset), toByteArray(count)); toByteArray(offset), toByteArray(count));
} }
public void zrangeByScore(final byte[] key, final String min, public void zrangeByScore(final byte[] key, final String min,
@@ -620,8 +646,10 @@ public class BinaryClient extends Connection {
public void zrevrangeByScore(final byte[] key, final double max, public void zrevrangeByScore(final byte[] key, final double max,
final double min, final int offset, int count) { final double min, final int offset, int count) {
byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf"
byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); .getBytes() : toByteArray(min);
byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf"
.getBytes() : toByteArray(max);
sendCommand(ZREVRANGEBYSCORE, key, byteArrayMax, byteArrayMin, sendCommand(ZREVRANGEBYSCORE, key, byteArrayMax, byteArrayMin,
LIMIT.raw, toByteArray(offset), toByteArray(count)); LIMIT.raw, toByteArray(offset), toByteArray(count));
@@ -637,8 +665,10 @@ public class BinaryClient extends Connection {
public void zrangeByScoreWithScores(final byte[] key, final double min, public void zrangeByScoreWithScores(final byte[] key, final double min,
final double max) { final double max) {
byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf"
byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); .getBytes() : toByteArray(min);
byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf"
.getBytes() : toByteArray(max);
sendCommand(ZRANGEBYSCORE, key, byteArrayMin, byteArrayMax, sendCommand(ZRANGEBYSCORE, key, byteArrayMin, byteArrayMax,
WITHSCORES.raw); WITHSCORES.raw);
@@ -654,8 +684,10 @@ public class BinaryClient extends Connection {
public void zrevrangeByScoreWithScores(final byte[] key, final double max, public void zrevrangeByScoreWithScores(final byte[] key, final double max,
final double min) { final double min) {
byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf"
byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); .getBytes() : toByteArray(min);
byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf"
.getBytes() : toByteArray(max);
sendCommand(ZREVRANGEBYSCORE, key, byteArrayMax, byteArrayMin, sendCommand(ZREVRANGEBYSCORE, key, byteArrayMax, byteArrayMin,
WITHSCORES.raw); WITHSCORES.raw);
@@ -670,12 +702,13 @@ public class BinaryClient extends Connection {
public void zrangeByScoreWithScores(final byte[] key, final double min, public void zrangeByScoreWithScores(final byte[] key, final double min,
final double max, final int offset, final int count) { final double max, final int offset, final int count) {
byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf"
byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); .getBytes() : toByteArray(min);
byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf"
.getBytes() : toByteArray(max);
sendCommand(ZRANGEBYSCORE, key, byteArrayMin, byteArrayMax, sendCommand(ZRANGEBYSCORE, key, byteArrayMin, byteArrayMax, LIMIT.raw,
LIMIT.raw, toByteArray(offset), toByteArray(count), toByteArray(offset), toByteArray(count), WITHSCORES.raw);
WITHSCORES.raw);
} }
public void zrangeByScoreWithScores(final byte[] key, final String min, public void zrangeByScoreWithScores(final byte[] key, final String min,
@@ -688,8 +721,10 @@ public class BinaryClient extends Connection {
public void zrevrangeByScoreWithScores(final byte[] key, final double max, public void zrevrangeByScoreWithScores(final byte[] key, final double max,
final double min, final int offset, final int count) { final double min, final int offset, final int count) {
byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf".getBytes() : toByteArray(min); byte byteArrayMin[] = (min == Double.NEGATIVE_INFINITY) ? "-inf"
byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf".getBytes() : toByteArray(max); .getBytes() : toByteArray(min);
byte byteArrayMax[] = (max == Double.POSITIVE_INFINITY) ? "+inf"
.getBytes() : toByteArray(max);
sendCommand(ZREVRANGEBYSCORE, key, byteArrayMax, byteArrayMin, sendCommand(ZREVRANGEBYSCORE, key, byteArrayMax, byteArrayMin,
LIMIT.raw, toByteArray(offset), toByteArray(count), LIMIT.raw, toByteArray(offset), toByteArray(count),
@@ -913,6 +948,14 @@ public class BinaryClient extends Connection {
super.disconnect(); super.disconnect();
} }
public void resetState() {
if (isInMulti())
discard();
if (isInWatch())
unwatch();
}
private void sendEvalCommand(Command command, byte[] script, private void sendEvalCommand(Command command, byte[] script,
byte[] keyCount, byte[][] params) { byte[] keyCount, byte[][] params) {
@@ -1037,7 +1080,8 @@ public class BinaryClient extends Connection {
sendCommand(DUMP, key); sendCommand(DUMP, key);
} }
public void restore(final byte[] key, final int ttl, final byte[] serializedValue) { public void restore(final byte[] key, final int ttl,
final byte[] serializedValue) {
sendCommand(RESTORE, key, toByteArray(ttl), serializedValue); sendCommand(RESTORE, key, toByteArray(ttl), serializedValue);
} }
@@ -1057,7 +1101,8 @@ public class BinaryClient extends Connection {
sendCommand(INCRBYFLOAT, key, toByteArray(increment)); sendCommand(INCRBYFLOAT, key, toByteArray(increment));
} }
public void psetex(final byte[] key, final int milliseconds, final byte[] value) { public void psetex(final byte[] key, final int milliseconds,
final byte[] value) {
sendCommand(PSETEX, key, toByteArray(milliseconds), value); sendCommand(PSETEX, key, toByteArray(milliseconds), value);
} }
@@ -1065,7 +1110,8 @@ public class BinaryClient extends Connection {
sendCommand(Command.SET, key, value, nxxx); sendCommand(Command.SET, key, value, nxxx);
} }
public void set(final byte[] key, final byte[] value, final byte[] nxxx, final byte[] expx, final int time) { public void set(final byte[] key, final byte[] value, final byte[] nxxx,
final byte[] expx, final int time) {
sendCommand(Command.SET, key, value, nxxx, expx, toByteArray(time)); sendCommand(Command.SET, key, value, nxxx, expx, toByteArray(time));
} }
@@ -1093,11 +1139,14 @@ public class BinaryClient extends Connection {
sendCommand(TIME); sendCommand(TIME);
} }
public void migrate(final byte[] host, final int port, final byte[] key, final int destinationDb, final int timeout) { public void migrate(final byte[] host, final int port, final byte[] key,
sendCommand(MIGRATE, host, toByteArray(port), key, toByteArray(destinationDb), toByteArray(timeout)); final int destinationDb, final int timeout) {
sendCommand(MIGRATE, host, toByteArray(port), key,
toByteArray(destinationDb), toByteArray(timeout));
} }
public void hincrByFloat(final byte[] key, final byte[] field, double increment) { public void hincrByFloat(final byte[] key, final byte[] field,
double increment) {
sendCommand(HINCRBYFLOAT, key, field, toByteArray(increment)); sendCommand(HINCRBYFLOAT, key, field, toByteArray(increment));
} }
@@ -1139,6 +1188,7 @@ public class BinaryClient extends Connection {
public void cluster(final byte[]... args) { public void cluster(final byte[]... args) {
sendCommand(CLUSTER, args); sendCommand(CLUSTER, args);
} }
public void asking() { public void asking() {
sendCommand(Command.ASKING); sendCommand(Command.ASKING);
} }

View File

@@ -1,17 +1,25 @@
package redis.clients.jedis; package redis.clients.jedis;
import static redis.clients.jedis.Protocol.toByteArray;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import redis.clients.jedis.BinaryClient.LIST_POSITION; import redis.clients.jedis.BinaryClient.LIST_POSITION;
import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.exceptions.JedisDataException;
import redis.clients.jedis.exceptions.JedisException; import redis.clients.jedis.exceptions.JedisException;
import redis.clients.util.JedisByteHashMap; import redis.clients.util.JedisByteHashMap;
import redis.clients.util.SafeEncoder; import redis.clients.util.SafeEncoder;
import java.net.URI; public class BinaryJedis implements BasicCommands, BinaryJedisCommands,
import java.util.*; MultiKeyBinaryCommands, AdvancedBinaryJedisCommands,
BinaryScriptingCommands {
import static redis.clients.jedis.Protocol.toByteArray;
public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKeyBinaryCommands, AdvancedBinaryJedisCommands, BinaryScriptingCommands {
protected Client client = null; protected Client client = null;
public BinaryJedis(final String host) { public BinaryJedis(final String host) {
@@ -75,15 +83,20 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey
/** /**
* Set the string value as value of the key. The string can't be longer than * Set the string value as value of the key. The string can't be longer than
* 1073741824 bytes (1 GB). * 1073741824 bytes (1 GB).
*
* @param key * @param key
* @param value * @param value
* @param nxxx NX|XX, NX -- Only set the key if it does not already exist. * @param nxxx
* XX -- Only set the key if it already exist. * NX|XX, NX -- Only set the key if it does not already exist. XX
* @param expx EX|PX, expire time units: EX = seconds; PX = milliseconds * -- Only set the key if it already exist.
* @param time expire time in the units of {@param #expx} * @param expx
* EX|PX, expire time units: EX = seconds; PX = milliseconds
* @param time
* expire time in the units of {@param #expx}
* @return Status code reply * @return Status code reply
*/ */
public String set(final byte[] key, final byte[] value, final byte[] nxxx, final byte[] expx, final long time) { public String set(final byte[] key, final byte[] value, final byte[] nxxx,
final byte[] expx, final long time) {
checkIsInMulti(); checkIsInMulti();
client.set(key, value, nxxx, expx, time); client.set(key, value, nxxx, expx, time);
return client.getStatusCodeReply(); return client.getStatusCodeReply();
@@ -1006,7 +1019,8 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey
* @return Multi bulk reply, specifically a list of elements in the * @return Multi bulk reply, specifically a list of elements in the
* specified range. * specified range.
*/ */
public List<byte[]> lrange(final byte[] key, final long start, final long end) { public List<byte[]> lrange(final byte[] key, final long start,
final long end) {
checkIsInMulti(); checkIsInMulti();
client.lrange(key, start, end); client.lrange(key, start, end);
return client.getBinaryMultiBulkReply(); return client.getBinaryMultiBulkReply();
@@ -1502,7 +1516,7 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey
return client.getIntegerReply(); return client.getIntegerReply();
} }
public Long zadd(final byte[] key, final Map<Double, byte[]> scoreMembers) { public Long zadd(final byte[] key, final Map<byte[], Double> scoreMembers) {
checkIsInMulti(); checkIsInMulti();
client.zaddBinary(key, scoreMembers); client.zaddBinary(key, scoreMembers);
return client.getIntegerReply(); return client.getIntegerReply();
@@ -1685,13 +1699,9 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey
public List<Object> multi(final TransactionBlock jedisTransaction) { public List<Object> multi(final TransactionBlock jedisTransaction) {
List<Object> results = null; List<Object> results = null;
jedisTransaction.setClient(client); jedisTransaction.setClient(client);
try {
client.multi(); client.multi();
jedisTransaction.execute(); jedisTransaction.execute();
results = jedisTransaction.exec(); results = jedisTransaction.exec();
} catch (Exception ex) {
jedisTransaction.discard();
}
return results; return results;
} }
@@ -1710,6 +1720,11 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey
client.disconnect(); client.disconnect();
} }
public void resetState() {
client.resetState();
client.getAll();
}
public String watch(final byte[]... keys) { public String watch(final byte[]... keys) {
client.watch(keys); client.watch(keys);
return client.getStatusCodeReply(); return client.getStatusCodeReply();
@@ -2261,7 +2276,8 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey
*/ */
public Set<byte[]> zrangeByScore(final byte[] key, final double min, public Set<byte[]> zrangeByScore(final byte[] key, final double min,
final double max, final int offset, final int count) { final double max, final int offset, final int count) {
return zrangeByScore(key, toByteArray(min),toByteArray(max),offset, count); return zrangeByScore(key, toByteArray(min), toByteArray(max), offset,
count);
} }
public Set<byte[]> zrangeByScore(final byte[] key, final byte[] min, public Set<byte[]> zrangeByScore(final byte[] key, final byte[] min,
@@ -2399,7 +2415,8 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey
public Set<Tuple> zrangeByScoreWithScores(final byte[] key, public Set<Tuple> zrangeByScoreWithScores(final byte[] key,
final double min, final double max, final int offset, final double min, final double max, final int offset,
final int count) { final int count) {
return zrangeByScoreWithScores(key, toByteArray(min), toByteArray(max), offset, count); return zrangeByScoreWithScores(key, toByteArray(min), toByteArray(max),
offset, count);
} }
public Set<Tuple> zrangeByScoreWithScores(final byte[] key, public Set<Tuple> zrangeByScoreWithScores(final byte[] key,
@@ -2437,7 +2454,8 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey
public Set<byte[]> zrevrangeByScore(final byte[] key, final double max, public Set<byte[]> zrevrangeByScore(final byte[] key, final double max,
final double min, final int offset, final int count) { final double min, final int offset, final int count) {
return zrevrangeByScore(key, toByteArray(max), toByteArray(min), offset, count); return zrevrangeByScore(key, toByteArray(max), toByteArray(min),
offset, count);
} }
public Set<byte[]> zrevrangeByScore(final byte[] key, final byte[] max, public Set<byte[]> zrevrangeByScore(final byte[] key, final byte[] max,
@@ -2449,13 +2467,15 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey
public Set<Tuple> zrevrangeByScoreWithScores(final byte[] key, public Set<Tuple> zrevrangeByScoreWithScores(final byte[] key,
final double max, final double min) { final double max, final double min) {
return zrevrangeByScoreWithScores(key, toByteArray(max), toByteArray(min)); return zrevrangeByScoreWithScores(key, toByteArray(max),
toByteArray(min));
} }
public Set<Tuple> zrevrangeByScoreWithScores(final byte[] key, public Set<Tuple> zrevrangeByScoreWithScores(final byte[] key,
final double max, final double min, final int offset, final double max, final double min, final int offset,
final int count) { final int count) {
return zrevrangeByScoreWithScores(key, toByteArray(max), toByteArray(min), offset, count); return zrevrangeByScoreWithScores(key, toByteArray(max),
toByteArray(min), offset, count);
} }
public Set<Tuple> zrevrangeByScoreWithScores(final byte[] key, public Set<Tuple> zrevrangeByScoreWithScores(final byte[] key,
@@ -2488,7 +2508,8 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey
* operation * operation
* *
*/ */
public Long zremrangeByRank(final byte[] key, final long start, final long end) { public Long zremrangeByRank(final byte[] key, final long start,
final long end) {
checkIsInMulti(); checkIsInMulti();
client.zremrangeByRank(key, start, end); client.zremrangeByRank(key, start, end);
return client.getIntegerReply(); return client.getIntegerReply();
@@ -3160,7 +3181,8 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey
public Object eval(byte[] script, int keyCount, byte[]... params) { public Object eval(byte[] script, int keyCount, byte[]... params) {
client.setTimeoutInfinite(); client.setTimeoutInfinite();
client.eval(script, SafeEncoder.encode(Integer.toString(keyCount)), params); client.eval(script, SafeEncoder.encode(Integer.toString(keyCount)),
params);
return client.getOne(); return client.getOne();
} }
@@ -3189,7 +3211,6 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey
for (int i = 0; i < argCount; i++) for (int i = 0; i < argCount; i++)
params[keyCount + i] = args.get(i); params[keyCount + i] = args.get(i);
return evalsha(sha1, keyCount, params); return evalsha(sha1, keyCount, params);
} }
@@ -3275,7 +3296,8 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey
return client.getBinaryBulkReply(); return client.getBinaryBulkReply();
} }
public String restore(final byte[] key, final int ttl, final byte[] serializedValue) { public String restore(final byte[] key, final int ttl,
final byte[] serializedValue) {
checkIsInMulti(); checkIsInMulti();
client.restore(key, ttl, serializedValue); client.restore(key, ttl, serializedValue);
return client.getStatusCodeReply(); return client.getStatusCodeReply();
@@ -3306,7 +3328,8 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey
return (relpy != null ? new Double(relpy) : null); return (relpy != null ? new Double(relpy) : null);
} }
public String psetex(final byte[] key, final int milliseconds, final byte[] value) { public String psetex(final byte[] key, final int milliseconds,
final byte[] value) {
checkIsInMulti(); checkIsInMulti();
client.psetex(key, milliseconds, value); client.psetex(key, milliseconds, value);
return client.getStatusCodeReply(); return client.getStatusCodeReply();
@@ -3318,7 +3341,8 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey
return client.getStatusCodeReply(); return client.getStatusCodeReply();
} }
public String set(final byte[] key, final byte[] value, final byte[] nxxx, final byte[] expx, final int time) { public String set(final byte[] key, final byte[] value, final byte[] nxxx,
final byte[] expx, final int time) {
checkIsInMulti(); checkIsInMulti();
client.set(key, value, nxxx, expx, time); client.set(key, value, nxxx, expx, time);
return client.getStatusCodeReply(); return client.getStatusCodeReply();
@@ -3354,13 +3378,15 @@ public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKey
return client.getMultiBulkReply(); return client.getMultiBulkReply();
} }
public String migrate(final byte[] host, final int port, final byte[] key, final int destinationDb, final int timeout) { public String migrate(final byte[] host, final int port, final byte[] key,
final int destinationDb, final int timeout) {
checkIsInMulti(); checkIsInMulti();
client.migrate(host, port, key, destinationDb, timeout); client.migrate(host, port, key, destinationDb, timeout);
return client.getStatusCodeReply(); return client.getStatusCodeReply();
} }
public Double hincrByFloat(final byte[] key, final byte[] field, double increment) { public Double hincrByFloat(final byte[] key, final byte[] field,
double increment) {
checkIsInMulti(); checkIsInMulti();
client.hincrByFloat(key, field, increment); client.hincrByFloat(key, field, increment);
String relpy = client.getBulkReply(); String relpy = client.getBulkReply();

View File

@@ -115,7 +115,7 @@ public interface BinaryJedisCommands {
Long zadd(byte[] key, double score, byte[] member); Long zadd(byte[] key, double score, byte[] member);
Long zadd(byte[] key, Map<Double, byte[]> scoreMembers); Long zadd(byte[] key, Map<byte[], Double> scoreMembers);
Set<byte[]> zrange(byte[] key, long start, long end); Set<byte[]> zrange(byte[] key, long start, long end);

View File

@@ -117,8 +117,7 @@ public interface BinaryRedisPipeline {
Response<List<byte[]>> sort(byte[] key); Response<List<byte[]>> sort(byte[] key);
Response<List<byte[]>> sort(byte[] key, Response<List<byte[]>> sort(byte[] key, SortingParams sortingParameters);
SortingParams sortingParameters);
Response<byte[]> spop(byte[] key); Response<byte[]> spop(byte[] key);
@@ -144,17 +143,15 @@ public interface BinaryRedisPipeline {
Response<Set<byte[]>> zrange(byte[] key, long start, long end); Response<Set<byte[]>> zrange(byte[] key, long start, long end);
Response<Set<byte[]>> zrangeByScore(byte[] key, double min, Response<Set<byte[]>> zrangeByScore(byte[] key, double min, double max);
double max);
Response<Set<byte[]>> zrangeByScore(byte[] key, byte[] min, Response<Set<byte[]>> zrangeByScore(byte[] key, byte[] min, byte[] max);
byte[] max);
Response<Set<byte[]>> zrangeByScore(byte[] key, double min, Response<Set<byte[]>> zrangeByScore(byte[] key, double min, double max,
double max, int offset, int count); int offset, int count);
Response<Set<byte[]>> zrangeByScore(byte[] key, byte[] min, Response<Set<byte[]>> zrangeByScore(byte[] key, byte[] min, byte[] max,
byte[] max, int offset, int count); int offset, int count);
Response<Set<Tuple>> zrangeByScoreWithScores(byte[] key, double min, Response<Set<Tuple>> zrangeByScoreWithScores(byte[] key, double min,
double max); double max);
@@ -168,30 +165,28 @@ public interface BinaryRedisPipeline {
Response<Set<Tuple>> zrangeByScoreWithScores(byte[] key, byte[] min, Response<Set<Tuple>> zrangeByScoreWithScores(byte[] key, byte[] min,
byte[] max, int offset, int count); byte[] max, int offset, int count);
Response<Set<byte[]>> zrevrangeByScore(byte[] key, double max, Response<Set<byte[]>> zrevrangeByScore(byte[] key, double max, double min);
Response<Set<byte[]>> zrevrangeByScore(byte[] key, byte[] max, byte[] min);
Response<Set<byte[]>> zrevrangeByScore(byte[] key, double max, double min,
int offset, int count);
Response<Set<byte[]>> zrevrangeByScore(byte[] key, byte[] max, byte[] min,
int offset, int count);
Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key, double max,
double min); double min);
Response<Set<byte[]>> zrevrangeByScore(byte[] key, byte[] max, Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key, byte[] max,
byte[] min); byte[] min);
Response<Set<byte[]>> zrevrangeByScore(byte[] key, double max, Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key, double max,
double min, int offset, int count); double min, int offset, int count);
Response<Set<byte[]>> zrevrangeByScore(byte[] key, byte[] max, Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key, byte[] max,
byte[] min, int offset, int count); byte[] min, int offset, int count);
Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key,
double max, double min);
Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key,
byte[] max, byte[] min);
Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key,
double max, double min, int offset, int count);
Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key,
byte[] max, byte[] min, int offset, int count);
Response<Set<Tuple>> zrangeWithScores(byte[] key, long start, long end); Response<Set<Tuple>> zrangeWithScores(byte[] key, long start, long end);
Response<Long> zrank(byte[] key, byte[] member); Response<Long> zrank(byte[] key, byte[] member);
@@ -206,8 +201,7 @@ public interface BinaryRedisPipeline {
Response<Set<byte[]>> zrevrange(byte[] key, long start, long end); Response<Set<byte[]>> zrevrange(byte[] key, long start, long end);
Response<Set<Tuple>> zrevrangeWithScores(byte[] key, long start, Response<Set<Tuple>> zrevrangeWithScores(byte[] key, long start, long end);
long end);
Response<Long> zrevrank(byte[] key, byte[] member); Response<Long> zrevrank(byte[] key, byte[] member);

View File

@@ -1,6 +1,5 @@
package redis.clients.jedis; package redis.clients.jedis;
import java.util.List; import java.util.List;
public interface BinaryScriptingCommands { public interface BinaryScriptingCommands {

View File

@@ -295,7 +295,7 @@ public class BinaryShardedJedis extends Sharded<Jedis, JedisShardInfo>
return j.zadd(key, score, member); return j.zadd(key, score, member);
} }
public Long zadd(byte[] key, Map<Double, byte[]> scoreMembers) { public Long zadd(byte[] key, Map<byte[], Double> scoreMembers) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zadd(key, scoreMembers); return j.zadd(key, scoreMembers);
} }

View File

@@ -1,8 +1,5 @@
package redis.clients.jedis; package redis.clients.jedis;
public enum BitOP { public enum BitOP {
AND, AND, OR, XOR, NOT;
OR,
XOR,
NOT;
} }

View File

@@ -1,8 +1,15 @@
package redis.clients.jedis; package redis.clients.jedis;
import redis.clients.util.SafeEncoder; import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.*; import redis.clients.util.SafeEncoder;
public class BuilderFactory { public class BuilderFactory {
public static final Builder<Double> DOUBLE = new Builder<Double>() { public static final Builder<Double> DOUBLE = new Builder<Double>() {
@@ -84,8 +91,8 @@ public class BuilderFactory {
final Map<String, String> hash = new HashMap<String, String>(); final Map<String, String> hash = new HashMap<String, String>();
final Iterator<byte[]> iterator = flatHash.iterator(); final Iterator<byte[]> iterator = flatHash.iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
hash.put(SafeEncoder.encode(iterator.next()), SafeEncoder hash.put(SafeEncoder.encode(iterator.next()),
.encode(iterator.next())); SafeEncoder.encode(iterator.next()));
} }
return hash; return hash;
@@ -96,6 +103,7 @@ public class BuilderFactory {
} }
}; };
public static final Builder<Set<String>> STRING_SET = new Builder<Set<String>>() { public static final Builder<Set<String>> STRING_SET = new Builder<Set<String>>() {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public Set<String> build(Object data) { public Set<String> build(Object data) {

View File

@@ -1,6 +1,6 @@
package redis.clients.jedis; package redis.clients.jedis;
import redis.clients.util.SafeEncoder; import static redis.clients.jedis.Protocol.toByteArray;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
@@ -8,8 +8,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import static redis.clients.jedis.Protocol.toByteArray; import redis.clients.util.SafeEncoder;
import static redis.clients.jedis.Protocol.Command.HSCAN;
public class Client extends BinaryClient implements Commands { public class Client extends BinaryClient implements Commands {
public Client(final String host) { public Client(final String host) {
@@ -24,8 +23,10 @@ public class Client extends BinaryClient implements Commands {
set(SafeEncoder.encode(key), SafeEncoder.encode(value)); set(SafeEncoder.encode(key), SafeEncoder.encode(value));
} }
public void set(final String key, final String value, final String nxxx, final String expx, final long time) { public void set(final String key, final String value, final String nxxx,
set(SafeEncoder.encode(key), SafeEncoder.encode(value), SafeEncoder.encode(nxxx), SafeEncoder.encode(expx), time); final String expx, final long time) {
set(SafeEncoder.encode(key), SafeEncoder.encode(value),
SafeEncoder.encode(nxxx), SafeEncoder.encode(expx), time);
} }
public void get(final String key) { public void get(final String key) {
@@ -672,6 +673,18 @@ public class Client extends BinaryClient implements Commands {
subscribe(cs); subscribe(cs);
} }
public void pubsubChannels(String pattern) {
pubsub(Protocol.PUBSUB_CHANNELS, pattern);
}
public void pubsubNumPat() {
pubsub(Protocol.PUBSUB_NUM_PAT);
}
public void pubsubNumSub(String... channels) {
pubsub(Protocol.PUBSUB_NUMSUB, channels);
}
public void configSet(String parameter, String value) { public void configSet(String parameter, String value) {
configSet(SafeEncoder.encode(parameter), SafeEncoder.encode(value)); configSet(SafeEncoder.encode(parameter), SafeEncoder.encode(value));
} }
@@ -710,12 +723,14 @@ public class Client extends BinaryClient implements Commands {
scriptLoad(SafeEncoder.encode(script)); scriptLoad(SafeEncoder.encode(script));
} }
public void zadd(String key, Map<Double, String> scoreMembers) { public void zadd(String key, Map<String, Double> scoreMembers) {
HashMap<Double, byte[]> binaryScoreMembers = new HashMap<Double, byte[]>();
for (Map.Entry<Double, String> entry : scoreMembers.entrySet()) { HashMap<byte[], Double> binaryScoreMembers = new HashMap<byte[], Double>();
binaryScoreMembers.put(entry.getKey(),
SafeEncoder.encode(entry.getValue())); for (Map.Entry<String, Double> entry : scoreMembers.entrySet()) {
binaryScoreMembers.put(SafeEncoder.encode(entry.getKey()),
entry.getValue());
} }
zaddBinary(SafeEncoder.encode(key), binaryScoreMembers); zaddBinary(SafeEncoder.encode(key), binaryScoreMembers);
@@ -757,7 +772,8 @@ public class Client extends BinaryClient implements Commands {
dump(SafeEncoder.encode(key)); dump(SafeEncoder.encode(key));
} }
public void restore(final String key, final int ttl, final byte[] serializedValue) { public void restore(final String key, final int ttl,
final byte[] serializedValue) {
restore(SafeEncoder.encode(key), ttl, serializedValue); restore(SafeEncoder.encode(key), ttl, serializedValue);
} }
@@ -777,16 +793,20 @@ public class Client extends BinaryClient implements Commands {
incrByFloat(SafeEncoder.encode(key), increment); incrByFloat(SafeEncoder.encode(key), increment);
} }
public void psetex(final String key, final int milliseconds, final String value) { public void psetex(final String key, final int milliseconds,
final String value) {
psetex(SafeEncoder.encode(key), milliseconds, SafeEncoder.encode(value)); psetex(SafeEncoder.encode(key), milliseconds, SafeEncoder.encode(value));
} }
public void set(final String key, final String value, final String nxxx) { public void set(final String key, final String value, final String nxxx) {
set(SafeEncoder.encode(key), SafeEncoder.encode(value), SafeEncoder.encode(nxxx)); set(SafeEncoder.encode(key), SafeEncoder.encode(value),
SafeEncoder.encode(nxxx));
} }
public void set(final String key, final String value, final String nxxx, final String expx, final int time) { public void set(final String key, final String value, final String nxxx,
set(SafeEncoder.encode(key), SafeEncoder.encode(value), SafeEncoder.encode(nxxx), SafeEncoder.encode(expx), time); final String expx, final int time) {
set(SafeEncoder.encode(key), SafeEncoder.encode(value),
SafeEncoder.encode(nxxx), SafeEncoder.encode(expx), time);
} }
public void srandmember(final String key, final int count) { public void srandmember(final String key, final int count) {
@@ -801,12 +821,16 @@ public class Client extends BinaryClient implements Commands {
clientSetname(SafeEncoder.encode(name)); clientSetname(SafeEncoder.encode(name));
} }
public void migrate(final String host, final int port, final String key, final int destinationDb, final int timeout) { public void migrate(final String host, final int port, final String key,
migrate(SafeEncoder.encode(host), port, SafeEncoder.encode(key), destinationDb, timeout); final int destinationDb, final int timeout) {
migrate(SafeEncoder.encode(host), port, SafeEncoder.encode(key),
destinationDb, timeout);
} }
public void hincrByFloat(final String key, final String field, double increment) { public void hincrByFloat(final String key, final String field,
hincrByFloat(SafeEncoder.encode(key), SafeEncoder.encode(field), increment); double increment) {
hincrByFloat(SafeEncoder.encode(key), SafeEncoder.encode(field),
increment);
} }
public void hscan(final String key, int cursor, final ScanParams params) { public void hscan(final String key, int cursor, final ScanParams params) {
@@ -830,6 +854,15 @@ public class Client extends BinaryClient implements Commands {
cluster(arg); cluster(arg);
} }
public void pubsub(final String subcommand, final String... args) {
final byte[][] arg = new byte[args.length+1][];
for (int i = 1; i < arg.length; i++) {
arg[i] = SafeEncoder.encode(args[i-1]);
}
arg[0] = SafeEncoder.encode(subcommand);
pubsub(arg);
}
public void cluster(final String subcommand, final String... args) { public void cluster(final String subcommand, final String... args) {
final byte[][] arg = new byte[args.length + 1][]; final byte[][] arg = new byte[args.length + 1][];
for (int i = 1; i < arg.length; i++) { for (int i = 1; i < arg.length; i++) {
@@ -871,14 +904,17 @@ public class Client extends BinaryClient implements Commands {
} }
public void clusterSetSlotNode(final int slot, final String nodeId) { public void clusterSetSlotNode(final int slot, final String nodeId) {
cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot), Protocol.CLUSTER_SETSLOT_NODE, nodeId); cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot),
Protocol.CLUSTER_SETSLOT_NODE, nodeId);
} }
public void clusterSetSlotMigrating(final int slot, final String nodeId) { public void clusterSetSlotMigrating(final int slot, final String nodeId) {
cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot), Protocol.CLUSTER_SETSLOT_MIGRATING, nodeId); cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot),
Protocol.CLUSTER_SETSLOT_MIGRATING, nodeId);
} }
public void clusterSetSlotImporting(final int slot, final String nodeId) { public void clusterSetSlotImporting(final int slot, final String nodeId) {
cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot), Protocol.CLUSTER_SETSLOT_IMPORTING, nodeId); cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot),
Protocol.CLUSTER_SETSLOT_IMPORTING, nodeId);
} }
} }

View File

@@ -144,7 +144,7 @@ public interface Commands {
public void zadd(final String key, final double score, final String member); public void zadd(final String key, final double score, final String member);
public void zadd(final String key, final Map<Double, String> scoreMembers); public void zadd(final String key, final Map<String, Double> scoreMembers);
public void zrange(final String key, final long start, final long end); public void zrange(final String key, final long start, final long end);

View File

@@ -124,9 +124,13 @@ public class Connection {
socket = new Socket(); socket = new Socket();
// ->@wjw_add // ->@wjw_add
socket.setReuseAddress(true); socket.setReuseAddress(true);
socket.setKeepAlive(true); //Will monitor the TCP connection is valid socket.setKeepAlive(true); // Will monitor the TCP connection is
socket.setTcpNoDelay(true); //Socket buffer Whetherclosed, to ensure timely delivery of data // valid
socket.setSoLinger(true,0); //Control calls close () method, the underlying socket is closed immediately socket.setTcpNoDelay(true); // Socket buffer Whetherclosed, to
// ensure timely delivery of data
socket.setSoLinger(true, 0); // Control calls close () method,
// the underlying socket is closed
// immediately
// <-@wjw_add // <-@wjw_add
socket.connect(new InetSocketAddress(host, port), timeout); socket.connect(new InetSocketAddress(host, port), timeout);
@@ -202,11 +206,19 @@ public class Connection {
return (List<byte[]>) Protocol.read(inputStream); return (List<byte[]>) Protocol.read(inputStream);
} }
public void resetPipelinedCount() {
pipelinedCommands = 0;
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public List<Object> getRawObjectMultiBulkReply() {
return (List<Object>) Protocol.read(inputStream);
}
public List<Object> getObjectMultiBulkReply() { public List<Object> getObjectMultiBulkReply() {
flush(); flush();
pipelinedCommands--; pipelinedCommands--;
return (List<Object>) Protocol.read(inputStream); return getRawObjectMultiBulkReply();
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")

View File

@@ -26,8 +26,7 @@ public class HostAndPort {
String thisHost = convertHost(host); String thisHost = convertHost(host);
String hpHost = convertHost(hp.host); String hpHost = convertHost(hp.host);
return port == hp.port && return port == hp.port && thisHost.equals(hpHost);
thisHost.equals(hpHost);
} }

View File

@@ -15,7 +15,9 @@ import redis.clients.jedis.BinaryClient.LIST_POSITION;
import redis.clients.util.SafeEncoder; import redis.clients.util.SafeEncoder;
import redis.clients.util.Slowlog; import redis.clients.util.Slowlog;
public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommands, AdvancedJedisCommands, ScriptingCommands, BasicCommands, ClusterCommands, SentinelCommands { public class Jedis extends BinaryJedis implements JedisCommands,
MultiKeyCommands, AdvancedJedisCommands, ScriptingCommands,
BasicCommands, ClusterCommands {
public Jedis(final String host) { public Jedis(final String host) {
super(host); super(host);
} }
@@ -55,24 +57,29 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand
/** /**
* Set the string value as value of the key. The string can't be longer than * Set the string value as value of the key. The string can't be longer than
* 1073741824 bytes (1 GB). * 1073741824 bytes (1 GB).
*
* @param key * @param key
* @param value * @param value
* @param nxxx NX|XX, NX -- Only set the key if it does not already exist. * @param nxxx
* XX -- Only set the key if it already exist. * NX|XX, NX -- Only set the key if it does not already exist. XX
* @param expx EX|PX, expire time units: EX = seconds; PX = milliseconds * -- Only set the key if it already exist.
* @param time expire time in the units of {@param #expx} * @param expx
* EX|PX, expire time units: EX = seconds; PX = milliseconds
* @param time
* expire time in the units of {@param #expx}
* @return Status code reply * @return Status code reply
*/ */
public String set(final String key, final String value, final String nxxx, final String expx, final long time) { public String set(final String key, final String value, final String nxxx,
final String expx, final long time) {
checkIsInMulti(); checkIsInMulti();
client.set(key, value, nxxx, expx, time); client.set(key, value, nxxx, expx, time);
return client.getStatusCodeReply(); return client.getStatusCodeReply();
} }
/** /**
* Get the value of the specified key. If the key does not exist the special * Get the value of the specified key. If the key does not exist null is
* value 'nil' is returned. If the value stored at key is not a string an * returned. If the value stored at key is not a string an error is returned
* error is returned because GET can only handle string values. * because GET can only handle string values.
* <p> * <p>
* Time complexity: O(1) * Time complexity: O(1)
* *
@@ -1414,7 +1421,7 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand
return client.getIntegerReply(); return client.getIntegerReply();
} }
public Long zadd(final String key, final Map<Double, String> scoreMembers) { public Long zadd(final String key, final Map<String, Double> scoreMembers) {
checkIsInMulti(); checkIsInMulti();
client.zadd(key, scoreMembers); client.zadd(key, scoreMembers);
return client.getIntegerReply(); return client.getIntegerReply();
@@ -1953,8 +1960,6 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand
return multiBulkReply; return multiBulkReply;
} }
public Long zcount(final String key, final double min, final double max) { public Long zcount(final String key, final double min, final double max) {
checkIsInMulti(); checkIsInMulti();
client.zcount(key, min, max); client.zcount(key, min, max);
@@ -2019,8 +2024,10 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand
* @see #zcount(String, double, double) * @see #zcount(String, double, double)
* *
* @param key * @param key
* @param min a double or Double.MIN_VALUE for "-inf" * @param min
* @param max a double or Double.MAX_VALUE for "+inf" * a double or Double.MIN_VALUE for "-inf"
* @param max
* a double or Double.MAX_VALUE for "+inf"
* @return Multi bulk reply specifically a list of elements in the specified * @return Multi bulk reply specifically a list of elements in the specified
* score range. * score range.
*/ */
@@ -3043,7 +3050,8 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand
return client.getBinaryBulkReply(); return client.getBinaryBulkReply();
} }
public String restore(final String key, final int ttl, final byte[] serializedValue) { public String restore(final String key, final int ttl,
final byte[] serializedValue) {
checkIsInMulti(); checkIsInMulti();
client.restore(key, ttl, serializedValue); client.restore(key, ttl, serializedValue);
return client.getStatusCodeReply(); return client.getStatusCodeReply();
@@ -3074,7 +3082,8 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand
return (relpy != null ? new Double(relpy) : null); return (relpy != null ? new Double(relpy) : null);
} }
public String psetex(final String key, final int milliseconds, final String value) { public String psetex(final String key, final int milliseconds,
final String value) {
checkIsInMulti(); checkIsInMulti();
client.psetex(key, milliseconds, value); client.psetex(key, milliseconds, value);
return client.getStatusCodeReply(); return client.getStatusCodeReply();
@@ -3086,7 +3095,8 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand
return client.getStatusCodeReply(); return client.getStatusCodeReply();
} }
public String set(final String key, final String value, final String nxxx, final String expx, final int time) { public String set(final String key, final String value, final String nxxx,
final String expx, final int time) {
checkIsInMulti(); checkIsInMulti();
client.set(key, value, nxxx, expx, time); client.set(key, value, nxxx, expx, time);
return client.getStatusCodeReply(); return client.getStatusCodeReply();
@@ -3104,13 +3114,15 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand
return client.getStatusCodeReply(); return client.getStatusCodeReply();
} }
public String migrate(final String host, final int port, final String key, final int destinationDb, final int timeout) { public String migrate(final String host, final int port, final String key,
final int destinationDb, final int timeout) {
checkIsInMulti(); checkIsInMulti();
client.migrate(host, port, key, destinationDb, timeout); client.migrate(host, port, key, destinationDb, timeout);
return client.getStatusCodeReply(); return client.getStatusCodeReply();
} }
public Double hincrByFloat(final String key, final String field, double increment) { public Double hincrByFloat(final String key, final String field,
double increment) {
checkIsInMulti(); checkIsInMulti();
client.hincrByFloat(key, field, increment); client.hincrByFloat(key, field, increment);
String relpy = client.getBulkReply(); String relpy = client.getBulkReply();
@@ -3134,11 +3146,13 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand
return new ScanResult<String>(newcursor, results); return new ScanResult<String>(newcursor, results);
} }
public ScanResult<Map.Entry<String, String>> hscan(final String key, int cursor) { public ScanResult<Map.Entry<String, String>> hscan(final String key,
int cursor) {
return hscan(key, cursor, new ScanParams()); return hscan(key, cursor, new ScanParams());
} }
public ScanResult<Map.Entry<String, String>> hscan(final String key, int cursor, final ScanParams params) { public ScanResult<Map.Entry<String, String>> hscan(final String key,
int cursor, final ScanParams params) {
checkIsInMulti(); checkIsInMulti();
client.hscan(key, cursor, params); client.hscan(key, cursor, params);
List<Object> result = client.getObjectMultiBulkReply(); List<Object> result = client.getObjectMultiBulkReply();
@@ -3147,7 +3161,9 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand
List<byte[]> rawResults = (List<byte[]>) result.get(1); List<byte[]> rawResults = (List<byte[]>) result.get(1);
Iterator<byte[]> iterator = rawResults.iterator(); Iterator<byte[]> iterator = rawResults.iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
results.add(new AbstractMap.SimpleEntry<String, String>(SafeEncoder.encode(iterator.next()), SafeEncoder.encode(iterator.next()))); results.add(new AbstractMap.SimpleEntry<String, String>(SafeEncoder
.encode(iterator.next()), SafeEncoder.encode(iterator
.next())));
} }
return new ScanResult<Map.Entry<String, String>>(newcursor, results); return new ScanResult<Map.Entry<String, String>>(newcursor, results);
} }
@@ -3156,7 +3172,8 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand
return sscan(key, cursor, new ScanParams()); return sscan(key, cursor, new ScanParams());
} }
public ScanResult<String> sscan(final String key, int cursor, final ScanParams params) { public ScanResult<String> sscan(final String key, int cursor,
final ScanParams params) {
checkIsInMulti(); checkIsInMulti();
client.sscan(key, cursor, params); client.sscan(key, cursor, params);
List<Object> result = client.getObjectMultiBulkReply(); List<Object> result = client.getObjectMultiBulkReply();
@@ -3173,7 +3190,8 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand
return zscan(key, cursor, new ScanParams()); return zscan(key, cursor, new ScanParams());
} }
public ScanResult<Tuple> zscan(final String key, int cursor, final ScanParams params) { public ScanResult<Tuple> zscan(final String key, int cursor,
final ScanParams params) {
checkIsInMulti(); checkIsInMulti();
client.zscan(key, cursor, params); client.zscan(key, cursor, params);
List<Object> result = client.getObjectMultiBulkReply(); List<Object> result = client.getObjectMultiBulkReply();
@@ -3182,10 +3200,12 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand
List<byte[]> rawResults = (List<byte[]>) result.get(1); List<byte[]> rawResults = (List<byte[]>) result.get(1);
Iterator<byte[]> iterator = rawResults.iterator(); Iterator<byte[]> iterator = rawResults.iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
results.add(new Tuple(SafeEncoder.encode(iterator.next()), Double.valueOf(SafeEncoder.encode(iterator.next())))); results.add(new Tuple(SafeEncoder.encode(iterator.next()), Double
.valueOf(SafeEncoder.encode(iterator.next()))));
} }
return new ScanResult<Tuple>(newcursor, results); return new ScanResult<Tuple>(newcursor, results);
} }
public String clusterNodes() { public String clusterNodes() {
checkIsInMulti(); checkIsInMulti();
client.clusterNodes(); client.clusterNodes();
@@ -3246,4 +3266,22 @@ public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommand
return client.getStatusCodeReply(); return client.getStatusCodeReply();
} }
public List<String> pubsubChannels(String pattern) {
checkIsInMulti();
client.pubsubChannels(pattern);
return client.getMultiBulkReply();
}
public Long pubsubNumPat() {
checkIsInMulti();
client.pubsubNumPat();
return client.getIntegerReply();
}
public Map<String, String> pubsubNumSub(String... channels) {
checkIsInMulti();
client.pubsubNumSub(channels);
return BuilderFactory.STRING_MAP
.build(client.getBinaryMultiBulkReply());
}
} }

View File

@@ -635,7 +635,7 @@ public class JedisCluster implements JedisCommands, BasicCommands {
} }
@Override @Override
public Long zadd(final String key, final Map<Double, String> scoreMembers) { public Long zadd(final String key, final Map<String, Double> scoreMembers) {
return new JedisClusterCommand<Long>(connectionHandler, timeout, return new JedisClusterCommand<Long>(connectionHandler, timeout,
maxRedirections) { maxRedirections) {
@Override @Override

View File

@@ -13,9 +13,11 @@ public abstract class JedisClusterCommand<T> {
private JedisClusterConnectionHandler connectionHandler; private JedisClusterConnectionHandler connectionHandler;
private int commandTimeout; private int commandTimeout;
private int redirections; private int redirections;
// private boolean asking = false; // private boolean asking = false;
public JedisClusterCommand(JedisClusterConnectionHandler connectionHandler, int timeout, int maxRedirections) { public JedisClusterCommand(JedisClusterConnectionHandler connectionHandler,
int timeout, int maxRedirections) {
this.connectionHandler = connectionHandler; this.connectionHandler = connectionHandler;
this.commandTimeout = timeout; this.commandTimeout = timeout;
this.redirections = maxRedirections; this.redirections = maxRedirections;
@@ -27,13 +29,17 @@ public abstract class JedisClusterCommand<T> {
try { try {
if (key == null) { if (key == null) {
throw new JedisClusterException("No way to dispatch this command to Redis Cluster."); throw new JedisClusterException(
"No way to dispatch this command to Redis Cluster.");
} else if (redirections == 0) { } else if (redirections == 0) {
throw new JedisClusterMaxRedirectionsException("Too many Cluster redirections?"); throw new JedisClusterMaxRedirectionsException(
"Too many Cluster redirections?");
} }
connectionHandler.getConnectionFromSlot(JedisClusterCRC16.getSlot(key)); connectionHandler.getConnectionFromSlot(JedisClusterCRC16
.getSlot(key));
if (asking) { if (asking) {
//TODO: Pipeline asking with the original command to make it faster.... // TODO: Pipeline asking with the original command to make it
// faster....
connectionHandler.getConnection().asking(); connectionHandler.getConnection().asking();
} }
return execute(); return execute();
@@ -47,7 +53,8 @@ public abstract class JedisClusterCommand<T> {
asking = true; asking = true;
} }
redirections--; redirections--;
this.connectionHandler.assignSlotToNode(jre.getSlot(), jre.getTargetNode()); this.connectionHandler.assignSlotToNode(jre.getSlot(),
jre.getTargetNode());
return run(key); return run(key);
} }
} }

View File

@@ -5,13 +5,13 @@ import java.util.Map;
import java.util.Random; import java.util.Random;
import java.util.Set; import java.util.Set;
public abstract class JedisClusterConnectionHandler { public abstract class JedisClusterConnectionHandler {
protected Map<String, JedisPool> nodes = new HashMap<String, JedisPool>(); protected Map<String, JedisPool> nodes = new HashMap<String, JedisPool>();
protected Map<Integer, JedisPool> slots = new HashMap<Integer, JedisPool>(); protected Map<Integer, JedisPool> slots = new HashMap<Integer, JedisPool>();
abstract Jedis getConnection(); abstract Jedis getConnection();
abstract Jedis getConnectionFromSlot(int slot); abstract Jedis getConnectionFromSlot(int slot);
public JedisClusterConnectionHandler(Set<HostAndPort> nodes) { public JedisClusterConnectionHandler(Set<HostAndPort> nodes) {
@@ -24,7 +24,8 @@ public abstract class JedisClusterConnectionHandler {
private void initializeSlotsCache(Set<HostAndPort> nodes) { private void initializeSlotsCache(Set<HostAndPort> nodes) {
for (HostAndPort hostAndPort : nodes) { for (HostAndPort hostAndPort : nodes) {
JedisPool jp = new JedisPool(hostAndPort.getHost(), hostAndPort.getPort()); JedisPool jp = new JedisPool(hostAndPort.getHost(),
hostAndPort.getPort());
this.nodes.put(hostAndPort.getHost() + hostAndPort.getPort(), jp); this.nodes.put(hostAndPort.getHost() + hostAndPort.getPort(), jp);
discoverClusterNodesAndSlots(jp); discoverClusterNodesAndSlots(jp);
} }
@@ -53,7 +54,8 @@ public abstract class JedisClusterConnectionHandler {
private void processSlot(String slot, JedisPool nodePool) { private void processSlot(String slot, JedisPool nodePool) {
if (slot.contains("-")) { if (slot.contains("-")) {
String[] slotRange = slot.split("-"); String[] slotRange = slot.split("-");
for (int i = Integer.valueOf(slotRange[0]); i <= Integer.valueOf(slotRange[1]); i++) { for (int i = Integer.valueOf(slotRange[0]); i <= Integer
.valueOf(slotRange[1]); i++) {
slots.put(i, nodePool); slots.put(i, nodePool);
} }
} else { } else {
@@ -64,19 +66,19 @@ public abstract class JedisClusterConnectionHandler {
private HostAndPort getHostAndPortFromNodeLine(String nodeInfo) { private HostAndPort getHostAndPortFromNodeLine(String nodeInfo) {
String stringHostAndPort = nodeInfo.split(" ", 3)[1]; String stringHostAndPort = nodeInfo.split(" ", 3)[1];
String[] arrayHostAndPort = stringHostAndPort.split(":"); String[] arrayHostAndPort = stringHostAndPort.split(":");
return new HostAndPort(arrayHostAndPort[0], Integer.valueOf(arrayHostAndPort[1])); return new HostAndPort(arrayHostAndPort[0],
Integer.valueOf(arrayHostAndPort[1]));
} }
public void assignSlotToNode(int slot, HostAndPort targetNode) { public void assignSlotToNode(int slot, HostAndPort targetNode) {
JedisPool targetPool = nodes.get(targetNode.getHost() + targetNode.getPort()); JedisPool targetPool = nodes.get(targetNode.getHost()
+ targetNode.getPort());
slots.put(slot, targetPool); slots.put(slot, targetPool);
} }
protected JedisPool getRandomConnection() { protected JedisPool getRandomConnection() {
Object[] nodeArray = nodes.values().toArray(); Object[] nodeArray = nodes.values().toArray();
return (JedisPool) (nodeArray[new Random().nextInt(nodeArray.length)]); return (JedisPool) (nodeArray[new Random().nextInt(nodeArray.length)]);
} }
} }

View File

@@ -7,8 +7,7 @@ import java.util.Set;
/** /**
* Common interface for sharded and non-sharded Jedis * Common interface for sharded and non-sharded Jedis
*/ */
public interface public interface JedisCommands {
JedisCommands {
String set(String key, String value); String set(String key, String value);
String get(String key); String get(String key);
@@ -115,7 +114,7 @@ public interface
Long zadd(String key, double score, String member); Long zadd(String key, double score, String member);
Long zadd(String key, Map<Double, String> scoreMembers); Long zadd(String key, Map<String, Double> scoreMembers);
Set<String> zrange(String key, long start, long end); Set<String> zrange(String key, long start, long end);

View File

@@ -84,6 +84,7 @@ public class JedisPool extends Pool<Jedis> {
} }
public void returnResource(final Jedis resource) { public void returnResource(final Jedis resource) {
resource.resetState();
returnResourceObject(resource); returnResourceObject(resource);
} }
} }

View File

@@ -16,7 +16,7 @@ import redis.clients.util.SafeEncoder;
public abstract class JedisPubSub { public abstract class JedisPubSub {
private int subscribedChannels = 0; private int subscribedChannels = 0;
private Client client; private volatile Client client;
public abstract void onMessage(String channel, String message); public abstract void onMessage(String channel, String message);
@@ -41,26 +41,46 @@ public abstract class JedisPubSub {
} }
public void unsubscribe(String... channels) { public void unsubscribe(String... channels) {
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance.");
}
client.unsubscribe(channels); client.unsubscribe(channels);
client.flush(); client.flush();
} }
public void subscribe(String... channels) { public void subscribe(String... channels) {
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance.");
}
client.subscribe(channels); client.subscribe(channels);
client.flush(); client.flush();
} }
public void psubscribe(String... patterns) { public void psubscribe(String... patterns) {
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance.");
}
client.psubscribe(patterns); client.psubscribe(patterns);
client.flush(); client.flush();
} }
public void punsubscribe() { public void punsubscribe() {
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance.");
}
client.punsubscribe(); client.punsubscribe();
client.flush(); client.flush();
} }
public void punsubscribe(String... patterns) { public void punsubscribe(String... patterns) {
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance.");
}
client.punsubscribe(patterns); client.punsubscribe(patterns);
client.flush(); client.flush();
} }
@@ -84,8 +104,9 @@ public abstract class JedisPubSub {
} }
private void process(Client client) { private void process(Client client) {
do { do {
List<Object> reply = client.getObjectMultiBulkReply(); List<Object> reply = client.getRawObjectMultiBulkReply();
final Object firstObj = reply.get(0); final Object firstObj = reply.get(0);
if (!(firstObj instanceof byte[])) { if (!(firstObj instanceof byte[])) {
throw new JedisException("Unknown message type: " + firstObj); throw new JedisException("Unknown message type: " + firstObj);
@@ -138,6 +159,15 @@ public abstract class JedisPubSub {
throw new JedisException("Unknown message type: " + firstObj); throw new JedisException("Unknown message type: " + firstObj);
} }
} while (isSubscribed()); } while (isSubscribed());
/* Invalidate instance since this thread is no longer listening */
this.client = null;
/*
* Reset pipeline count because subscribe() calls would have increased
* it but nothing decremented it.
*/
client.resetPipelinedCount();
} }
public int getSubscribedChannels() { public int getSubscribedChannels() {

View File

@@ -4,7 +4,6 @@ import java.util.Set;
public class JedisRandomConnectionHandler extends JedisClusterConnectionHandler { public class JedisRandomConnectionHandler extends JedisClusterConnectionHandler {
public JedisRandomConnectionHandler(Set<HostAndPort> nodes) { public JedisRandomConnectionHandler(Set<HostAndPort> nodes) {
super(nodes); super(nodes);
} }

View File

@@ -79,6 +79,7 @@ public class JedisSentinelPool extends Pool<Jedis> {
} }
public void returnResource(final Jedis resource) { public void returnResource(final Jedis resource) {
resource.resetState();
returnResourceObject(resource); returnResourceObject(resource);
} }
@@ -100,7 +101,8 @@ public class JedisSentinelPool extends Pool<Jedis> {
if (!master.equals(currentHostMaster)) { if (!master.equals(currentHostMaster)) {
currentHostMaster = master; currentHostMaster = master;
log.info("Created JedisPool to master at " + master); log.info("Created JedisPool to master at " + master);
initPool(poolConfig, new JedisFactory(master.getHost(), master.getPort(), initPool(poolConfig,
new JedisFactory(master.getHost(), master.getPort(),
timeout, password, database)); timeout, password, database));
} }
} }

View File

@@ -2,7 +2,8 @@ package redis.clients.jedis;
import java.util.Set; import java.util.Set;
public class JedisSlotBasedConnectionHandler extends JedisClusterConnectionHandler { public class JedisSlotBasedConnectionHandler extends
JedisClusterConnectionHandler {
private Jedis currentConnection; private Jedis currentConnection;
@@ -10,22 +11,21 @@ public class JedisSlotBasedConnectionHandler extends JedisClusterConnectionHandl
super(nodes); super(nodes);
} }
public Jedis getConnection() { public Jedis getConnection() {
return currentConnection != null ? currentConnection : getRandomConnection().getResource(); return currentConnection != null ? currentConnection
: getRandomConnection().getResource();
} }
private void returnCurrentConnection() { private void returnCurrentConnection() {
if (currentConnection != null) { if (currentConnection != null) {
nodes.get(currentConnection.getClient().getHost()+currentConnection.getClient().getPort()).returnResource(currentConnection); nodes.get(
currentConnection.getClient().getHost()
+ currentConnection.getClient().getPort())
.returnResource(currentConnection);
} }
} }
@Override @Override
public void assignSlotToNode(int slot, HostAndPort targetNode) { public void assignSlotToNode(int slot, HostAndPort targetNode) {
super.assignSlotToNode(slot, targetNode); super.assignSlotToNode(slot, targetNode);
@@ -43,6 +43,4 @@ public class JedisSlotBasedConnectionHandler extends JedisClusterConnectionHandl
return connectionPool.getResource(); return connectionPool.getResource();
} }
} }

View File

@@ -1,6 +1,5 @@
package redis.clients.jedis; package redis.clients.jedis;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;

View File

@@ -1,11 +1,11 @@
package redis.clients.jedis; package redis.clients.jedis;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
/** /**
* Multikey related commands (these are split out because they are non-shardable) * Multikey related commands (these are split out because they are
* non-shardable)
*/ */
public interface MultiKeyBinaryRedisPipeline { public interface MultiKeyBinaryRedisPipeline {
@@ -39,7 +39,8 @@ public interface MultiKeyBinaryRedisPipeline {
Response<Long> smove(byte[] srckey, byte[] dstkey, byte[] member); Response<Long> smove(byte[] srckey, byte[] dstkey, byte[] member);
Response<Long> sort(byte[] key, SortingParams sortingParameters, byte[] dstkey); Response<Long> sort(byte[] key, SortingParams sortingParameters,
byte[] dstkey);
Response<Long> sort(byte[] key, byte[] dstkey); Response<Long> sort(byte[] key, byte[] dstkey);

View File

@@ -1,8 +1,6 @@
package redis.clients.jedis; package redis.clients.jedis;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Set; import java.util.Set;
public interface MultiKeyCommands { public interface MultiKeyCommands {

View File

@@ -1,12 +1,11 @@
package redis.clients.jedis; package redis.clients.jedis;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
/** /**
* Multikey related commands (these are split out because they are non-shardable) * Multikey related commands (these are split out because they are
* non-shardable)
*/ */
public interface MultiKeyCommandsPipeline { public interface MultiKeyCommandsPipeline {
Response<Long> del(String... keys); Response<Long> del(String... keys);
@@ -39,7 +38,8 @@ public interface MultiKeyCommandsPipeline {
Response<Long> smove(String srckey, String dstkey, String member); Response<Long> smove(String srckey, String dstkey, String member);
Response<Long> sort(String key, SortingParams sortingParameters, String dstkey); Response<Long> sort(String key, SortingParams sortingParameters,
String dstkey);
Response<Long> sort(String key, String dstkey); Response<Long> sort(String key, String dstkey);

View File

@@ -5,10 +5,8 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
abstract class MultiKeyPipelineBase extends PipelineBase implements abstract class MultiKeyPipelineBase extends PipelineBase implements
BasicRedisPipeline, BasicRedisPipeline, MultiKeyBinaryRedisPipeline,
MultiKeyBinaryRedisPipeline, MultiKeyCommandsPipeline, ClusterPipeline {
MultiKeyCommandsPipeline,
ClusterPipeline {
protected Client client = null; protected Client client = null;
@@ -192,14 +190,14 @@ abstract class MultiKeyPipelineBase extends PipelineBase implements
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Long> sort(String key, public Response<Long> sort(String key, SortingParams sortingParameters,
SortingParams sortingParameters, String dstkey) { String dstkey) {
client.sort(key, sortingParameters, dstkey); client.sort(key, sortingParameters, dstkey);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Long> sort(byte[] key, public Response<Long> sort(byte[] key, SortingParams sortingParameters,
SortingParams sortingParameters, byte[] dstkey) { byte[] dstkey) {
client.sort(key, sortingParameters, dstkey); client.sort(key, sortingParameters, dstkey);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
@@ -425,22 +423,26 @@ abstract class MultiKeyPipelineBase extends PipelineBase implements
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<List<String>> clusterGetKeysInSlot(final int slot, final int count) { public Response<List<String>> clusterGetKeysInSlot(final int slot,
final int count) {
client.clusterGetKeysInSlot(slot, count); client.clusterGetKeysInSlot(slot, count);
return getResponse(BuilderFactory.STRING_LIST); return getResponse(BuilderFactory.STRING_LIST);
} }
public Response<String> clusterSetSlotNode(final int slot, final String nodeId) { public Response<String> clusterSetSlotNode(final int slot,
final String nodeId) {
client.clusterSetSlotNode(slot, nodeId); client.clusterSetSlotNode(slot, nodeId);
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<String> clusterSetSlotMigrating(final int slot, final String nodeId) { public Response<String> clusterSetSlotMigrating(final int slot,
final String nodeId) {
client.clusterSetSlotMigrating(slot, nodeId); client.clusterSetSlotMigrating(slot, nodeId);
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<String> clusterSetSlotImporting(final int slot, final String nodeId) { public Response<String> clusterSetSlotImporting(final int slot,
final String nodeId) {
client.clusterSetSlotImporting(slot, nodeId); client.clusterSetSlotImporting(slot, nodeId);
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }

View File

@@ -1,10 +1,10 @@
package redis.clients.jedis; package redis.clients.jedis;
import redis.clients.jedis.exceptions.JedisDataException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import redis.clients.jedis.exceptions.JedisDataException;
public class Pipeline extends MultiKeyPipelineBase { public class Pipeline extends MultiKeyPipelineBase {
private MultiResponseBuilder currentMulti; private MultiResponseBuilder currentMulti;
@@ -19,7 +19,8 @@ public class Pipeline extends MultiKeyPipelineBase {
List<Object> values = new ArrayList<Object>(); List<Object> values = new ArrayList<Object>();
if (list.size() != responses.size()) { if (list.size() != responses.size()) {
throw new JedisDataException("Expected data size " + responses.size() + " but was " + list.size()); throw new JedisDataException("Expected data size "
+ responses.size() + " but was " + list.size());
} }
for (int i = 0; i < list.size(); i++) { for (int i = 0; i < list.size(); i++) {
@@ -43,8 +44,7 @@ public class Pipeline extends MultiKeyPipelineBase {
Response<T> lr = new Response<T>(builder); Response<T> lr = new Response<T>(builder);
currentMulti.addResponse(lr); currentMulti.addResponse(lr);
return lr; return lr;
} } else {
else{
return super.getResponse(builder); return super.getResponse(builder);
} }
} }
@@ -112,7 +112,8 @@ public class Pipeline extends MultiKeyPipelineBase {
public Response<String> multi() { public Response<String> multi() {
client.multi(); client.multi();
Response<String> response = getResponse(BuilderFactory.STRING); //Expecting OK Response<String> response = getResponse(BuilderFactory.STRING); // Expecting
// OK
currentMulti = new MultiResponseBuilder(); currentMulti = new MultiResponseBuilder();
return response; return response;
} }

View File

@@ -1,15 +1,14 @@
package redis.clients.jedis; package redis.clients.jedis;
import redis.clients.jedis.BinaryClient.LIST_POSITION; import static redis.clients.jedis.Protocol.toByteArray;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import static redis.clients.jedis.Protocol.toByteArray; import redis.clients.jedis.BinaryClient.LIST_POSITION;
abstract class PipelineBase extends Queable implements abstract class PipelineBase extends Queable implements BinaryRedisPipeline,
BinaryRedisPipeline,
RedisPipeline { RedisPipeline {
protected abstract Client getClient(String key); protected abstract Client getClient(String key);
@@ -654,7 +653,7 @@ abstract class PipelineBase extends Queable implements
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Long> zadd(String key, Map<Double, String> scoreMembers) { public Response<Long> zadd(String key, Map<String, Double> scoreMembers) {
getClient(key).zadd(key, scoreMembers); getClient(key).zadd(key, scoreMembers);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
@@ -738,14 +737,16 @@ abstract class PipelineBase extends Queable implements
return getResponse(BuilderFactory.STRING_ZSET); return getResponse(BuilderFactory.STRING_ZSET);
} }
public Response<Set<String>> zrangeByScore(String key, String min, String max, int offset, int count) { public Response<Set<String>> zrangeByScore(String key, String min,
String max, int offset, int count) {
getClient(key).zrangeByScore(key, min, max, offset, count); getClient(key).zrangeByScore(key, min, max, offset, count);
return getResponse(BuilderFactory.STRING_ZSET); return getResponse(BuilderFactory.STRING_ZSET);
} }
public Response<Set<byte[]>> zrangeByScore(byte[] key, double min, public Response<Set<byte[]>> zrangeByScore(byte[] key, double min,
double max, int offset, int count) { double max, int offset, int count) {
return zrangeByScore(key, toByteArray(min), toByteArray(max), offset, count); return zrangeByScore(key, toByteArray(min), toByteArray(max), offset,
count);
} }
public Response<Set<byte[]>> zrangeByScore(byte[] key, byte[] min, public Response<Set<byte[]>> zrangeByScore(byte[] key, byte[] min,
@@ -791,7 +792,8 @@ abstract class PipelineBase extends Queable implements
public Response<Set<Tuple>> zrangeByScoreWithScores(byte[] key, double min, public Response<Set<Tuple>> zrangeByScoreWithScores(byte[] key, double min,
double max, int offset, int count) { double max, int offset, int count) {
getClient(key).zrangeByScoreWithScores(key, toByteArray(min), toByteArray(max), offset, count); getClient(key).zrangeByScoreWithScores(key, toByteArray(min),
toByteArray(max), offset, count);
return getResponse(BuilderFactory.TUPLE_ZSET_BINARY); return getResponse(BuilderFactory.TUPLE_ZSET_BINARY);
} }
@@ -809,7 +811,8 @@ abstract class PipelineBase extends Queable implements
public Response<Set<byte[]>> zrevrangeByScore(byte[] key, double max, public Response<Set<byte[]>> zrevrangeByScore(byte[] key, double max,
double min) { double min) {
getClient(key).zrevrangeByScore(key, toByteArray(max), toByteArray(min)); getClient(key)
.zrevrangeByScore(key, toByteArray(max), toByteArray(min));
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
} }
@@ -839,7 +842,8 @@ abstract class PipelineBase extends Queable implements
public Response<Set<byte[]>> zrevrangeByScore(byte[] key, double max, public Response<Set<byte[]>> zrevrangeByScore(byte[] key, double max,
double min, int offset, int count) { double min, int offset, int count) {
getClient(key).zrevrangeByScore(key, toByteArray(max), toByteArray(min), offset, count); getClient(key).zrevrangeByScore(key, toByteArray(max),
toByteArray(min), offset, count);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
} }
@@ -863,7 +867,8 @@ abstract class PipelineBase extends Queable implements
public Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key, public Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key,
double max, double min) { double max, double min) {
getClient(key).zrevrangeByScoreWithScores(key, toByteArray(max), toByteArray(min)); getClient(key).zrevrangeByScoreWithScores(key, toByteArray(max),
toByteArray(min));
return getResponse(BuilderFactory.TUPLE_ZSET_BINARY); return getResponse(BuilderFactory.TUPLE_ZSET_BINARY);
} }
@@ -887,7 +892,8 @@ abstract class PipelineBase extends Queable implements
public Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key, public Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key,
double max, double min, int offset, int count) { double max, double min, int offset, int count) {
getClient(key).zrevrangeByScoreWithScores(key, toByteArray(max), toByteArray(min), offset, count); getClient(key).zrevrangeByScoreWithScores(key, toByteArray(max),
toByteArray(min), offset, count);
return getResponse(BuilderFactory.TUPLE_ZSET_BINARY); return getResponse(BuilderFactory.TUPLE_ZSET_BINARY);
} }
@@ -897,12 +903,14 @@ abstract class PipelineBase extends Queable implements
return getResponse(BuilderFactory.TUPLE_ZSET_BINARY); return getResponse(BuilderFactory.TUPLE_ZSET_BINARY);
} }
public Response<Set<Tuple>> zrangeWithScores(String key, long start, long end) { public Response<Set<Tuple>> zrangeWithScores(String key, long start,
long end) {
getClient(key).zrangeWithScores(key, start, end); getClient(key).zrangeWithScores(key, start, end);
return getResponse(BuilderFactory.TUPLE_ZSET); return getResponse(BuilderFactory.TUPLE_ZSET);
} }
public Response<Set<Tuple>> zrangeWithScores(byte[] key, long start, long end) { public Response<Set<Tuple>> zrangeWithScores(byte[] key, long start,
long end) {
getClient(key).zrangeWithScores(key, start, end); getClient(key).zrangeWithScores(key, start, end);
return getResponse(BuilderFactory.TUPLE_ZSET_BINARY); return getResponse(BuilderFactory.TUPLE_ZSET_BINARY);
} }
@@ -948,7 +956,8 @@ abstract class PipelineBase extends Queable implements
} }
public Response<Long> zremrangeByScore(byte[] key, double start, double end) { public Response<Long> zremrangeByScore(byte[] key, double start, double end) {
getClient(key).zremrangeByScore(key, toByteArray(start), toByteArray(end)); getClient(key).zremrangeByScore(key, toByteArray(start),
toByteArray(end));
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
@@ -1029,12 +1038,14 @@ abstract class PipelineBase extends Queable implements
return getResponse(BuilderFactory.BYTE_ARRAY); return getResponse(BuilderFactory.BYTE_ARRAY);
} }
public Response<String> migrate(String host, int port, String key, int destinationDb, int timeout) { public Response<String> migrate(String host, int port, String key,
int destinationDb, int timeout) {
getClient(key).migrate(host, port, key, destinationDb, timeout); getClient(key).migrate(host, port, key, destinationDb, timeout);
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<String> migrate(byte[] host, int port, byte[] key, int destinationDb, int timeout) { public Response<String> migrate(byte[] host, int port, byte[] key,
int destinationDb, int timeout) {
getClient(key).migrate(host, port, key, destinationDb, timeout); getClient(key).migrate(host, port, key, destinationDb, timeout);
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
@@ -1139,22 +1150,26 @@ abstract class PipelineBase extends Queable implements
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<String> set(String key, String value, String nxxx, String expx, int time) { public Response<String> set(String key, String value, String nxxx,
String expx, int time) {
getClient(key).set(key, value, nxxx, expx, time); getClient(key).set(key, value, nxxx, expx, time);
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<String> set(byte[] key, byte[] value, byte[] nxxx, byte[] expx, int time) { public Response<String> set(byte[] key, byte[] value, byte[] nxxx,
byte[] expx, int time) {
getClient(key).set(key, value, nxxx, expx, time); getClient(key).set(key, value, nxxx, expx, time);
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<Double> hincrByFloat(String key, String field, double increment) { public Response<Double> hincrByFloat(String key, String field,
double increment) {
getClient(key).hincrByFloat(key, field, increment); getClient(key).hincrByFloat(key, field, increment);
return getResponse(BuilderFactory.DOUBLE); return getResponse(BuilderFactory.DOUBLE);
} }
public Response<Double> hincrByFloat(byte[] key, byte[] field, double increment) { public Response<Double> hincrByFloat(byte[] key, byte[] field,
double increment) {
getClient(key).hincrByFloat(key, field, increment); getClient(key).hincrByFloat(key, field, increment);
return getResponse(BuilderFactory.DOUBLE); return getResponse(BuilderFactory.DOUBLE);
} }
@@ -1163,7 +1178,8 @@ abstract class PipelineBase extends Queable implements
return this.eval(script, 0, new String[0]); return this.eval(script, 0, new String[0]);
} }
public Response<String> eval(String script, List<String> keys, List<String> args) { public Response<String> eval(String script, List<String> keys,
List<String> args) {
String[] argv = Jedis.getParams(keys, args); String[] argv = Jedis.getParams(keys, args);
return this.eval(script, keys.size(), argv); return this.eval(script, keys.size(), argv);
} }
@@ -1177,7 +1193,8 @@ abstract class PipelineBase extends Queable implements
return this.evalsha(script, 0, new String[0]); return this.evalsha(script, 0, new String[0]);
} }
public Response<String> evalsha(String sha1, List<String> keys, List<String> args) { public Response<String> evalsha(String sha1, List<String> keys,
List<String> args) {
String[] argv = Jedis.getParams(keys, args); String[] argv = Jedis.getParams(keys, args);
return this.evalsha(sha1, keys.size(), argv); return this.evalsha(sha1, keys.size(), argv);
} }
@@ -1187,5 +1204,4 @@ abstract class PipelineBase extends Queable implements
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
} }

View File

@@ -1,6 +1,5 @@
package redis.clients.jedis; package redis.clients.jedis;
public abstract class PipelineBlock extends Pipeline { public abstract class PipelineBlock extends Pipeline {
public abstract void execute(); public abstract void execute();
} }

View File

@@ -48,6 +48,9 @@ public final class Protocol {
public static final String CLUSTER_SETSLOT_NODE = "node"; public static final String CLUSTER_SETSLOT_NODE = "node";
public static final String CLUSTER_SETSLOT_MIGRATING = "migrating"; public static final String CLUSTER_SETSLOT_MIGRATING = "migrating";
public static final String CLUSTER_SETSLOT_IMPORTING = "importing"; public static final String CLUSTER_SETSLOT_IMPORTING = "importing";
public static final String PUBSUB_CHANNELS= "channels";
public static final String PUBSUB_NUMSUB = "numsub";
public static final String PUBSUB_NUM_PAT = "numpat";
private Protocol() { private Protocol() {
// this prevent the class from instantiation // this prevent the class from instantiation
@@ -85,15 +88,20 @@ public final class Protocol {
// Maybe Read only first 5 bytes instead? // Maybe Read only first 5 bytes instead?
if (message.startsWith(MOVED_RESPONSE)) { if (message.startsWith(MOVED_RESPONSE)) {
String[] movedInfo = parseTargetHostAndSlot(message); String[] movedInfo = parseTargetHostAndSlot(message);
throw new JedisMovedDataException(message, new HostAndPort(movedInfo[1], Integer.valueOf(movedInfo[2])), Integer.valueOf(movedInfo[0])); throw new JedisMovedDataException(message, new HostAndPort(
movedInfo[1], Integer.valueOf(movedInfo[2])),
Integer.valueOf(movedInfo[0]));
} else if (message.startsWith(ASK_RESPONSE)) { } else if (message.startsWith(ASK_RESPONSE)) {
String[] askInfo = parseTargetHostAndSlot(message); String[] askInfo = parseTargetHostAndSlot(message);
throw new JedisAskDataException(message, new HostAndPort(askInfo[1], Integer.valueOf(askInfo[2])), Integer.valueOf(askInfo[0])); throw new JedisAskDataException(message, new HostAndPort(
askInfo[1], Integer.valueOf(askInfo[2])),
Integer.valueOf(askInfo[0]));
} }
throw new JedisDataException(message); throw new JedisDataException(message);
} }
private static String[] parseTargetHostAndSlot(String clusterRedirectResponse) { private static String[] parseTargetHostAndSlot(
String clusterRedirectResponse) {
String[] response = new String[3]; String[] response = new String[3];
String[] messageInfo = clusterRedirectResponse.split(" "); String[] messageInfo = clusterRedirectResponse.split(" ");
String[] targetHostAndPort = messageInfo[2].split(":"); String[] targetHostAndPort = messageInfo[2].split(":");
@@ -140,7 +148,8 @@ public final class Protocol {
while (offset < len) { while (offset < len) {
int size = is.read(read, offset, (len - offset)); int size = is.read(read, offset, (len - offset));
if (size == -1) if (size == -1)
throw new JedisConnectionException("It seems like server has closed the connection."); throw new JedisConnectionException(
"It seems like server has closed the connection.");
offset += size; offset += size;
} }
// read 2 more bytes for the command delimiter // read 2 more bytes for the command delimiter
@@ -195,7 +204,7 @@ public final class Protocol {
} }
public static enum Command { public static enum Command {
PING, SET, GET, QUIT, EXISTS, DEL, TYPE, FLUSHDB, KEYS, RANDOMKEY, RENAME, RENAMENX, RENAMEX, DBSIZE, EXPIRE, EXPIREAT, TTL, SELECT, MOVE, FLUSHALL, GETSET, MGET, SETNX, SETEX, MSET, MSETNX, DECRBY, DECR, INCRBY, INCR, APPEND, SUBSTR, HSET, HGET, HSETNX, HMSET, HMGET, HINCRBY, HEXISTS, HDEL, HLEN, HKEYS, HVALS, HGETALL, RPUSH, LPUSH, LLEN, LRANGE, LTRIM, LINDEX, LSET, LREM, LPOP, RPOP, RPOPLPUSH, SADD, SMEMBERS, SREM, SPOP, SMOVE, SCARD, SISMEMBER, SINTER, SINTERSTORE, SUNION, SUNIONSTORE, SDIFF, SDIFFSTORE, SRANDMEMBER, ZADD, ZRANGE, ZREM, ZINCRBY, ZRANK, ZREVRANK, ZREVRANGE, ZCARD, ZSCORE, MULTI, DISCARD, EXEC, WATCH, UNWATCH, SORT, BLPOP, BRPOP, AUTH, SUBSCRIBE, PUBLISH, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, ZCOUNT, ZRANGEBYSCORE, ZREVRANGEBYSCORE, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZUNIONSTORE, ZINTERSTORE, SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE, SHUTDOWN, INFO, MONITOR, SLAVEOF, CONFIG, STRLEN, SYNC, LPUSHX, PERSIST, RPUSHX, ECHO, LINSERT, DEBUG, BRPOPLPUSH, SETBIT, GETBIT, SETRANGE, GETRANGE, EVAL, EVALSHA, SCRIPT, SLOWLOG, OBJECT, BITCOUNT, BITOP, SENTINEL, DUMP, RESTORE, PEXPIRE, PEXPIREAT, PTTL, INCRBYFLOAT, PSETEX, CLIENT, TIME, MIGRATE, HINCRBYFLOAT, SCAN, HSCAN, SSCAN, ZSCAN, WAIT, CLUSTER, ASKING; PING, SET, GET, QUIT, EXISTS, DEL, TYPE, FLUSHDB, KEYS, RANDOMKEY, RENAME, RENAMENX, RENAMEX, DBSIZE, EXPIRE, EXPIREAT, TTL, SELECT, MOVE, FLUSHALL, GETSET, MGET, SETNX, SETEX, MSET, MSETNX, DECRBY, DECR, INCRBY, INCR, APPEND, SUBSTR, HSET, HGET, HSETNX, HMSET, HMGET, HINCRBY, HEXISTS, HDEL, HLEN, HKEYS, HVALS, HGETALL, RPUSH, LPUSH, LLEN, LRANGE, LTRIM, LINDEX, LSET, LREM, LPOP, RPOP, RPOPLPUSH, SADD, SMEMBERS, SREM, SPOP, SMOVE, SCARD, SISMEMBER, SINTER, SINTERSTORE, SUNION, SUNIONSTORE, SDIFF, SDIFFSTORE, SRANDMEMBER, ZADD, ZRANGE, ZREM, ZINCRBY, ZRANK, ZREVRANK, ZREVRANGE, ZCARD, ZSCORE, MULTI, DISCARD, EXEC, WATCH, UNWATCH, SORT, BLPOP, BRPOP, AUTH, SUBSCRIBE, PUBLISH, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, PUBSUB, ZCOUNT, ZRANGEBYSCORE, ZREVRANGEBYSCORE, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZUNIONSTORE, ZINTERSTORE, SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE, SHUTDOWN, INFO, MONITOR, SLAVEOF, CONFIG, STRLEN, SYNC, LPUSHX, PERSIST, RPUSHX, ECHO, LINSERT, DEBUG, BRPOPLPUSH, SETBIT, GETBIT, SETRANGE, GETRANGE, EVAL, EVALSHA, SCRIPT, SLOWLOG, OBJECT, BITCOUNT, BITOP, SENTINEL, DUMP, RESTORE, PEXPIRE, PEXPIREAT, PTTL, INCRBYFLOAT, PSETEX, CLIENT, TIME, MIGRATE, HINCRBYFLOAT, SCAN, HSCAN, SSCAN, ZSCAN, WAIT, CLUSTER, ASKING;
public final byte[] raw; public final byte[] raw;
@@ -205,8 +214,7 @@ public final class Protocol {
} }
public static enum Keyword { public static enum Keyword {
AGGREGATE, ALPHA, ASC, BY, DESC, GET, LIMIT, MESSAGE, NO, NOSORT, PMESSAGE, PSUBSCRIBE, PUNSUBSCRIBE, OK, ONE, QUEUED, SET, STORE, SUBSCRIBE, UNSUBSCRIBE, WEIGHTS, WITHSCORES, RESETSTAT, RESET, FLUSH, EXISTS, LOAD, KILL, LEN, REFCOUNT, ENCODING, IDLETIME, AND, OR, XOR, NOT, AGGREGATE, ALPHA, ASC, BY, DESC, GET, LIMIT, MESSAGE, NO, NOSORT, PMESSAGE, PSUBSCRIBE, PUNSUBSCRIBE, OK, ONE, QUEUED, SET, STORE, SUBSCRIBE, UNSUBSCRIBE, WEIGHTS, WITHSCORES, RESETSTAT, RESET, FLUSH, EXISTS, LOAD, KILL, LEN, REFCOUNT, ENCODING, IDLETIME, AND, OR, XOR, NOT, GETNAME, SETNAME, LIST, MATCH, COUNT;
GETNAME, SETNAME,LIST, MATCH, COUNT;
public final byte[] raw; public final byte[] raw;
Keyword() { Keyword() {

View File

@@ -32,10 +32,7 @@ public interface RedisPipeline {
Response<Boolean> getbit(String key, long offset); Response<Boolean> getbit(String key, long offset);
Response<String> getrange(String key, long startOffset, long endOffset);
Response<String> getrange(String key, long startOffset,
long endOffset);
Response<String> getSet(String key, String value); Response<String> getSet(String key, String value);
@@ -118,8 +115,7 @@ public interface RedisPipeline {
Response<List<String>> sort(String key); Response<List<String>> sort(String key);
Response<List<String>> sort(String key, Response<List<String>> sort(String key, SortingParams sortingParameters);
SortingParams sortingParameters);
Response<String> spop(String key); Response<String> spop(String key);
@@ -145,14 +141,12 @@ public interface RedisPipeline {
Response<Set<String>> zrange(String key, long start, long end); Response<Set<String>> zrange(String key, long start, long end);
Response<Set<String>> zrangeByScore(String key, double min, Response<Set<String>> zrangeByScore(String key, double min, double max);
double max);
Response<Set<String>> zrangeByScore(String key, String min, Response<Set<String>> zrangeByScore(String key, String min, String max);
String max);
Response<Set<String>> zrangeByScore(String key, double min, Response<Set<String>> zrangeByScore(String key, double min, double max,
double max, int offset, int count); int offset, int count);
Response<Set<Tuple>> zrangeByScoreWithScores(String key, double min, Response<Set<Tuple>> zrangeByScoreWithScores(String key, double min,
double max); double max);
@@ -160,21 +154,19 @@ public interface RedisPipeline {
Response<Set<Tuple>> zrangeByScoreWithScores(String key, double min, Response<Set<Tuple>> zrangeByScoreWithScores(String key, double min,
double max, int offset, int count); double max, int offset, int count);
Response<Set<String>> zrevrangeByScore(String key, double max, Response<Set<String>> zrevrangeByScore(String key, double max, double min);
Response<Set<String>> zrevrangeByScore(String key, String max, String min);
Response<Set<String>> zrevrangeByScore(String key, double max, double min,
int offset, int count);
Response<Set<Tuple>> zrevrangeByScoreWithScores(String key, double max,
double min); double min);
Response<Set<String>> zrevrangeByScore(String key, String max, Response<Set<Tuple>> zrevrangeByScoreWithScores(String key, double max,
String min);
Response<Set<String>> zrevrangeByScore(String key, double max,
double min, int offset, int count); double min, int offset, int count);
Response<Set<Tuple>> zrevrangeByScoreWithScores(String key,
double max, double min);
Response<Set<Tuple>> zrevrangeByScoreWithScores(String key,
double max, double min, int offset, int count);
Response<Set<Tuple>> zrangeWithScores(String key, long start, long end); Response<Set<Tuple>> zrangeWithScores(String key, long start, long end);
Response<Long> zrank(String key, String member); Response<Long> zrank(String key, String member);
@@ -187,8 +179,7 @@ public interface RedisPipeline {
Response<Set<String>> zrevrange(String key, long start, long end); Response<Set<String>> zrevrange(String key, long start, long end);
Response<Set<Tuple>> zrevrangeWithScores(String key, long start, Response<Set<Tuple>> zrevrangeWithScores(String key, long start, long end);
long end);
Response<Long> zrevrank(String key, String member); Response<Long> zrevrank(String key, String member);

View File

@@ -1,14 +1,14 @@
package redis.clients.jedis; package redis.clients.jedis;
import redis.clients.jedis.BinaryClient.LIST_POSITION;
import redis.clients.util.Hashing;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Set; import java.util.Set;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import redis.clients.jedis.BinaryClient.LIST_POSITION;
import redis.clients.util.Hashing;
public class ShardedJedis extends BinaryShardedJedis implements JedisCommands { public class ShardedJedis extends BinaryShardedJedis implements JedisCommands {
public ShardedJedis(List<JedisShardInfo> shards) { public ShardedJedis(List<JedisShardInfo> shards) {
super(shards); super(shards);
@@ -327,7 +327,7 @@ public class ShardedJedis extends BinaryShardedJedis implements JedisCommands {
return j.zadd(key, score, member); return j.zadd(key, score, member);
} }
public Long zadd(String key, Map<Double, String> scoreMembers) { public Long zadd(String key, Map<String, Double> scoreMembers) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zadd(key, scoreMembers); return j.zadd(key, scoreMembers);
} }

View File

@@ -48,8 +48,8 @@ public class ShardedJedisPipeline extends PipelineBase {
/** /**
* Syncronize pipeline by reading all responses. This operation closes the * Syncronize pipeline by reading all responses. This operation closes the
* pipeline. Whenever possible try to avoid using this version and use * pipeline. Whenever possible try to avoid using this version and use
* ShardedJedisPipeline.sync() as it won't go through all the responses and generate the * ShardedJedisPipeline.sync() as it won't go through all the responses and
* right response type (usually it is a waste of time). * generate the right response type (usually it is a waste of time).
* *
* @return A list of all the responses in the order you executed them. * @return A list of all the responses in the order you executed them.
*/ */
@@ -62,8 +62,8 @@ public class ShardedJedisPipeline extends PipelineBase {
} }
/** /**
* This method will be removed in Jedis 3.0. Use the methods that return Response's and call * This method will be removed in Jedis 3.0. Use the methods that return
* sync(). * Response's and call sync().
*/ */
@Deprecated @Deprecated
public void execute() { public void execute() {

View File

@@ -6,7 +6,8 @@ import java.util.List;
import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.exceptions.JedisDataException;
/** /**
* Transaction is nearly identical to Pipeline, only differences are the multi/discard behaviors * Transaction is nearly identical to Pipeline, only differences are the
* multi/discard behaviors
*/ */
public class Transaction extends MultiKeyPipelineBase { public class Transaction extends MultiKeyPipelineBase {

View File

@@ -5,15 +5,18 @@ import redis.clients.jedis.HostAndPort;
public class JedisAskDataException extends JedisRedirectionException { public class JedisAskDataException extends JedisRedirectionException {
private static final long serialVersionUID = 3878126572474819403L; private static final long serialVersionUID = 3878126572474819403L;
public JedisAskDataException(Throwable cause, HostAndPort targetHost, int slot) { public JedisAskDataException(Throwable cause, HostAndPort targetHost,
int slot) {
super(cause, targetHost, slot); super(cause, targetHost, slot);
} }
public JedisAskDataException(String message, Throwable cause, HostAndPort targetHost, int slot) { public JedisAskDataException(String message, Throwable cause,
HostAndPort targetHost, int slot) {
super(message, cause, targetHost, slot); super(message, cause, targetHost, slot);
} }
public JedisAskDataException(String message, HostAndPort targetHost, int slot) { public JedisAskDataException(String message, HostAndPort targetHost,
int slot) {
super(message, targetHost, slot); super(message, targetHost, slot);
} }

View File

@@ -1,6 +1,5 @@
package redis.clients.jedis.exceptions; package redis.clients.jedis.exceptions;
public class JedisClusterException extends JedisDataException { public class JedisClusterException extends JedisDataException {
private static final long serialVersionUID = 3878126572474819403L; private static final long serialVersionUID = 3878126572474819403L;

View File

@@ -1,6 +1,5 @@
package redis.clients.jedis.exceptions; package redis.clients.jedis.exceptions;
public class JedisClusterMaxRedirectionsException extends JedisDataException { public class JedisClusterMaxRedirectionsException extends JedisDataException {
private static final long serialVersionUID = 3878126572474819403L; private static final long serialVersionUID = 3878126572474819403L;

View File

@@ -1,6 +1,5 @@
package redis.clients.jedis.exceptions; package redis.clients.jedis.exceptions;
public class JedisException extends RuntimeException { public class JedisException extends RuntimeException {
private static final long serialVersionUID = -2946266495682282677L; private static final long serialVersionUID = -2946266495682282677L;

View File

@@ -2,20 +2,21 @@ package redis.clients.jedis.exceptions;
import redis.clients.jedis.HostAndPort; import redis.clients.jedis.HostAndPort;
public class JedisMovedDataException extends JedisRedirectionException { public class JedisMovedDataException extends JedisRedirectionException {
private static final long serialVersionUID = 3878126572474819403L; private static final long serialVersionUID = 3878126572474819403L;
public JedisMovedDataException(String message, HostAndPort targetNode,
public JedisMovedDataException(String message, HostAndPort targetNode, int slot) { int slot) {
super(message, targetNode, slot); super(message, targetNode, slot);
} }
public JedisMovedDataException(Throwable cause, HostAndPort targetNode, int slot) { public JedisMovedDataException(Throwable cause, HostAndPort targetNode,
int slot) {
super(cause, targetNode, slot); super(cause, targetNode, slot);
} }
public JedisMovedDataException(String message, Throwable cause, HostAndPort targetNode, int slot) { public JedisMovedDataException(String message, Throwable cause,
HostAndPort targetNode, int slot) {
super(message, cause, targetNode, slot); super(message, cause, targetNode, slot);
} }
} }

View File

@@ -2,26 +2,28 @@ package redis.clients.jedis.exceptions;
import redis.clients.jedis.HostAndPort; import redis.clients.jedis.HostAndPort;
public class JedisRedirectionException extends JedisDataException { public class JedisRedirectionException extends JedisDataException {
private static final long serialVersionUID = 3878126572474819403L; private static final long serialVersionUID = 3878126572474819403L;
private HostAndPort targetNode; private HostAndPort targetNode;
private int slot; private int slot;
public JedisRedirectionException(String message, HostAndPort targetNode, int slot) { public JedisRedirectionException(String message, HostAndPort targetNode,
int slot) {
super(message); super(message);
this.targetNode = targetNode; this.targetNode = targetNode;
this.slot = slot; this.slot = slot;
} }
public JedisRedirectionException(Throwable cause, HostAndPort targetNode, int slot) { public JedisRedirectionException(Throwable cause, HostAndPort targetNode,
int slot) {
super(cause); super(cause);
this.targetNode = targetNode; this.targetNode = targetNode;
this.slot = slot; this.slot = slot;
} }
public JedisRedirectionException(String message, Throwable cause, HostAndPort targetNode, int slot) { public JedisRedirectionException(String message, Throwable cause,
HostAndPort targetNode, int slot) {
super(message, cause); super(message, cause);
this.targetNode = targetNode; this.targetNode = targetNode;
this.slot = slot; this.slot = slot;

View File

@@ -69,8 +69,8 @@ public class JedisByteHashMap implements Map<byte[], byte[]>, Cloneable,
while (iterator.hasNext()) { while (iterator.hasNext()) {
Entry<? extends byte[], ? extends byte[]> next = (Entry<? extends byte[], ? extends byte[]>) iterator Entry<? extends byte[], ? extends byte[]> next = (Entry<? extends byte[], ? extends byte[]>) iterator
.next(); .next();
internalMap.put(new ByteArrayWrapper(next.getKey()), next internalMap.put(new ByteArrayWrapper(next.getKey()),
.getValue()); next.getValue());
} }
} }

View File

@@ -11,8 +11,10 @@ public class JedisClusterCRC16 {
boolean bit = ((b >> (7 - i) & 1) == 1); boolean bit = ((b >> (7 - i) & 1) == 1);
boolean c15 = ((crc >> 15 & 1) == 1); boolean c15 = ((crc >> 15 & 1) == 1);
crc <<= 1; crc <<= 1;
// If coefficient of bit and remainder polynomial = 1 xor crc with polynomial // If coefficient of bit and remainder polynomial = 1 xor crc
if (c15 ^ bit) crc ^= polynomial; // with polynomial
if (c15 ^ bit)
crc ^= polynomial;
} }
} }

View File

@@ -1,11 +1,13 @@
package redis.clients.util; package redis.clients.util;
import java.io.*; import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/** /**
* The class implements a buffered output stream without synchronization * The class implements a buffered output stream without synchronization There
* There are also special operations like in-place string encoding. * are also special operations like in-place string encoding. This stream fully
* This stream fully ignore mark/reset and should not be used outside Jedis * ignore mark/reset and should not be used outside Jedis
*/ */
public final class RedisOutputStream extends FilterOutputStream { public final class RedisOutputStream extends FilterOutputStream {
protected final byte buf[]; protected final byte buf[];
@@ -42,7 +44,8 @@ public final class RedisOutputStream extends FilterOutputStream {
write(b, 0, b.length); write(b, 0, b.length);
} }
public void write(final byte b[], final int off, final int len) throws IOException { public void write(final byte b[], final int off, final int len)
throws IOException {
if (len >= buf.length) { if (len >= buf.length) {
flushBuffer(); flushBuffer();
out.write(b, off, len); out.write(b, off, len);
@@ -106,7 +109,8 @@ public final class RedisOutputStream extends FilterOutputStream {
int i; int i;
for (i = 0; i < strLen; i++) { for (i = 0; i < strLen; i++) {
char c = str.charAt(i); char c = str.charAt(i);
if (!(c < 0x80)) break; if (!(c < 0x80))
break;
buf[count++] = (byte) c; buf[count++] = (byte) c;
if (count == buf.length) { if (count == buf.length) {
flushBuffer(); flushBuffer();
@@ -148,46 +152,37 @@ public final class RedisOutputStream extends FilterOutputStream {
writeCrLf(); writeCrLf();
} }
private final static int[] sizeTable = {9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, Integer.MAX_VALUE}; private final static int[] sizeTable = { 9, 99, 999, 9999, 99999, 999999,
9999999, 99999999, 999999999, Integer.MAX_VALUE };
private final static byte[] DigitTens = { private final static byte[] DigitTens = { '0', '0', '0', '0', '0', '0',
'0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1',
'1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '3', '3',
'2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '3', '3', '3', '3', '3', '3', '3', '3', '4', '4', '4', '4', '4',
'3', '3', '3', '3', '3', '3', '3', '3', '3', '3', '4', '4', '4', '4', '4', '5', '5', '5', '5', '5', '5', '5', '5',
'4', '4', '4', '4', '4', '4', '4', '4', '4', '4', '5', '5', '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', '7',
'5', '5', '5', '5', '5', '5', '5', '5', '5', '5', '7', '7', '7', '7', '7', '7', '7', '7', '7', '8', '8', '8', '8',
'6', '6', '6', '6', '6', '6', '6', '6', '6', '6', '8', '8', '8', '8', '8', '8', '9', '9', '9', '9', '9', '9', '9',
'7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '9', '9', '9', };
'8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
'9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
};
private final static byte[] DigitOnes = { private final static byte[] DigitOnes = { '0', '1', '2', '3', '4', '5',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '7', '8', '9', };
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
};
private final static byte[] digits = { private final static byte[] digits = { '0', '1', '2', '3', '4', '5', '6',
'0', '1', '2', '3', '4', '5', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'6', '7', '8', '9', 'a', 'b', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'c', 'd', 'e', 'f', 'g', 'h', 'x', 'y', 'z' };
'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z'
};
public void writeIntCrLf(int value) throws IOException { public void writeIntCrLf(int value) throws IOException {
if (value < 0) { if (value < 0) {
write('-'); write((byte) '-');
value = -value; value = -value;
} }
@@ -216,7 +211,8 @@ public final class RedisOutputStream extends FilterOutputStream {
r = value - ((q << 3) + (q << 1)); r = value - ((q << 3) + (q << 1));
buf[--charPos] = digits[r]; buf[--charPos] = digits[r];
value = q; value = q;
if (value == 0) break; if (value == 0)
break;
} }
count += size; count += size;

View File

@@ -57,11 +57,14 @@ public class Sharded<R, S extends ShardInfo<R>> {
final S shardInfo = shards.get(i); final S shardInfo = shards.get(i);
if (shardInfo.getName() == null) if (shardInfo.getName() == null)
for (int n = 0; n < 160 * shardInfo.getWeight(); n++) { for (int n = 0; n < 160 * shardInfo.getWeight(); n++) {
nodes.put(this.algo.hash("SHARD-" + i + "-NODE-" + n), shardInfo); nodes.put(this.algo.hash("SHARD-" + i + "-NODE-" + n),
shardInfo);
} }
else else
for (int n = 0; n < 160 * shardInfo.getWeight(); n++) { for (int n = 0; n < 160 * shardInfo.getWeight(); n++) {
nodes.put(this.algo.hash(shardInfo.getName() + "*" + shardInfo.getWeight() + n), shardInfo); nodes.put(
this.algo.hash(shardInfo.getName() + "*"
+ shardInfo.getWeight() + n), shardInfo);
} }
resources.put(shardInfo, shardInfo.createResource()); resources.put(shardInfo, shardInfo.createResource());
} }
@@ -113,4 +116,3 @@ public class Sharded<R, S extends ShardInfo<R>> {
return Collections.unmodifiableCollection(resources.values()); return Collections.unmodifiableCollection(resources.values());
} }
} }

View File

@@ -11,6 +11,7 @@ import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis; import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Transaction;
import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisConnectionException;
public class JedisPoolTest extends Assert { public class JedisPoolTest extends Assert {
@@ -92,8 +93,8 @@ public class JedisPoolTest extends Assert {
public void securePool() { public void securePool() {
JedisPoolConfig config = new JedisPoolConfig(); JedisPoolConfig config = new JedisPoolConfig();
config.setTestOnBorrow(true); config.setTestOnBorrow(true);
JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(), 2000, JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(),
"foobared"); 2000, "foobared");
Jedis jedis = pool.getResource(); Jedis jedis = pool.getResource();
jedis.set("foo", "bar"); jedis.set("foo", "bar");
pool.returnResource(jedis); pool.returnResource(jedis);
@@ -176,4 +177,25 @@ public class JedisPoolTest extends Assert {
pool0.returnResource(jedis); pool0.returnResource(jedis);
pool0.destroy(); pool0.destroy();
} }
@Test
public void returnResourceShouldResetState() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(),
2000, "foobared");
Jedis jedis = pool.getResource();
jedis.set("hello", "jedis");
Transaction t = jedis.multi();
t.set("hello", "world");
pool.returnResource(jedis);
Jedis jedis2 = pool.getResource();
assertTrue(jedis == jedis2);
assertEquals("jedis", jedis2.get("hello"));
pool.returnResource(jedis2);
pool.destroy();
}
} }

View File

@@ -13,6 +13,7 @@ import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis; import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub; import redis.clients.jedis.JedisPubSub;
import redis.clients.jedis.JedisSentinelPool; import redis.clients.jedis.JedisSentinelPool;
import redis.clients.jedis.Transaction;
public class JedisSentinelPoolTest extends JedisTestBase { public class JedisSentinelPoolTest extends JedisTestBase {
private static final String MASTER_NAME = "mymaster"; private static final String MASTER_NAME = "mymaster";
@@ -150,4 +151,24 @@ public class JedisSentinelPoolTest extends JedisTestBase {
} }
} }
@Test
public void returnResourceShouldResetState() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1);
config.setBlockWhenExhausted(false);
JedisSentinelPool pool = new JedisSentinelPool(MASTER_NAME, sentinels,
config, 1000, "foobared", 2);
Jedis jedis = pool.getResource();
jedis.set("hello", "jedis");
Transaction t = jedis.multi();
t.set("hello", "world");
pool.returnResource(jedis);
Jedis jedis2 = pool.getResource();
assertTrue(jedis == jedis2);
assertEquals("jedis", jedis2.get("hello"));
pool.returnResource(jedis2);
pool.destroy();
}
} }

View File

@@ -116,14 +116,18 @@ public class PipeliningTest extends Assert {
Pipeline p = jedis.pipelined(); Pipeline p = jedis.pipelined();
Response<Map<byte[], byte[]>> fmap = p.hgetAll("key".getBytes()); Response<Map<byte[], byte[]>> fmap = p.hgetAll("key".getBytes());
Response<Set<byte[]>> fkeys = p.hkeys("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[]>> fordered = p.hmget("key".getBytes(),
"f22".getBytes(), "f1".getBytes());
Response<List<byte[]>> fvals = p.hvals("key".getBytes()); Response<List<byte[]>> fvals = p.hvals("key".getBytes());
p.sync(); p.sync();
assertNotNull(fmap.get()); assertNotNull(fmap.get());
// we have to do these strange contortions because byte[] is not a very good key // we have to do these strange contortions because byte[] is not a very
// for a java Map. It only works with equality (you need the exact key object to retrieve // good key
// the value) I recommend we switch to using ByteBuffer or something similar: // 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 // http://stackoverflow.com/questions/1058149/using-a-byte-array-as-hashmap-key-java
Map<byte[], byte[]> map = fmap.get(); Map<byte[], byte[]> map = fmap.get();
Set<byte[]> mapKeys = map.keySet(); Set<byte[]> mapKeys = map.keySet();
@@ -131,17 +135,20 @@ public class PipeliningTest extends Assert {
byte[] firstMapKey = iterMap.next(); byte[] firstMapKey = iterMap.next();
byte[] secondMapKey = iterMap.next(); byte[] secondMapKey = iterMap.next();
assertFalse(iterMap.hasNext()); assertFalse(iterMap.hasNext());
verifyHasBothValues(firstMapKey, secondMapKey, "f1".getBytes(), "f22".getBytes()); verifyHasBothValues(firstMapKey, secondMapKey, "f1".getBytes(),
"f22".getBytes());
byte[] firstMapValue = map.get(firstMapKey); byte[] firstMapValue = map.get(firstMapKey);
byte[] secondMapValue = map.get(secondMapKey); byte[] secondMapValue = map.get(secondMapKey);
verifyHasBothValues(firstMapValue, secondMapValue, "v111".getBytes(), "v2222".getBytes()); verifyHasBothValues(firstMapValue, secondMapValue, "v111".getBytes(),
"v2222".getBytes());
assertNotNull(fkeys.get()); assertNotNull(fkeys.get());
Iterator<byte[]> iter = fkeys.get().iterator(); Iterator<byte[]> iter = fkeys.get().iterator();
byte[] firstKey = iter.next(); byte[] firstKey = iter.next();
byte[] secondKey = iter.next(); byte[] secondKey = iter.next();
assertFalse(iter.hasNext()); assertFalse(iter.hasNext());
verifyHasBothValues(firstKey, secondKey, "f1".getBytes(), "f22".getBytes()); verifyHasBothValues(firstKey, secondKey, "f1".getBytes(),
"f22".getBytes());
assertNotNull(fordered.get()); assertNotNull(fordered.get());
assertArrayEquals("v2222".getBytes(), fordered.get().get(0)); assertArrayEquals("v2222".getBytes(), fordered.get().get(0));
@@ -151,13 +158,17 @@ public class PipeliningTest extends Assert {
assertEquals(2, fvals.get().size()); assertEquals(2, fvals.get().size());
byte[] firstValue = fvals.get().get(0); byte[] firstValue = fvals.get().get(0);
byte[] secondValue = fvals.get().get(1); byte[] secondValue = fvals.get().get(1);
verifyHasBothValues(firstValue, secondValue, "v111".getBytes(), "v2222".getBytes()); verifyHasBothValues(firstValue, secondValue, "v111".getBytes(),
"v2222".getBytes());
} }
private void verifyHasBothValues(byte[] firstKey, byte[] secondKey, byte[] value1, byte[] value2) { private void verifyHasBothValues(byte[] firstKey, byte[] secondKey,
byte[] value1, byte[] value2) {
assertFalse(Arrays.equals(firstKey, secondKey)); assertFalse(Arrays.equals(firstKey, secondKey));
assertTrue(Arrays.equals(firstKey, value1) || Arrays.equals(firstKey, value2)); assertTrue(Arrays.equals(firstKey, value1)
assertTrue(Arrays.equals(secondKey, value1) || Arrays.equals(secondKey, value2)); || Arrays.equals(firstKey, value2));
assertTrue(Arrays.equals(secondKey, value1)
|| Arrays.equals(secondKey, value2));
} }
@Test @Test
@@ -178,7 +189,6 @@ public class PipeliningTest extends Assert {
assertNull(score.get()); assertNull(score.get());
} }
@Test(expected = JedisDataException.class) @Test(expected = JedisDataException.class)
public void pipelineResponseWithinPipeline() { public void pipelineResponseWithinPipeline() {
jedis.set("string", "foo"); jedis.set("string", "foo");
@@ -193,8 +203,8 @@ public class PipeliningTest extends Assert {
public void pipelineWithPubSub() { public void pipelineWithPubSub() {
Pipeline pipelined = jedis.pipelined(); Pipeline pipelined = jedis.pipelined();
Response<Long> p1 = pipelined.publish("foo", "bar"); Response<Long> p1 = pipelined.publish("foo", "bar");
Response<Long> p2 = pipelined.publish("foo".getBytes(), "bar" Response<Long> p2 = pipelined.publish("foo".getBytes(),
.getBytes()); "bar".getBytes());
pipelined.sync(); pipelined.sync();
assertEquals(0, p1.get().longValue()); assertEquals(0, p1.get().longValue());
assertEquals(0, p2.get().longValue()); assertEquals(0, p2.get().longValue());
@@ -284,9 +294,11 @@ public class PipeliningTest extends Assert {
Pipeline p = jedis.pipelined(); Pipeline p = jedis.pipelined();
p.set(key, "0"); p.set(key, "0");
Response<String> result0 = p.eval(script, Arrays.asList(key), Arrays.asList(arg)); Response<String> result0 = p.eval(script, Arrays.asList(key),
Arrays.asList(arg));
p.incr(key); p.incr(key);
Response<String> result1 = p.eval(script, Arrays.asList(key), Arrays.asList(arg)); Response<String> result1 = p.eval(script, Arrays.asList(key),
Arrays.asList(arg));
Response<String> result2 = p.get(key); Response<String> result2 = p.get(key);
p.sync(); p.sync();
@@ -320,9 +332,11 @@ public class PipeliningTest extends Assert {
Pipeline p = jedis.pipelined(); Pipeline p = jedis.pipelined();
p.set(key, "0"); p.set(key, "0");
Response<String> result0 = p.evalsha(sha1, Arrays.asList(key), Arrays.asList(arg)); Response<String> result0 = p.evalsha(sha1, Arrays.asList(key),
Arrays.asList(arg));
p.incr(key); p.incr(key);
Response<String> result1 = p.evalsha(sha1, Arrays.asList(key), Arrays.asList(arg)); Response<String> result1 = p.evalsha(sha1, Arrays.asList(key),
Arrays.asList(arg));
Response<String> result2 = p.get(key); Response<String> result2 = p.get(key);
p.sync(); p.sync();

View File

@@ -53,7 +53,8 @@ public class ShardedJedisTest extends Assert {
@Test @Test
public void trySharding() { public void trySharding() {
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(); List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
JedisShardInfo si = new JedisShardInfo(redis1.getHost(), redis1.getPort()); JedisShardInfo si = new JedisShardInfo(redis1.getHost(),
redis1.getPort());
si.setPassword("foobared"); si.setPassword("foobared");
shards.add(si); shards.add(si);
si = new JedisShardInfo(redis2.getHost(), redis2.getPort()); si = new JedisShardInfo(redis2.getHost(), redis2.getPort());
@@ -80,7 +81,8 @@ public class ShardedJedisTest extends Assert {
@Test @Test
public void tryShardingWithMurmure() { public void tryShardingWithMurmure() {
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(); List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
JedisShardInfo si = new JedisShardInfo(redis1.getHost(), redis1.getPort()); JedisShardInfo si = new JedisShardInfo(redis1.getHost(),
redis1.getPort());
si.setPassword("foobared"); si.setPassword("foobared");
shards.add(si); shards.add(si);
si = new JedisShardInfo(redis2.getHost(), redis2.getPort()); si = new JedisShardInfo(redis2.getHost(), redis2.getPort());
@@ -264,8 +266,8 @@ public class ShardedJedisTest extends Assert {
.toString(i)); .toString(i));
JedisShardInfo jedisShardInfo2 = sharded2.getShardInfo(Integer JedisShardInfo jedisShardInfo2 = sharded2.getShardInfo(Integer
.toString(i)); .toString(i));
assertEquals(shards.indexOf(jedisShardInfo), otherShards assertEquals(shards.indexOf(jedisShardInfo),
.indexOf(jedisShardInfo2)); otherShards.indexOf(jedisShardInfo2));
} }
} }

View File

@@ -21,7 +21,8 @@ public class HashingBenchmark {
public static void main(String[] args) throws UnknownHostException, public static void main(String[] args) throws UnknownHostException,
IOException { IOException {
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(); List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
JedisShardInfo shard = new JedisShardInfo(hnp1.getHost(), hnp1.getPort()); JedisShardInfo shard = new JedisShardInfo(hnp1.getHost(),
hnp1.getPort());
shard.setPassword("foobared"); shard.setPassword("foobared");
shards.add(shard); shards.add(shard);
shard = new JedisShardInfo(hnp2.getHost(), hnp2.getPort()); shard = new JedisShardInfo(hnp2.getHost(), hnp2.getPort());

View File

@@ -1,14 +1,15 @@
package redis.clients.jedis.tests.commands; package redis.clients.jedis.tests.commands;
import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.Protocol.Keyword;
import redis.clients.jedis.exceptions.JedisDataException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.Protocol.Keyword;
import redis.clients.jedis.exceptions.JedisDataException;
public class BinaryValuesCommandsTest extends JedisCommandTestBase { public class BinaryValuesCommandsTest extends JedisCommandTestBase {
byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 };
byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; byte[] bbar = { 0x05, 0x06, 0x07, 0x08 };
@@ -57,7 +58,8 @@ public class BinaryValuesCommandsTest extends JedisCommandTestBase {
String status = jedis.set(bfoo, binaryValue); String status = jedis.set(bfoo, binaryValue);
assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); assertTrue(Keyword.OK.name().equalsIgnoreCase(status));
// nx should fail if value exists // nx should fail if value exists
String statusFail = jedis.set(bfoo, binaryValue, bnx, bex, expireSeconds); String statusFail = jedis.set(bfoo, binaryValue, bnx, bex,
expireSeconds);
assertNull(statusFail); assertNull(statusFail);
byte[] value = jedis.get(bfoo); byte[] value = jedis.get(bfoo);
@@ -71,7 +73,8 @@ public class BinaryValuesCommandsTest extends JedisCommandTestBase {
String status = jedis.set(bfoo, binaryValue); String status = jedis.set(bfoo, binaryValue);
assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); assertTrue(Keyword.OK.name().equalsIgnoreCase(status));
// nx should fail if value exists // nx should fail if value exists
String statusSuccess = jedis.set(bfoo, binaryValue, bxx, bex, expireSeconds); String statusSuccess = jedis.set(bfoo, binaryValue, bxx, bex,
expireSeconds);
assertTrue(Keyword.OK.name().equalsIgnoreCase(statusSuccess)); assertTrue(Keyword.OK.name().equalsIgnoreCase(statusSuccess));
byte[] value = jedis.get(bfoo); byte[] value = jedis.get(bfoo);
@@ -83,7 +86,8 @@ public class BinaryValuesCommandsTest extends JedisCommandTestBase {
@Test @Test
public void setFailIfNotExistAndGet() { public void setFailIfNotExistAndGet() {
// xx should fail if value does NOT exists // xx should fail if value does NOT exists
String statusFail = jedis.set(bfoo, binaryValue, bxx, bex, expireSeconds); String statusFail = jedis.set(bfoo, binaryValue, bxx, bex,
expireSeconds);
assertNull(statusFail); assertNull(statusFail);
} }
@@ -95,7 +99,6 @@ public class BinaryValuesCommandsTest extends JedisCommandTestBase {
assertTrue(ttl > 0 && ttl <= expireSeconds); assertTrue(ttl > 0 && ttl <= expireSeconds);
} }
@Test @Test
public void setAndExpire() { public void setAndExpire() {
String status = jedis.set(bfoo, binaryValue, bnx, bex, expireSeconds); String status = jedis.set(bfoo, binaryValue, bnx, bex, expireSeconds);
@@ -104,7 +107,6 @@ public class BinaryValuesCommandsTest extends JedisCommandTestBase {
assertTrue(ttl > 0 && ttl <= expireSeconds); assertTrue(ttl > 0 && ttl <= expireSeconds);
} }
@Test @Test
public void getSet() { public void getSet() {
byte[] value = jedis.getSet(bfoo, binaryValue); byte[] value = jedis.getSet(bfoo, binaryValue);
@@ -263,15 +265,13 @@ public class BinaryValuesCommandsTest extends JedisCommandTestBase {
assertTrue(Arrays.equals(first512, rfirst512)); assertTrue(Arrays.equals(first512, rfirst512));
byte[] last512 = new byte[512]; byte[] last512 = new byte[512];
System System.arraycopy(binaryValue, binaryValue.length - 512, last512, 0, 512);
.arraycopy(binaryValue, binaryValue.length - 512, last512, 0,
512);
assertTrue(Arrays.equals(last512, jedis.substr(bfoo, -512, -1))); 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, assertTrue(Arrays.equals(last512,
binaryValue.length - 512, 100000))); jedis.substr(bfoo, binaryValue.length - 512, 100000)));
} }
@Test @Test

View File

@@ -51,8 +51,7 @@ public class BitCommandsTest extends JedisCommandTestBase {
} }
@Test @Test
public void bitOp() public void bitOp() {
{
jedis.set("key1", "\u0060"); jedis.set("key1", "\u0060");
jedis.set("key2", "\u0044"); jedis.set("key2", "\u0044");
@@ -76,8 +75,7 @@ public class BitCommandsTest extends JedisCommandTestBase {
} }
@Test @Test
public void bitOpNot() public void bitOpNot() {
{
jedis.del("key"); jedis.del("key");
jedis.setbit("key", 0, true); jedis.setbit("key", 0, true);
jedis.setbit("key", 4, true); jedis.setbit("key", 4, true);

View File

@@ -59,11 +59,14 @@ public class ClusterCommandsTest extends JedisTestBase {
private static void waitForEqualClusterSize() throws InterruptedException { private static void waitForEqualClusterSize() throws InterruptedException {
boolean notEqualSize = true; boolean notEqualSize = true;
while (notEqualSize) { while (notEqualSize) {
notEqualSize = getClusterAttribute(node1.clusterInfo(), "cluster_known_nodes") == getClusterAttribute(node2.clusterInfo(), "cluster_size") ? false : true; notEqualSize = getClusterAttribute(node1.clusterInfo(),
"cluster_known_nodes") == getClusterAttribute(
node2.clusterInfo(), "cluster_size") ? false : true;
} }
} }
private static int getClusterAttribute(String clusterInfo, String attributeName) { private static int getClusterAttribute(String clusterInfo,
String attributeName) {
for (String infoElement : clusterInfo.split("\n")) { for (String infoElement : clusterInfo.split("\n")) {
if (infoElement.contains(attributeName)) { if (infoElement.contains(attributeName)) {
return Integer.valueOf(infoElement.split(":")[1].trim()); return Integer.valueOf(infoElement.split(":")[1].trim());

View File

@@ -61,6 +61,11 @@ public class ControlCommandsTest extends JedisCommandTestBase {
public void monitor() { public void monitor() {
new Thread(new Runnable() { new Thread(new Runnable() {
public void run() { 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"); Jedis j = new Jedis("localhost");
j.auth("foobared"); j.auth("foobared");
for (int i = 0; i < 5; i++) { for (int i = 0; i < 5; i++) {

View File

@@ -309,7 +309,8 @@ public class HashesCommandsTest extends JedisCommandTestBase {
jedis.hset("foo", "b", "b"); jedis.hset("foo", "b", "b");
jedis.hset("foo", "a", "a"); jedis.hset("foo", "a", "a");
jedis.hset("foo", "aa", "aa"); jedis.hset("foo", "aa", "aa");
ScanResult<Map.Entry<String, String>> result = jedis.hscan("foo", 0, params); ScanResult<Map.Entry<String, String>> result = jedis.hscan("foo", 0,
params);
assertEquals(0, result.getCursor()); assertEquals(0, result.getCursor());
assertFalse(result.getResult().isEmpty()); assertFalse(result.getResult().isEmpty());
@@ -324,7 +325,8 @@ public class HashesCommandsTest extends JedisCommandTestBase {
jedis.hset("foo", "a" + i, "a" + i); jedis.hset("foo", "a" + i, "a" + i);
} }
ScanResult<Map.Entry<String, String>> result = jedis.hscan("foo", 0, params); ScanResult<Map.Entry<String, String>> result = jedis.hscan("foo", 0,
params);
assertFalse(result.getResult().isEmpty()); assertFalse(result.getResult().isEmpty());
} }

View File

@@ -33,7 +33,6 @@ public class ListCommandsTest extends JedisCommandTestBase {
size = jedis.rpush("foo", "bar", "foo"); size = jedis.rpush("foo", "bar", "foo");
assertEquals(4, size); assertEquals(4, size);
// Binary // Binary
long bsize = jedis.rpush(bfoo, bbar); long bsize = jedis.rpush(bfoo, bbar);
assertEquals(1, bsize); assertEquals(1, bsize);
@@ -445,7 +444,6 @@ public class ListCommandsTest extends JedisCommandTestBase {
List<String> result = jedis.brpop(1, "foo"); List<String> result = jedis.brpop(1, "foo");
assertNull(result); assertNull(result);
jedis.lpush("foo", "bar"); jedis.lpush("foo", "bar");
result = jedis.brpop(1, "foo"); result = jedis.brpop(1, "foo");
assertNotNull(result); assertNotNull(result);

View File

@@ -3,16 +3,17 @@ package redis.clients.jedis.tests.commands;
import java.io.IOException; import java.io.IOException;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import redis.clients.jedis.BinaryJedisPubSub; import redis.clients.jedis.BinaryJedisPubSub;
import redis.clients.jedis.Jedis; import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub; import redis.clients.jedis.JedisPubSub;
import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisDataException;
import redis.clients.util.SafeEncoder; import redis.clients.util.SafeEncoder;
public class PublishSubscribeCommandsTest extends JedisCommandTestBase { public class PublishSubscribeCommandsTest extends JedisCommandTestBase {
@@ -64,6 +65,124 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase {
}, "foo"); }, "foo");
} }
@Test
public void pubSubChannels(){
final List<String> expectedActiveChannels = Arrays.asList("testchan1", "testchan2", "testchan3");
jedis.subscribe(new JedisPubSub() {
private int count = 0;
@Override
public void onUnsubscribe(String channel, int subscribedChannels) {
}
@Override
public void onSubscribe(String channel, int subscribedChannels) {
count++;
//All channels are subscribed
if (count == 3) {
Jedis otherJedis = createJedis();
List<String> activeChannels = otherJedis.pubsubChannels("test*");
assertTrue(expectedActiveChannels.containsAll(activeChannels));
unsubscribe();
}
}
@Override
public void onPUnsubscribe(String pattern, int subscribedChannels) {
}
@Override
public void onPSubscribe(String pattern, int subscribedChannels) {
}
@Override
public void onPMessage(String pattern, String channel, String message) {
}
@Override
public void onMessage(String channel, String message) {
}
}, "testchan1", "testchan2", "testchan3");
}
@Test
public void pubSubNumPat(){
jedis.psubscribe(new JedisPubSub() {
private int count=0;
@Override
public void onUnsubscribe(String channel, int subscribedChannels) {
}
@Override
public void onSubscribe(String channel, int subscribedChannels) {
}
@Override
public void onPUnsubscribe(String pattern, int subscribedChannels) {
}
@Override
public void onPSubscribe(String pattern, int subscribedChannels) {
count++;
if (count == 3) {
Jedis otherJedis = createJedis();
Long numPatterns = otherJedis.pubsubNumPat();
assertEquals(new Long(2l), numPatterns);
punsubscribe();
}
}
@Override
public void onPMessage(String pattern, String channel, String message) {
}
@Override
public void onMessage(String channel, String message) {
}
}, "test*", "test*", "chan*");
}
@Test
public void pubSubNumSub(){
final Map<String, String> expectedNumSub = new HashMap<String, String>();
expectedNumSub.put("testchannel2", "1");
expectedNumSub.put("testchannel1", "1");
jedis.subscribe(new JedisPubSub() {
private int count=0;
@Override
public void onUnsubscribe(String channel, int subscribedChannels) {
}
@Override
public void onSubscribe(String channel, int subscribedChannels) {
count++;
if (count == 2) {
Jedis otherJedis = createJedis();
Map<String, String> numSub = otherJedis.pubsubNumSub("testchannel1", "testchannel2");
assertEquals(expectedNumSub, numSub);
unsubscribe();
}
}
@Override
public void onPUnsubscribe(String pattern, int subscribedChannels) {
}
@Override
public void onPSubscribe(String pattern, int subscribedChannels) {
}
@Override
public void onPMessage(String pattern, String channel, String message) {
}
@Override
public void onMessage(String channel, String message) {
}
}, "testchannel1", "testchannel2");
}
@Test @Test
public void subscribeMany() throws UnknownHostException, IOException, public void subscribeMany() throws UnknownHostException, IOException,
InterruptedException { InterruptedException {
@@ -264,7 +383,8 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase {
public void onPSubscribe(byte[] pattern, int subscribedChannels) { public void onPSubscribe(byte[] pattern, int subscribedChannels) {
assertTrue(Arrays.equals(SafeEncoder.encode("foo.*"), pattern)); assertTrue(Arrays.equals(SafeEncoder.encode("foo.*"), pattern));
assertEquals(1, subscribedChannels); assertEquals(1, subscribedChannels);
publishOne(SafeEncoder.encode(pattern).replace("*", "bar"), "exit"); publishOne(SafeEncoder.encode(pattern).replace("*", "bar"),
"exit");
} }
public void onPUnsubscribe(byte[] pattern, int subscribedChannels) { public void onPUnsubscribe(byte[] pattern, int subscribedChannels) {
@@ -297,7 +417,8 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase {
} }
public void onPSubscribe(byte[] pattern, int subscribedChannels) { public void onPSubscribe(byte[] pattern, int subscribedChannels) {
publishOne(SafeEncoder.encode(pattern).replace("*", "123"), "exit"); publishOne(SafeEncoder.encode(pattern).replace("*", "123"),
"exit");
} }
public void onPUnsubscribe(byte[] pattern, int subscribedChannels) { public void onPUnsubscribe(byte[] pattern, int subscribedChannels) {
@@ -331,7 +452,8 @@ public class PublishSubscribeCommandsTest extends JedisCommandTestBase {
} }
public void onPSubscribe(byte[] pattern, int subscribedChannels) { public void onPSubscribe(byte[] pattern, int subscribedChannels) {
publishOne(SafeEncoder.encode(pattern).replace("*", "123"), "exit"); publishOne(SafeEncoder.encode(pattern).replace("*", "123"),
"exit");
} }
public void onPUnsubscribe(byte[] pattern, int subscribedChannels) { public void onPUnsubscribe(byte[] pattern, int subscribedChannels) {

View File

@@ -47,11 +47,13 @@ public class ScriptingCommandsTest extends JedisCommandTestBase {
args.add("second".getBytes()); args.add("second".getBytes());
args.add("third".getBytes()); args.add("third".getBytes());
BinaryJedis binaryJedis = new BinaryJedis(hnp.getHost(), hnp.getPort(), 500); BinaryJedis binaryJedis = new BinaryJedis(hnp.getHost(), hnp.getPort(),
500);
binaryJedis.connect(); binaryJedis.connect();
binaryJedis.auth("foobared"); binaryJedis.auth("foobared");
List<byte[]> responses = (List<byte[]>) binaryJedis.eval(script.getBytes(), keys, args); List<byte[]> responses = (List<byte[]>) binaryJedis.eval(
script.getBytes(), keys, args);
assertEquals(5, responses.size()); assertEquals(5, responses.size());
assertEquals("key1", new String(responses.get(0))); assertEquals("key1", new String(responses.get(0)));
assertEquals("key2", new String(responses.get(1))); assertEquals("key2", new String(responses.get(1)));
@@ -169,7 +171,8 @@ public class ScriptingCommandsTest extends JedisCommandTestBase {
@Test @Test
public void scriptEvalReturnNullValues() { public void scriptEvalReturnNullValues() {
String script = "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}"; String script = "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}";
List<String> results = (List<String>) jedis.eval(script, 2, "key1", "key2", "1", "2"); List<String> results = (List<String>) jedis.eval(script, 2, "key1",
"key2", "1", "2");
assertEquals(results.get(0), "key1"); assertEquals(results.get(0), "key1");
assertEquals(results.get(1), "key2"); assertEquals(results.get(1), "key2");
assertEquals(results.get(2), "1"); assertEquals(results.get(2), "1");
@@ -180,7 +183,8 @@ public class ScriptingCommandsTest extends JedisCommandTestBase {
public void scriptEvalShaReturnNullValues() { public void scriptEvalShaReturnNullValues() {
String script = "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}"; String script = "return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}";
String sha = jedis.scriptLoad(script); String sha = jedis.scriptLoad(script);
List<String> results = (List<String>) jedis.evalsha(sha, 2, "key1", "key2", "1", "2"); List<String> results = (List<String>) jedis.evalsha(sha, 2, "key1",
"key2", "1", "2");
assertEquals(results.get(0), "key1"); assertEquals(results.get(0), "key1");
assertEquals(results.get(1), "key2"); assertEquals(results.get(1), "key2");
assertEquals(results.get(2), "1"); assertEquals(results.get(2), "1");
@@ -188,4 +192,3 @@ public class ScriptingCommandsTest extends JedisCommandTestBase {
} }
} }

View File

@@ -2,7 +2,6 @@ package redis.clients.jedis.tests.commands;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map;
import java.util.Set; import java.util.Set;
import org.junit.Test; import org.junit.Test;
@@ -454,7 +453,6 @@ public class SetCommandsTest extends JedisCommandTestBase {
assertNull(bmember); assertNull(bmember);
} }
@Test @Test
public void sscan() { public void sscan() {
jedis.sadd("foo", "a", "b"); jedis.sadd("foo", "a", "b");

View File

@@ -389,7 +389,8 @@ public class SortedSetCommandsTest extends JedisCommandTestBase {
assertEquals(2, bresult); assertEquals(2, bresult);
bresult = jedis.zcount(bfoo, SafeEncoder.encode("(0.01"), SafeEncoder.encode("+inf")); bresult = jedis.zcount(bfoo, SafeEncoder.encode("(0.01"),
SafeEncoder.encode("+inf"));
assertEquals(3, bresult); assertEquals(3, bresult);
} }
@@ -447,8 +448,8 @@ public class SortedSetCommandsTest extends JedisCommandTestBase {
assertEquals(bexpected, brange); assertEquals(bexpected, brange);
brange = jedis.zrangeByScore(bfoo, 0d, 2d, 1, 1); brange = jedis.zrangeByScore(bfoo, 0d, 2d, 1, 1);
Set<byte[]> brange2 = jedis.zrangeByScore(bfoo, SafeEncoder Set<byte[]> brange2 = jedis.zrangeByScore(bfoo,
.encode("-inf"), SafeEncoder.encode("(2")); SafeEncoder.encode("-inf"), SafeEncoder.encode("(2"));
assertEquals(bexpected, brange2); assertEquals(bexpected, brange2);
bexpected = new LinkedHashSet<byte[]>(); bexpected = new LinkedHashSet<byte[]>();
@@ -523,8 +524,8 @@ public class SortedSetCommandsTest extends JedisCommandTestBase {
assertEquals(bexpected, brange); assertEquals(bexpected, brange);
Set<byte[]> brange2 = jedis.zrevrangeByScore(bfoo, SafeEncoder Set<byte[]> brange2 = jedis.zrevrangeByScore(bfoo,
.encode("+inf"), SafeEncoder.encode("(2")); SafeEncoder.encode("+inf"), SafeEncoder.encode("(2"));
bexpected = new LinkedHashSet<byte[]>(); bexpected = new LinkedHashSet<byte[]>();
bexpected.add(bb); bexpected.add(bb);
@@ -763,8 +764,8 @@ public class SortedSetCommandsTest extends JedisCommandTestBase {
bexpected.add(new Tuple(bb, new Double(4))); bexpected.add(new Tuple(bb, new Double(4)));
bexpected.add(new Tuple(ba, new Double(3))); bexpected.add(new Tuple(ba, new Double(3)));
assertEquals(bexpected, jedis.zrangeWithScores(SafeEncoder assertEquals(bexpected,
.encode("dst"), 0, 100)); jedis.zrangeWithScores(SafeEncoder.encode("dst"), 0, 100));
} }
@Test @Test
@@ -805,8 +806,8 @@ public class SortedSetCommandsTest extends JedisCommandTestBase {
bexpected.add(new Tuple(bb, new Double(8))); bexpected.add(new Tuple(bb, new Double(8)));
bexpected.add(new Tuple(ba, new Double(6))); bexpected.add(new Tuple(ba, new Double(6)));
assertEquals(bexpected, jedis.zrangeWithScores(SafeEncoder assertEquals(bexpected,
.encode("dst"), 0, 100)); jedis.zrangeWithScores(SafeEncoder.encode("dst"), 0, 100));
} }
@Test @Test
@@ -836,8 +837,8 @@ public class SortedSetCommandsTest extends JedisCommandTestBase {
Set<Tuple> bexpected = new LinkedHashSet<Tuple>(); Set<Tuple> bexpected = new LinkedHashSet<Tuple>();
bexpected.add(new Tuple(ba, new Double(3))); bexpected.add(new Tuple(ba, new Double(3)));
assertEquals(bexpected, jedis.zrangeWithScores(SafeEncoder assertEquals(bexpected,
.encode("dst"), 0, 100)); jedis.zrangeWithScores(SafeEncoder.encode("dst"), 0, 100));
} }
@Test @Test
@@ -874,8 +875,8 @@ public class SortedSetCommandsTest extends JedisCommandTestBase {
Set<Tuple> bexpected = new LinkedHashSet<Tuple>(); Set<Tuple> bexpected = new LinkedHashSet<Tuple>();
bexpected.add(new Tuple(ba, new Double(6))); bexpected.add(new Tuple(ba, new Double(6)));
assertEquals(bexpected, jedis.zrangeWithScores(SafeEncoder assertEquals(bexpected,
.encode("dst"), 0, 100)); jedis.zrangeWithScores(SafeEncoder.encode("dst"), 0, 100));
} }
@Test @Test
@@ -888,7 +889,6 @@ public class SortedSetCommandsTest extends JedisCommandTestBase {
assertEquals(0, t2.compareTo(t2)); assertEquals(0, t2.compareTo(t2));
} }
@Test @Test
public void zscan() { public void zscan() {
jedis.zadd("foo", 1, "a"); jedis.zadd("foo", 1, "a");

View File

@@ -180,8 +180,8 @@ public class StringValuesCommandsTest extends JedisCommandTestBase {
public void incrLargeNumbers() { public void incrLargeNumbers() {
long value = jedis.incr("foo"); long value = jedis.incr("foo");
assertEquals(1, value); assertEquals(1, value);
assertEquals(1L + Integer.MAX_VALUE, (long) jedis.incrBy("foo", assertEquals(1L + Integer.MAX_VALUE,
Integer.MAX_VALUE)); (long) jedis.incrBy("foo", Integer.MAX_VALUE));
} }
@Test(expected = JedisDataException.class) @Test(expected = JedisDataException.class)

View File

@@ -4,6 +4,7 @@ import java.io.IOException;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@@ -11,11 +12,13 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import redis.clients.jedis.Jedis; import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Protocol.Keyword; import redis.clients.jedis.Protocol.Keyword;
import redis.clients.jedis.Response; import redis.clients.jedis.Response;
import redis.clients.jedis.Transaction; import redis.clients.jedis.Transaction;
import redis.clients.jedis.TransactionBlock; import redis.clients.jedis.TransactionBlock;
import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.exceptions.JedisDataException;
import redis.clients.jedis.exceptions.JedisException;
public class TransactionCommandsTest extends JedisCommandTestBase { public class TransactionCommandsTest extends JedisCommandTestBase {
final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 };
@@ -105,6 +108,52 @@ public class TransactionCommandsTest extends JedisCommandTestBase {
} }
@Test
public void multiBlockWithErrorRedisDiscardsTransaction() throws Exception {
// Transaction with error - Redis discards transaction automatically
// (Syntax Error, etc.)
TransactionBlock tb = new TransactionBlock() {
@Override
public void execute() throws JedisException {
del("hello");
hmset("hello", new HashMap<String, String>());
}
};
try {
jedis.multi(tb);
} catch (JedisDataException e) {
assertTrue(e.getMessage().contains("EXECABORT"));
} catch (Exception e) {
throw e;
}
}
@Test
public void multiBlockWithErrorRedisForceToExecuteAllCommands()
throws Exception {
// Transaction with error - Redis doesn't roll back (Type Error,
// Deletion of non-exist key, etc.)
jedis.del("hello2");
TransactionBlock tb2 = new TransactionBlock() {
@Override
public void execute() throws JedisException {
del("hello2");
set("hello2", "hello");
sadd("hello2", "hello2");
}
};
List<Object> responses = jedis.multi(tb2);
assertEquals("OK", responses.get(1));
assertEquals(JedisDataException.class, responses.get(2).getClass());
Exception exc = (JedisDataException) responses.get(2);
assertTrue(exc.getMessage().contains("WRONGTYPE"));
}
@Test @Test
public void watch() throws UnknownHostException, IOException { public void watch() throws UnknownHostException, IOException {
jedis.watch("mykey", "somekey"); jedis.watch("mykey", "somekey");
@@ -294,4 +343,48 @@ public class TransactionCommandsTest extends JedisCommandTestBase {
assertNull(results); assertNull(results);
} }
@Test
public void testResetStateWhenInMulti() {
jedis.auth("foobared");
Transaction t = jedis.multi();
t.set("foooo", "barrr");
jedis.resetState();
assertEquals(null, jedis.get("foooo"));
}
@Test
public void testResetStateWhenInMultiWithinPipeline() {
jedis.auth("foobared");
Pipeline p = jedis.pipelined();
p.multi();
p.set("foooo", "barrr");
jedis.resetState();
assertEquals(null, jedis.get("foooo"));
}
@Test
public void testResetStateWhenInWatch() {
jedis.watch("mykey", "somekey");
// state reset : unwatch
jedis.resetState();
Transaction t = jedis.multi();
nj.connect();
nj.auth("foobared");
nj.set("mykey", "bar");
nj.disconnect();
t.set("mykey", "foo");
List<Object> resp = t.exec();
assertNotNull(resp);
assertEquals(1, resp.size());
assertEquals("foo", jedis.get("mykey"));
}
} }

View File

@@ -117,30 +117,30 @@ public class VariadicCommandsTest extends JedisCommandTestBase {
@Test @Test
public void zadd() { public void zadd() {
Map<Double, String> scoreMembers = new HashMap<Double, String>(); Map<String, Double> scoreMembers = new HashMap<String, Double>();
scoreMembers.put(1d, "bar"); scoreMembers.put("bar", 1d);
scoreMembers.put(10d, "foo"); scoreMembers.put("foo", 10d);
long status = jedis.zadd("foo", scoreMembers); long status = jedis.zadd("foo", scoreMembers);
assertEquals(2, status); assertEquals(2, status);
scoreMembers.clear(); scoreMembers.clear();
scoreMembers.put(0.1d, "car"); scoreMembers.put("car", 0.1d);
scoreMembers.put(2d, "bar"); scoreMembers.put("bar", 2d);
status = jedis.zadd("foo", scoreMembers); status = jedis.zadd("foo", scoreMembers);
assertEquals(1, status); assertEquals(1, status);
Map<Double, byte[]> bscoreMembers = new HashMap<Double, byte[]>(); Map<byte[], Double> bscoreMembers = new HashMap<byte[], Double>();
bscoreMembers.put(1d, bbar); bscoreMembers.put(bbar, 1d);
bscoreMembers.put(10d, bfoo); bscoreMembers.put(bfoo, 10d);
status = jedis.zadd(bfoo, bscoreMembers); status = jedis.zadd(bfoo, bscoreMembers);
assertEquals(2, status); assertEquals(2, status);
bscoreMembers.clear(); bscoreMembers.clear();
bscoreMembers.put(0.1d, bcar); bscoreMembers.put(bcar, 0.1d);
bscoreMembers.put(2d, bbar); bscoreMembers.put(bbar, 2d);
status = jedis.zadd(bfoo, bscoreMembers); status = jedis.zadd(bfoo, bscoreMembers);
assertEquals(1, status); assertEquals(1, status);