Replace tabs with spaces

This commit is contained in:
2015-09-01 13:13:24 +01:00
parent cdd16a53af
commit 3817f4c7ed
117 changed files with 12749 additions and 12749 deletions

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -158,38 +158,38 @@ public interface BinaryJedisCommands {
Set<byte[]> zrevrangeByScore(byte[] key, double max, double min); Set<byte[]> zrevrangeByScore(byte[] key, double max, double min);
Set<byte[]> zrangeByScore(byte[] key, double min, double max, int offset, Set<byte[]> zrangeByScore(byte[] key, double min, double max, int offset,
int count); int count);
Set<byte[]> zrevrangeByScore(byte[] key, byte[] max, byte[] min); Set<byte[]> zrevrangeByScore(byte[] key, byte[] max, byte[] min);
Set<byte[]> zrangeByScore(byte[] key, byte[] min, byte[] max, int offset, Set<byte[]> zrangeByScore(byte[] key, byte[] min, byte[] max, int offset,
int count); int count);
Set<byte[]> zrevrangeByScore(byte[] key, double max, double min, Set<byte[]> zrevrangeByScore(byte[] key, double max, double min,
int offset, int count); int offset, int count);
Set<Tuple> zrangeByScoreWithScores(byte[] key, double min, double max); Set<Tuple> zrangeByScoreWithScores(byte[] key, double min, double max);
Set<Tuple> zrevrangeByScoreWithScores(byte[] key, double max, double min); Set<Tuple> zrevrangeByScoreWithScores(byte[] key, double max, double min);
Set<Tuple> zrangeByScoreWithScores(byte[] key, double min, double max, Set<Tuple> zrangeByScoreWithScores(byte[] key, double min, double max,
int offset, int count); int offset, int count);
Set<byte[]> zrevrangeByScore(byte[] key, byte[] max, byte[] min, Set<byte[]> zrevrangeByScore(byte[] key, byte[] max, byte[] min,
int offset, int count); int offset, int count);
Set<Tuple> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max); Set<Tuple> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max);
Set<Tuple> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min); Set<Tuple> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min);
Set<Tuple> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max, Set<Tuple> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max,
int offset, int count); int offset, int count);
Set<Tuple> zrevrangeByScoreWithScores(byte[] key, double max, double min, Set<Tuple> zrevrangeByScoreWithScores(byte[] key, double max, double min,
int offset, int count); int offset, int count);
Set<Tuple> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min, Set<Tuple> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min,
int offset, int count); int offset, int count);
Long zremrangeByRank(byte[] key, long start, long end); Long zremrangeByRank(byte[] key, long start, long end);
@@ -202,18 +202,18 @@ public interface BinaryJedisCommands {
Set<byte[]> zrangeByLex(final byte[] key, final byte[] min, final byte[] max); Set<byte[]> zrangeByLex(final byte[] key, final byte[] min, final byte[] max);
Set<byte[]> zrangeByLex(final byte[] key, final byte[] min, Set<byte[]> zrangeByLex(final byte[] key, final byte[] min,
final byte[] max, int offset, int count); final byte[] max, int offset, int count);
Set<byte[]> zrevrangeByLex(final byte[] key, final byte[] max, Set<byte[]> zrevrangeByLex(final byte[] key, final byte[] max,
final byte[] min); final byte[] min);
Set<byte[]> zrevrangeByLex(final byte[] key, final byte[] max, Set<byte[]> zrevrangeByLex(final byte[] key, final byte[] max,
final byte[] min, int offset, int count); final byte[] min, int offset, int count);
Long zremrangeByLex(final byte[] key, final byte[] min, final byte[] max); Long zremrangeByLex(final byte[] key, final byte[] min, final byte[] max);
Long linsert(byte[] key, Client.LIST_POSITION where, byte[] pivot, Long linsert(byte[] key, Client.LIST_POSITION where, byte[] pivot,
byte[] value); byte[] value);
Long lpushx(byte[] key, byte[]... arg); Long lpushx(byte[] key, byte[]... arg);

View File

@@ -16,104 +16,104 @@ public abstract class BinaryJedisPubSub {
private int subscribedChannels = 0; private int subscribedChannels = 0;
private Client client; private Client client;
public void onMessage(byte[] channel, byte[] message) {} public void onMessage(byte[] channel, byte[] message) {}
public void onPMessage(byte[] pattern, byte[] channel, byte[] message) {} public void onPMessage(byte[] pattern, byte[] channel, byte[] message) {}
public void onSubscribe(byte[] channel, int subscribedChannels) {} public void onSubscribe(byte[] channel, int subscribedChannels) {}
public void onUnsubscribe(byte[] channel, int subscribedChannels) {} public void onUnsubscribe(byte[] channel, int subscribedChannels) {}
public void onPUnsubscribe(byte[] pattern, int subscribedChannels) {} public void onPUnsubscribe(byte[] pattern, int subscribedChannels) {}
public void onPSubscribe(byte[] pattern, int subscribedChannels) {} public void onPSubscribe(byte[] pattern, int subscribedChannels) {}
public void unsubscribe() { public void unsubscribe() {
client.unsubscribe(); client.unsubscribe();
client.flush(); client.flush();
} }
public void unsubscribe(byte[]... channels) { public void unsubscribe(byte[]... channels) {
client.unsubscribe(channels); client.unsubscribe(channels);
client.flush(); client.flush();
} }
public void subscribe(byte[]... channels) { public void subscribe(byte[]... channels) {
client.subscribe(channels); client.subscribe(channels);
client.flush(); client.flush();
} }
public void psubscribe(byte[]... patterns) { public void psubscribe(byte[]... patterns) {
client.psubscribe(patterns); client.psubscribe(patterns);
client.flush(); client.flush();
} }
public void punsubscribe() { public void punsubscribe() {
client.punsubscribe(); client.punsubscribe();
client.flush(); client.flush();
} }
public void punsubscribe(byte[]... patterns) { public void punsubscribe(byte[]... patterns) {
client.punsubscribe(patterns); client.punsubscribe(patterns);
client.flush(); client.flush();
} }
public boolean isSubscribed() { public boolean isSubscribed() {
return subscribedChannels > 0; return subscribedChannels > 0;
} }
public void proceedWithPatterns(Client client, byte[]... patterns) { public void proceedWithPatterns(Client client, byte[]... patterns) {
this.client = client; this.client = client;
client.psubscribe(patterns); client.psubscribe(patterns);
process(client); process(client);
} }
public void proceed(Client client, byte[]... channels) { public void proceed(Client client, byte[]... channels) {
this.client = client; this.client = client;
client.subscribe(channels); client.subscribe(channels);
process(client); process(client);
} }
private void process(Client client) { private void process(Client client) {
do { do {
List<Object> reply = client.getObjectMultiBulkReply(); List<Object> reply = client.getObjectMultiBulkReply();
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);
} }
final byte[] resp = (byte[]) firstObj; final byte[] resp = (byte[]) firstObj;
if (Arrays.equals(SUBSCRIBE.raw, resp)) { if (Arrays.equals(SUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue(); subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bchannel = (byte[]) reply.get(1); final byte[] bchannel = (byte[]) reply.get(1);
onSubscribe(bchannel, subscribedChannels); onSubscribe(bchannel, subscribedChannels);
} else if (Arrays.equals(UNSUBSCRIBE.raw, resp)) { } else if (Arrays.equals(UNSUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue(); subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bchannel = (byte[]) reply.get(1); final byte[] bchannel = (byte[]) reply.get(1);
onUnsubscribe(bchannel, subscribedChannels); onUnsubscribe(bchannel, subscribedChannels);
} else if (Arrays.equals(MESSAGE.raw, resp)) { } else if (Arrays.equals(MESSAGE.raw, resp)) {
final byte[] bchannel = (byte[]) reply.get(1); final byte[] bchannel = (byte[]) reply.get(1);
final byte[] bmesg = (byte[]) reply.get(2); final byte[] bmesg = (byte[]) reply.get(2);
onMessage(bchannel, bmesg); onMessage(bchannel, bmesg);
} else if (Arrays.equals(PMESSAGE.raw, resp)) { } else if (Arrays.equals(PMESSAGE.raw, resp)) {
final byte[] bpattern = (byte[]) reply.get(1); final byte[] bpattern = (byte[]) reply.get(1);
final byte[] bchannel = (byte[]) reply.get(2); final byte[] bchannel = (byte[]) reply.get(2);
final byte[] bmesg = (byte[]) reply.get(3); final byte[] bmesg = (byte[]) reply.get(3);
onPMessage(bpattern, bchannel, bmesg); onPMessage(bpattern, bchannel, bmesg);
} else if (Arrays.equals(PSUBSCRIBE.raw, resp)) { } else if (Arrays.equals(PSUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue(); subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bpattern = (byte[]) reply.get(1); final byte[] bpattern = (byte[]) reply.get(1);
onPSubscribe(bpattern, subscribedChannels); onPSubscribe(bpattern, subscribedChannels);
} else if (Arrays.equals(PUNSUBSCRIBE.raw, resp)) { } else if (Arrays.equals(PUNSUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue(); subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bpattern = (byte[]) reply.get(1); final byte[] bpattern = (byte[]) reply.get(1);
onPUnsubscribe(bpattern, subscribedChannels); onPUnsubscribe(bpattern, subscribedChannels);
} else { } else {
throw new JedisException("Unknown message type: " + firstObj); throw new JedisException("Unknown message type: " + firstObj);
} }
} while (isSubscribed()); } while (isSubscribed());
} }
public int getSubscribedChannels() { public int getSubscribedChannels() {
return subscribedChannels; return subscribedChannels;
} }
} }

View File

@@ -67,7 +67,7 @@ public interface BinaryRedisPipeline {
Response<byte[]> lindex(byte[] key, long index); Response<byte[]> lindex(byte[] key, long index);
Response<Long> linsert(byte[] key, BinaryClient.LIST_POSITION where, Response<Long> linsert(byte[] key, BinaryClient.LIST_POSITION where,
byte[] pivot, byte[] value); byte[] pivot, byte[] value);
Response<Long> llen(byte[] key); Response<Long> llen(byte[] key);
@@ -148,44 +148,44 @@ public interface BinaryRedisPipeline {
Response<Set<byte[]>> zrangeByScore(byte[] key, byte[] min, byte[] max); Response<Set<byte[]>> zrangeByScore(byte[] key, byte[] min, byte[] max);
Response<Set<byte[]>> zrangeByScore(byte[] key, double min, double max, Response<Set<byte[]>> zrangeByScore(byte[] key, double min, double max,
int offset, int count); int offset, int count);
Response<Set<byte[]>> zrangeByScore(byte[] key, byte[] min, byte[] max, Response<Set<byte[]>> zrangeByScore(byte[] key, byte[] min, 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);
Response<Set<Tuple>> zrangeByScoreWithScores(byte[] key, byte[] min, Response<Set<Tuple>> zrangeByScoreWithScores(byte[] key, byte[] min,
byte[] max); byte[] max);
Response<Set<Tuple>> zrangeByScoreWithScores(byte[] key, double min, Response<Set<Tuple>> zrangeByScoreWithScores(byte[] key, double min,
double max, int offset, int count); double max, int offset, int count);
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, double min); 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, byte[] max, byte[] min);
Response<Set<byte[]>> zrevrangeByScore(byte[] key, double max, double min, Response<Set<byte[]>> zrevrangeByScore(byte[] key, double max, double min,
int offset, int count); int offset, int count);
Response<Set<byte[]>> zrevrangeByScore(byte[] key, byte[] max, byte[] min, Response<Set<byte[]>> zrevrangeByScore(byte[] key, byte[] max, byte[] min,
int offset, int count); int offset, int count);
Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key, double max, Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key, double max,
double min); double min);
Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key, byte[] max, Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key, byte[] max,
byte[] min); byte[] min);
Response<Set<Tuple>> zrevrangeByScoreWithScores(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<Tuple>> zrevrangeByScoreWithScores(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>> zrangeWithScores(byte[] key, long start, long end); Response<Set<Tuple>> zrangeWithScores(byte[] key, long start, long end);
@@ -208,22 +208,22 @@ public interface BinaryRedisPipeline {
Response<Double> zscore(byte[] key, byte[] member); Response<Double> zscore(byte[] key, byte[] member);
Response<Long> zlexcount(final byte[] key, final byte[] min, Response<Long> zlexcount(final byte[] key, final byte[] min,
final byte[] max); final byte[] max);
Response<Set<byte[]>> zrangeByLex(final byte[] key, final byte[] min, Response<Set<byte[]>> zrangeByLex(final byte[] key, final byte[] min,
final byte[] max); final byte[] max);
Response<Set<byte[]>> zrangeByLex(final byte[] key, final byte[] min, Response<Set<byte[]>> zrangeByLex(final byte[] key, final byte[] min,
final byte[] max, int offset, int count); final byte[] max, int offset, int count);
Response<Set<byte[]>> zrevrangeByLex(final byte[] key, final byte[] max, Response<Set<byte[]>> zrevrangeByLex(final byte[] key, final byte[] max,
final byte[] min); final byte[] min);
Response<Set<byte[]>> zrevrangeByLex(final byte[] key, final byte[] max, Response<Set<byte[]>> zrevrangeByLex(final byte[] key, final byte[] max,
final byte[] min, int offset, int count); final byte[] min, int offset, int count);
Response<Long> zremrangeByLex(final byte[] key, final byte[] min, Response<Long> zremrangeByLex(final byte[] key, final byte[] min,
final byte[] max); final byte[] max);
Response<Long> bitcount(byte[] key); Response<Long> bitcount(byte[] key);

View File

@@ -11,618 +11,618 @@ import redis.clients.util.Hashing;
import redis.clients.util.Sharded; import redis.clients.util.Sharded;
public class BinaryShardedJedis extends Sharded<Jedis, JedisShardInfo> public class BinaryShardedJedis extends Sharded<Jedis, JedisShardInfo>
implements BinaryJedisCommands { implements BinaryJedisCommands {
public BinaryShardedJedis(List<JedisShardInfo> shards) { public BinaryShardedJedis(List<JedisShardInfo> shards) {
super(shards); super(shards);
} }
public BinaryShardedJedis(List<JedisShardInfo> shards, Hashing algo) { public BinaryShardedJedis(List<JedisShardInfo> shards, Hashing algo) {
super(shards, algo); super(shards, algo);
} }
public BinaryShardedJedis(List<JedisShardInfo> shards, Pattern keyTagPattern) { public BinaryShardedJedis(List<JedisShardInfo> shards, Pattern keyTagPattern) {
super(shards, keyTagPattern); super(shards, keyTagPattern);
} }
public BinaryShardedJedis(List<JedisShardInfo> shards, Hashing algo, public BinaryShardedJedis(List<JedisShardInfo> shards, Hashing algo,
Pattern keyTagPattern) { Pattern keyTagPattern) {
super(shards, algo, keyTagPattern); super(shards, algo, keyTagPattern);
} }
public void disconnect() { public void disconnect() {
for (Jedis jedis : getAllShards()) { for (Jedis jedis : getAllShards()) {
jedis.quit(); jedis.quit();
jedis.disconnect(); jedis.disconnect();
} }
} }
protected Jedis create(JedisShardInfo shard) { protected Jedis create(JedisShardInfo shard) {
return new Jedis(shard); return new Jedis(shard);
} }
public String set(byte[] key, byte[] value) { public String set(byte[] key, byte[] value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.set(key, value); return j.set(key, value);
} }
public byte[] get(byte[] key) { public byte[] get(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.get(key); return j.get(key);
} }
public Boolean exists(byte[] key) { public Boolean exists(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.exists(key); return j.exists(key);
} }
public String type(byte[] key) { public String type(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.type(key); return j.type(key);
} }
public Long expire(byte[] key, int seconds) { public Long expire(byte[] key, int seconds) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.expire(key, seconds); return j.expire(key, seconds);
} }
public Long expireAt(byte[] key, long unixTime) { public Long expireAt(byte[] key, long unixTime) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.expireAt(key, unixTime); return j.expireAt(key, unixTime);
} }
public Long ttl(byte[] key) { public Long ttl(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.ttl(key); return j.ttl(key);
} }
public byte[] getSet(byte[] key, byte[] value) { public byte[] getSet(byte[] key, byte[] value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.getSet(key, value); return j.getSet(key, value);
} }
public Long setnx(byte[] key, byte[] value) { public Long setnx(byte[] key, byte[] value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.setnx(key, value); return j.setnx(key, value);
} }
public String setex(byte[] key, int seconds, byte[] value) { public String setex(byte[] key, int seconds, byte[] value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.setex(key, seconds, value); return j.setex(key, seconds, value);
} }
public Long decrBy(byte[] key, long integer) { public Long decrBy(byte[] key, long integer) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.decrBy(key, integer); return j.decrBy(key, integer);
} }
public Long decr(byte[] key) { public Long decr(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.decr(key); return j.decr(key);
} }
public Long del(byte[] key) { public Long del(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.del(key); return j.del(key);
} }
public Long incrBy(byte[] key, long integer) { public Long incrBy(byte[] key, long integer) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.incrBy(key, integer); return j.incrBy(key, integer);
} }
public Double incrByFloat(byte[] key, double integer) { public Double incrByFloat(byte[] key, double integer) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.incrByFloat(key, integer); return j.incrByFloat(key, integer);
} }
public Long incr(byte[] key) { public Long incr(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.incr(key); return j.incr(key);
} }
public Long append(byte[] key, byte[] value) { public Long append(byte[] key, byte[] value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.append(key, value); return j.append(key, value);
} }
public byte[] substr(byte[] key, int start, int end) { public byte[] substr(byte[] key, int start, int end) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.substr(key, start, end); return j.substr(key, start, end);
} }
public Long hset(byte[] key, byte[] field, byte[] value) { public Long hset(byte[] key, byte[] field, byte[] value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hset(key, field, value); return j.hset(key, field, value);
} }
public byte[] hget(byte[] key, byte[] field) { public byte[] hget(byte[] key, byte[] field) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hget(key, field); return j.hget(key, field);
} }
public Long hsetnx(byte[] key, byte[] field, byte[] value) { public Long hsetnx(byte[] key, byte[] field, byte[] value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hsetnx(key, field, value); return j.hsetnx(key, field, value);
} }
public String hmset(byte[] key, Map<byte[], byte[]> hash) { public String hmset(byte[] key, Map<byte[], byte[]> hash) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hmset(key, hash); return j.hmset(key, hash);
} }
public List<byte[]> hmget(byte[] key, byte[]... fields) { public List<byte[]> hmget(byte[] key, byte[]... fields) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hmget(key, fields); return j.hmget(key, fields);
} }
public Long hincrBy(byte[] key, byte[] field, long value) { public Long hincrBy(byte[] key, byte[] field, long value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hincrBy(key, field, value); return j.hincrBy(key, field, value);
} }
public Double hincrByFloat(byte[] key, byte[] field, double value) { public Double hincrByFloat(byte[] key, byte[] field, double value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hincrByFloat(key, field, value); return j.hincrByFloat(key, field, value);
} }
public Boolean hexists(byte[] key, byte[] field) { public Boolean hexists(byte[] key, byte[] field) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hexists(key, field); return j.hexists(key, field);
} }
public Long hdel(byte[] key, byte[]... fields) { public Long hdel(byte[] key, byte[]... fields) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hdel(key, fields); return j.hdel(key, fields);
} }
public Long hlen(byte[] key) { public Long hlen(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hlen(key); return j.hlen(key);
} }
public Set<byte[]> hkeys(byte[] key) { public Set<byte[]> hkeys(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hkeys(key); return j.hkeys(key);
} }
public Collection<byte[]> hvals(byte[] key) { public Collection<byte[]> hvals(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hvals(key); return j.hvals(key);
} }
public Map<byte[], byte[]> hgetAll(byte[] key) { public Map<byte[], byte[]> hgetAll(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hgetAll(key); return j.hgetAll(key);
} }
public Long rpush(byte[] key, byte[]... strings) { public Long rpush(byte[] key, byte[]... strings) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.rpush(key, strings); return j.rpush(key, strings);
} }
public Long lpush(byte[] key, byte[]... strings) { public Long lpush(byte[] key, byte[]... strings) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.lpush(key, strings); return j.lpush(key, strings);
} }
public Long strlen(final byte[] key) { public Long strlen(final byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.strlen(key); return j.strlen(key);
} }
public Long lpushx(byte[] key, byte[]... string) { public Long lpushx(byte[] key, byte[]... string) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.lpushx(key, string); return j.lpushx(key, string);
} }
public Long persist(final byte[] key) { public Long persist(final byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.persist(key); return j.persist(key);
} }
public Long rpushx(byte[] key, byte[]... string) { public Long rpushx(byte[] key, byte[]... string) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.rpushx(key, string); return j.rpushx(key, string);
} }
public Long llen(byte[] key) { public Long llen(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.llen(key); return j.llen(key);
} }
public List<byte[]> lrange(byte[] key, long start, long end) { public List<byte[]> lrange(byte[] key, long start, long end) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.lrange(key, start, end); return j.lrange(key, start, end);
} }
public String ltrim(byte[] key, long start, long end) { public String ltrim(byte[] key, long start, long end) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.ltrim(key, start, end); return j.ltrim(key, start, end);
} }
public byte[] lindex(byte[] key, long index) { public byte[] lindex(byte[] key, long index) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.lindex(key, index); return j.lindex(key, index);
} }
public String lset(byte[] key, long index, byte[] value) { public String lset(byte[] key, long index, byte[] value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.lset(key, index, value); return j.lset(key, index, value);
} }
public Long lrem(byte[] key, long count, byte[] value) { public Long lrem(byte[] key, long count, byte[] value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.lrem(key, count, value); return j.lrem(key, count, value);
} }
public byte[] lpop(byte[] key) { public byte[] lpop(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.lpop(key); return j.lpop(key);
} }
public byte[] rpop(byte[] key) { public byte[] rpop(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.rpop(key); return j.rpop(key);
} }
public Long sadd(byte[] key, byte[]... members) { public Long sadd(byte[] key, byte[]... members) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.sadd(key, members); return j.sadd(key, members);
} }
public Set<byte[]> smembers(byte[] key) { public Set<byte[]> smembers(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.smembers(key); return j.smembers(key);
} }
public Long srem(byte[] key, byte[]... members) { public Long srem(byte[] key, byte[]... members) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.srem(key, members); return j.srem(key, members);
} }
public byte[] spop(byte[] key) { public byte[] spop(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.spop(key); return j.spop(key);
} }
public Long scard(byte[] key) { public Long scard(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.scard(key); return j.scard(key);
} }
public Boolean sismember(byte[] key, byte[] member) { public Boolean sismember(byte[] key, byte[] member) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.sismember(key, member); return j.sismember(key, member);
} }
public byte[] srandmember(byte[] key) { public byte[] srandmember(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.srandmember(key); return j.srandmember(key);
} }
@Override @Override
public List srandmember(byte[] key, int count) { public List srandmember(byte[] key, int count) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.srandmember(key, count); return j.srandmember(key, count);
} }
public Long zadd(byte[] key, double score, byte[] member) { public Long zadd(byte[] key, double score, byte[] member) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zadd(key, score, member); return j.zadd(key, score, member);
} }
public Long zadd(byte[] key, Map<byte[], Double> 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);
} }
public Set<byte[]> zrange(byte[] key, long start, long end) { public Set<byte[]> zrange(byte[] key, long start, long end) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrange(key, start, end); return j.zrange(key, start, end);
} }
public Long zrem(byte[] key, byte[]... members) { public Long zrem(byte[] key, byte[]... members) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrem(key, members); return j.zrem(key, members);
} }
public Double zincrby(byte[] key, double score, byte[] member) { public Double zincrby(byte[] key, double score, byte[] member) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zincrby(key, score, member); return j.zincrby(key, score, member);
} }
public Long zrank(byte[] key, byte[] member) { public Long zrank(byte[] key, byte[] member) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrank(key, member); return j.zrank(key, member);
} }
public Long zrevrank(byte[] key, byte[] member) { public Long zrevrank(byte[] key, byte[] member) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrank(key, member); return j.zrevrank(key, member);
} }
public Set<byte[]> zrevrange(byte[] key, long start, long end) { public Set<byte[]> zrevrange(byte[] key, long start, long end) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrange(key, start, end); return j.zrevrange(key, start, end);
} }
public Set<Tuple> zrangeWithScores(byte[] key, long start, long end) { public Set<Tuple> zrangeWithScores(byte[] key, long start, long end) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrangeWithScores(key, start, end); return j.zrangeWithScores(key, start, end);
} }
public Set<Tuple> zrevrangeWithScores(byte[] key, long start, long end) { public Set<Tuple> zrevrangeWithScores(byte[] key, long start, long end) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrangeWithScores(key, start, end); return j.zrevrangeWithScores(key, start, end);
} }
public Long zcard(byte[] key) { public Long zcard(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zcard(key); return j.zcard(key);
} }
public Double zscore(byte[] key, byte[] member) { public Double zscore(byte[] key, byte[] member) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zscore(key, member); return j.zscore(key, member);
} }
public List<byte[]> sort(byte[] key) { public List<byte[]> sort(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.sort(key); return j.sort(key);
} }
public List<byte[]> sort(byte[] key, SortingParams sortingParameters) { public List<byte[]> sort(byte[] key, SortingParams sortingParameters) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.sort(key, sortingParameters); return j.sort(key, sortingParameters);
} }
public Long zcount(byte[] key, double min, double max) { public Long zcount(byte[] key, double min, double max) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zcount(key, min, max); return j.zcount(key, min, max);
} }
public Long zcount(byte[] key, byte[] min, byte[] max) { public Long zcount(byte[] key, byte[] min, byte[] max) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zcount(key, min, max); return j.zcount(key, min, max);
} }
public Set<byte[]> zrangeByScore(byte[] key, double min, double max) { public Set<byte[]> zrangeByScore(byte[] key, double min, double max) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrangeByScore(key, min, max); return j.zrangeByScore(key, min, max);
} }
public Set<byte[]> zrangeByScore(byte[] key, double min, double max, public Set<byte[]> zrangeByScore(byte[] key, double min, double max,
int offset, int count) { int offset, int count) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrangeByScore(key, min, max, offset, count); return j.zrangeByScore(key, min, max, offset, count);
} }
public Set<Tuple> zrangeByScoreWithScores(byte[] key, double min, double max) { public Set<Tuple> zrangeByScoreWithScores(byte[] key, double min, double max) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max); return j.zrangeByScoreWithScores(key, min, max);
} }
public Set<Tuple> zrangeByScoreWithScores(byte[] key, double min, public Set<Tuple> zrangeByScoreWithScores(byte[] key, double min,
double max, int offset, int count) { double max, int offset, int count) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max, offset, count); return j.zrangeByScoreWithScores(key, min, max, offset, count);
} }
public Set<byte[]> zrangeByScore(byte[] key, byte[] min, byte[] max) { public Set<byte[]> zrangeByScore(byte[] key, byte[] min, byte[] max) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrangeByScore(key, min, max); return j.zrangeByScore(key, min, max);
} }
public Set<Tuple> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max) { public Set<Tuple> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max); return j.zrangeByScoreWithScores(key, min, max);
} }
public Set<Tuple> zrangeByScoreWithScores(byte[] key, byte[] min, public Set<Tuple> zrangeByScoreWithScores(byte[] key, byte[] min,
byte[] max, int offset, int count) { byte[] max, int offset, int count) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max, offset, count); return j.zrangeByScoreWithScores(key, min, max, offset, count);
} }
public Set<byte[]> zrangeByScore(byte[] key, byte[] min, byte[] max, public Set<byte[]> zrangeByScore(byte[] key, byte[] min, byte[] max,
int offset, int count) { int offset, int count) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrangeByScore(key, min, max, offset, count); return j.zrangeByScore(key, min, max, offset, count);
} }
public Set<byte[]> zrevrangeByScore(byte[] key, double max, double min) { public Set<byte[]> zrevrangeByScore(byte[] key, double max, double min) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min); return j.zrevrangeByScore(key, max, min);
} }
public Set<byte[]> zrevrangeByScore(byte[] key, double max, double min, public Set<byte[]> zrevrangeByScore(byte[] key, double max, double min,
int offset, int count) { int offset, int count) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min, offset, count); return j.zrevrangeByScore(key, max, min, offset, count);
} }
public Set<Tuple> zrevrangeByScoreWithScores(byte[] key, double max, public Set<Tuple> zrevrangeByScoreWithScores(byte[] key, double max,
double min) { double min) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min); return j.zrevrangeByScoreWithScores(key, max, min);
} }
public Set<Tuple> zrevrangeByScoreWithScores(byte[] key, double max, public Set<Tuple> zrevrangeByScoreWithScores(byte[] key, double max,
double min, int offset, int count) { double min, int offset, int count) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min, offset, count); return j.zrevrangeByScoreWithScores(key, max, min, offset, count);
} }
public Set<byte[]> zrevrangeByScore(byte[] key, byte[] max, byte[] min) { public Set<byte[]> zrevrangeByScore(byte[] key, byte[] max, byte[] min) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min); return j.zrevrangeByScore(key, max, min);
} }
public Set<byte[]> zrevrangeByScore(byte[] key, byte[] max, byte[] min, public Set<byte[]> zrevrangeByScore(byte[] key, byte[] max, byte[] min,
int offset, int count) { int offset, int count) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min, offset, count); return j.zrevrangeByScore(key, max, min, offset, count);
} }
public Set<Tuple> zrevrangeByScoreWithScores(byte[] key, byte[] max, public Set<Tuple> zrevrangeByScoreWithScores(byte[] key, byte[] max,
byte[] min) { byte[] min) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min); return j.zrevrangeByScoreWithScores(key, max, min);
} }
public Set<Tuple> zrevrangeByScoreWithScores(byte[] key, byte[] max, public Set<Tuple> zrevrangeByScoreWithScores(byte[] key, byte[] max,
byte[] min, int offset, int count) { byte[] min, int offset, int count) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min, offset, count); return j.zrevrangeByScoreWithScores(key, max, min, offset, count);
} }
public Long zremrangeByRank(byte[] key, long start, long end) { public Long zremrangeByRank(byte[] key, long start, long end) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zremrangeByRank(key, start, end); return j.zremrangeByRank(key, start, end);
} }
public Long zremrangeByScore(byte[] key, double start, double end) { public Long zremrangeByScore(byte[] key, double start, double end) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zremrangeByScore(key, start, end); return j.zremrangeByScore(key, start, end);
} }
public Long zremrangeByScore(byte[] key, byte[] start, byte[] end) { public Long zremrangeByScore(byte[] key, byte[] start, byte[] end) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zremrangeByScore(key, start, end); return j.zremrangeByScore(key, start, end);
} }
@Override @Override
public Long zlexcount(final byte[] key, final byte[] min, final byte[] max) { public Long zlexcount(final byte[] key, final byte[] min, final byte[] max) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zlexcount(key, min, max); return j.zlexcount(key, min, max);
} }
@Override @Override
public Set<byte[]> zrangeByLex(final byte[] key, final byte[] min, public Set<byte[]> zrangeByLex(final byte[] key, final byte[] min,
final byte[] max) { final byte[] max) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrangeByLex(key, min, max); return j.zrangeByLex(key, min, max);
} }
@Override @Override
public Set<byte[]> zrangeByLex(final byte[] key, final byte[] min, public Set<byte[]> zrangeByLex(final byte[] key, final byte[] min,
final byte[] max, final int offset, final int count) { final byte[] max, final int offset, final int count) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrangeByLex(key, min, max, offset, count); return j.zrangeByLex(key, min, max, offset, count);
} }
@Override @Override
public Set<byte[]> zrevrangeByLex(byte[] key, byte[] max, byte[] min) { public Set<byte[]> zrevrangeByLex(byte[] key, byte[] max, byte[] min) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrangeByLex(key, max, min); return j.zrevrangeByLex(key, max, min);
} }
@Override @Override
public Set<byte[]> zrevrangeByLex(byte[] key, byte[] max, byte[] min, public Set<byte[]> zrevrangeByLex(byte[] key, byte[] max, byte[] min,
int offset, int count) { int offset, int count) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrangeByLex(key, max, min, offset, count); return j.zrevrangeByLex(key, max, min, offset, count);
} }
@Override @Override
public Long zremrangeByLex(final byte[] key, final byte[] min, public Long zremrangeByLex(final byte[] key, final byte[] min,
final byte[] max) { final byte[] max) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zremrangeByLex(key, min, max); return j.zremrangeByLex(key, min, max);
} }
public Long linsert(byte[] key, LIST_POSITION where, byte[] pivot, public Long linsert(byte[] key, LIST_POSITION where, byte[] pivot,
byte[] value) { byte[] value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.linsert(key, where, pivot, value); return j.linsert(key, where, pivot, value);
} }
public ShardedJedisPipeline pipelined() { public ShardedJedisPipeline pipelined() {
ShardedJedisPipeline pipeline = new ShardedJedisPipeline(); ShardedJedisPipeline pipeline = new ShardedJedisPipeline();
pipeline.setShardedJedis(this); pipeline.setShardedJedis(this);
return pipeline; return pipeline;
} }
public Long objectRefcount(byte[] key) { public Long objectRefcount(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.objectRefcount(key); return j.objectRefcount(key);
} }
public byte[] objectEncoding(byte[] key) { public byte[] objectEncoding(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.objectEncoding(key); return j.objectEncoding(key);
} }
public Long objectIdletime(byte[] key) { public Long objectIdletime(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.objectIdletime(key); return j.objectIdletime(key);
} }
public Boolean setbit(byte[] key, long offset, boolean value) { public Boolean setbit(byte[] key, long offset, boolean value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.setbit(key, offset, value); return j.setbit(key, offset, value);
} }
public Boolean setbit(byte[] key, long offset, byte[] value) { public Boolean setbit(byte[] key, long offset, byte[] value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.setbit(key, offset, value); return j.setbit(key, offset, value);
} }
public Boolean getbit(byte[] key, long offset) { public Boolean getbit(byte[] key, long offset) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.getbit(key, offset); return j.getbit(key, offset);
} }
public Long setrange(byte[] key, long offset, byte[] value) { public Long setrange(byte[] key, long offset, byte[] value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.setrange(key, offset, value); return j.setrange(key, offset, value);
} }
public byte[] getrange(byte[] key, long startOffset, long endOffset) { public byte[] getrange(byte[] key, long startOffset, long endOffset) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.getrange(key, startOffset, endOffset); return j.getrange(key, startOffset, endOffset);
} }
public Long move(byte[] key, int dbIndex) { public Long move(byte[] key, int dbIndex) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.move(key, dbIndex); return j.move(key, dbIndex);
} }
public byte[] echo(byte[] arg) { public byte[] echo(byte[] arg) {
Jedis j = getShard(arg); Jedis j = getShard(arg);
return j.echo(arg); return j.echo(arg);
} }
public List<byte[]> brpop(byte[] arg) { public List<byte[]> brpop(byte[] arg) {
Jedis j = getShard(arg); Jedis j = getShard(arg);
return j.brpop(arg); return j.brpop(arg);
} }
public List<byte[]> blpop(byte[] arg) { public List<byte[]> blpop(byte[] arg) {
Jedis j = getShard(arg); Jedis j = getShard(arg);
return j.blpop(arg); return j.blpop(arg);
} }
public Long bitcount(byte[] key) { public Long bitcount(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.bitcount(key); return j.bitcount(key);
} }
public Long bitcount(byte[] key, long start, long end) { public Long bitcount(byte[] key, long start, long end) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.bitcount(key, start, end); return j.bitcount(key, start, end);
} }
@Override @Override
public Long pfadd(final byte[] key, final byte[]... elements) { public Long pfadd(final byte[] key, final byte[]... elements) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.pfadd(key, elements); return j.pfadd(key, elements);
} }
@Override @Override
public long pfcount(final byte[] key) { public long pfcount(final byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.pfcount(key); return j.pfcount(key);
} }
} }

View File

@@ -12,16 +12,16 @@ public class BitPosParams {
} }
public BitPosParams(long start) { public BitPosParams(long start) {
params.add(Protocol.toByteArray(start)); params.add(Protocol.toByteArray(start));
} }
public BitPosParams(long start, long end) { public BitPosParams(long start, long end) {
this(start); this(start);
params.add(Protocol.toByteArray(end)); params.add(Protocol.toByteArray(end));
} }
public Collection<byte[]> getParams() { public Collection<byte[]> getParams() {
return Collections.unmodifiableCollection(params); return Collections.unmodifiableCollection(params);
} }
} }

View File

@@ -14,265 +14,265 @@ 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>() {
public Double build(Object data) { public Double build(Object data) {
String asString = STRING.build(data); String asString = STRING.build(data);
return asString == null ? null : Double.valueOf(asString); return asString == null ? null : Double.valueOf(asString);
} }
public String toString() { public String toString() {
return "double"; return "double";
} }
}; };
public static final Builder<Boolean> BOOLEAN = new Builder<Boolean>() { public static final Builder<Boolean> BOOLEAN = new Builder<Boolean>() {
public Boolean build(Object data) { public Boolean build(Object data) {
return ((Long) data) == 1; return ((Long) data) == 1;
} }
public String toString() { public String toString() {
return "boolean"; return "boolean";
} }
}; };
public static final Builder<byte[]> BYTE_ARRAY = new Builder<byte[]>() { public static final Builder<byte[]> BYTE_ARRAY = new Builder<byte[]>() {
public byte[] build(Object data) { public byte[] build(Object data) {
return ((byte[]) data); // deleted == 1 return ((byte[]) data); // deleted == 1
} }
public String toString() { public String toString() {
return "byte[]"; return "byte[]";
} }
}; };
public static final Builder<Long> LONG = new Builder<Long>() { public static final Builder<Long> LONG = new Builder<Long>() {
public Long build(Object data) { public Long build(Object data) {
return (Long) data; return (Long) data;
} }
public String toString() { public String toString() {
return "long"; return "long";
} }
}; };
public static final Builder<String> STRING = new Builder<String>() { public static final Builder<String> STRING = new Builder<String>() {
public String build(Object data) { public String build(Object data) {
return data == null ? null : SafeEncoder.encode((byte[]) data); return data == null ? null : SafeEncoder.encode((byte[]) data);
} }
public String toString() { public String toString() {
return "string"; return "string";
} }
}; };
public static final Builder<List<String>> STRING_LIST = new Builder<List<String>>() { public static final Builder<List<String>> STRING_LIST = new Builder<List<String>>() {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public List<String> build(Object data) { public List<String> build(Object data) {
if (null == data) { if (null == data) {
return null; return null;
} }
List<byte[]> l = (List<byte[]>) data; List<byte[]> l = (List<byte[]>) data;
final ArrayList<String> result = new ArrayList<String>(l.size()); final ArrayList<String> result = new ArrayList<String>(l.size());
for (final byte[] barray : l) { for (final byte[] barray : l) {
if (barray == null) { if (barray == null) {
result.add(null); result.add(null);
} else { } else {
result.add(SafeEncoder.encode(barray)); result.add(SafeEncoder.encode(barray));
} }
} }
return result; return result;
} }
public String toString() { public String toString() {
return "List<String>"; return "List<String>";
} }
}; };
public static final Builder<Map<String, String>> STRING_MAP = new Builder<Map<String, String>>() { public static final Builder<Map<String, String>> STRING_MAP = new Builder<Map<String, String>>() {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public Map<String, String> build(Object data) { public Map<String, String> build(Object data) {
final List<byte[]> flatHash = (List<byte[]>) data; final List<byte[]> flatHash = (List<byte[]>) data;
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()), hash.put(SafeEncoder.encode(iterator.next()),
SafeEncoder.encode(iterator.next())); SafeEncoder.encode(iterator.next()));
} }
return hash; return hash;
} }
public String toString() { public String toString() {
return "Map<String, String>"; return "Map<String, String>";
} }
}; };
public static final Builder<Map<String, String>> PUBSUB_NUMSUB_MAP = new Builder<Map<String, String>>() { public static final Builder<Map<String, String>> PUBSUB_NUMSUB_MAP = new Builder<Map<String, String>>() {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public Map<String, String> build(Object data) { public Map<String, String> build(Object data) {
final List<Object> flatHash = (List<Object>) data; final List<Object> flatHash = (List<Object>) data;
final Map<String, String> hash = new HashMap<String, String>(); final Map<String, String> hash = new HashMap<String, String>();
final Iterator<Object> iterator = flatHash.iterator(); final Iterator<Object> iterator = flatHash.iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
hash.put(SafeEncoder.encode((byte[]) iterator.next()), hash.put(SafeEncoder.encode((byte[]) iterator.next()),
String.valueOf((Long) iterator.next())); String.valueOf((Long) iterator.next()));
} }
return hash; return hash;
} }
public String toString() { public String toString() {
return "PUBSUB_NUMSUB_MAP<String, String>"; return "PUBSUB_NUMSUB_MAP<String, String>";
} }
}; };
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) {
if (null == data) { if (null == data) {
return null; return null;
} }
List<byte[]> l = (List<byte[]>) data; List<byte[]> l = (List<byte[]>) data;
final Set<String> result = new HashSet<String>(l.size()); final Set<String> result = new HashSet<String>(l.size());
for (final byte[] barray : l) { for (final byte[] barray : l) {
if (barray == null) { if (barray == null) {
result.add(null); result.add(null);
} else { } else {
result.add(SafeEncoder.encode(barray)); result.add(SafeEncoder.encode(barray));
} }
} }
return result; return result;
} }
public String toString() { public String toString() {
return "Set<String>"; return "Set<String>";
} }
}; };
public static final Builder<List<byte[]>> BYTE_ARRAY_LIST = new Builder<List<byte[]>>() { public static final Builder<List<byte[]>> BYTE_ARRAY_LIST = new Builder<List<byte[]>>() {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public List<byte[]> build(Object data) { public List<byte[]> build(Object data) {
if (null == data) { if (null == data) {
return null; return null;
} }
List<byte[]> l = (List<byte[]>) data; List<byte[]> l = (List<byte[]>) data;
return l; return l;
} }
public String toString() { public String toString() {
return "List<byte[]>"; return "List<byte[]>";
} }
}; };
public static final Builder<Set<byte[]>> BYTE_ARRAY_ZSET = new Builder<Set<byte[]>>() { public static final Builder<Set<byte[]>> BYTE_ARRAY_ZSET = new Builder<Set<byte[]>>() {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public Set<byte[]> build(Object data) { public Set<byte[]> build(Object data) {
if (null == data) { if (null == data) {
return null; return null;
} }
List<byte[]> l = (List<byte[]>) data; List<byte[]> l = (List<byte[]>) data;
final Set<byte[]> result = new LinkedHashSet<byte[]>(l); final Set<byte[]> result = new LinkedHashSet<byte[]>(l);
for (final byte[] barray : l) { for (final byte[] barray : l) {
if (barray == null) { if (barray == null) {
result.add(null); result.add(null);
} else { } else {
result.add(barray); result.add(barray);
} }
} }
return result; return result;
} }
public String toString() { public String toString() {
return "ZSet<byte[]>"; return "ZSet<byte[]>";
} }
}; };
public static final Builder<Map<byte[], byte[]>> BYTE_ARRAY_MAP = new Builder<Map<byte[], byte[]>>() { public static final Builder<Map<byte[], byte[]>> BYTE_ARRAY_MAP = new Builder<Map<byte[], byte[]>>() {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public Map<byte[], byte[]> build(Object data) { public Map<byte[], byte[]> build(Object data) {
final List<byte[]> flatHash = (List<byte[]>) data; final List<byte[]> flatHash = (List<byte[]>) data;
final Map<byte[], byte[]> hash = new JedisByteHashMap(); final Map<byte[], byte[]> hash = new JedisByteHashMap();
final Iterator<byte[]> iterator = flatHash.iterator(); final Iterator<byte[]> iterator = flatHash.iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
hash.put(iterator.next(), iterator.next()); hash.put(iterator.next(), iterator.next());
} }
return hash; return hash;
} }
public String toString() { public String toString() {
return "Map<byte[], byte[]>"; return "Map<byte[], byte[]>";
} }
}; };
public static final Builder<Set<String>> STRING_ZSET = new Builder<Set<String>>() { public static final Builder<Set<String>> STRING_ZSET = new Builder<Set<String>>() {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public Set<String> build(Object data) { public Set<String> build(Object data) {
if (null == data) { if (null == data) {
return null; return null;
} }
List<byte[]> l = (List<byte[]>) data; List<byte[]> l = (List<byte[]>) data;
final Set<String> result = new LinkedHashSet<String>(l.size()); final Set<String> result = new LinkedHashSet<String>(l.size());
for (final byte[] barray : l) { for (final byte[] barray : l) {
if (barray == null) { if (barray == null) {
result.add(null); result.add(null);
} else { } else {
result.add(SafeEncoder.encode(barray)); result.add(SafeEncoder.encode(barray));
} }
} }
return result; return result;
} }
public String toString() { public String toString() {
return "ZSet<String>"; return "ZSet<String>";
} }
}; };
public static final Builder<Set<Tuple>> TUPLE_ZSET = new Builder<Set<Tuple>>() { public static final Builder<Set<Tuple>> TUPLE_ZSET = new Builder<Set<Tuple>>() {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public Set<Tuple> build(Object data) { public Set<Tuple> build(Object data) {
if (null == data) { if (null == data) {
return null; return null;
} }
List<byte[]> l = (List<byte[]>) data; List<byte[]> l = (List<byte[]>) data;
final Set<Tuple> result = new LinkedHashSet<Tuple>(l.size()); final Set<Tuple> result = new LinkedHashSet<Tuple>(l.size());
Iterator<byte[]> iterator = l.iterator(); Iterator<byte[]> iterator = l.iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
result.add(new Tuple(SafeEncoder.encode(iterator.next()), result.add(new Tuple(SafeEncoder.encode(iterator.next()),
Double.valueOf(SafeEncoder.encode(iterator.next())))); Double.valueOf(SafeEncoder.encode(iterator.next()))));
} }
return result; return result;
} }
public String toString() { public String toString() {
return "ZSet<Tuple>"; return "ZSet<Tuple>";
} }
}; };
public static final Builder<Set<Tuple>> TUPLE_ZSET_BINARY = new Builder<Set<Tuple>>() { public static final Builder<Set<Tuple>> TUPLE_ZSET_BINARY = new Builder<Set<Tuple>>() {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public Set<Tuple> build(Object data) { public Set<Tuple> build(Object data) {
if (null == data) { if (null == data) {
return null; return null;
} }
List<byte[]> l = (List<byte[]>) data; List<byte[]> l = (List<byte[]>) data;
final Set<Tuple> result = new LinkedHashSet<Tuple>(l.size()); final Set<Tuple> result = new LinkedHashSet<Tuple>(l.size());
Iterator<byte[]> iterator = l.iterator(); Iterator<byte[]> iterator = l.iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
result.add(new Tuple(iterator.next(), Double result.add(new Tuple(iterator.next(), Double
.valueOf(SafeEncoder.encode(iterator.next())))); .valueOf(SafeEncoder.encode(iterator.next()))));
} }
return result; return result;
} }
public String toString() { public String toString() {
return "ZSet<Tuple>"; return "ZSet<Tuple>";
} }
}; };
} }

File diff suppressed because it is too large Load Diff

View File

@@ -9,7 +9,7 @@ public interface Commands {
public void set(final String key, final String value); public void set(final String key, final String 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,
final String expx, final long time); final String expx, final long time);
public void get(final String key); public void get(final String key);
@@ -82,7 +82,7 @@ public interface Commands {
public void hincrBy(final String key, final String field, final long value); public void hincrBy(final String key, final String field, final long value);
public void hincrByFloat(final String key, final String field, public void hincrByFloat(final String key, final String field,
final double value); final double value);
public void hexists(final String key, final String field); public void hexists(final String key, final String field);
@@ -127,7 +127,7 @@ public interface Commands {
public void spop(final String key); public void spop(final String key);
public void smove(final String srckey, final String dstkey, public void smove(final String srckey, final String dstkey,
final String member); final String member);
public void scard(final String key); public void scard(final String key);
@@ -156,7 +156,7 @@ public interface Commands {
public void zrem(final String key, final String... members); public void zrem(final String key, final String... members);
public void zincrby(final String key, final double score, public void zincrby(final String key, final double score,
final String member); final String member);
public void zrank(final String key, final String member); public void zrank(final String key, final String member);
@@ -165,10 +165,10 @@ public interface Commands {
public void zrevrange(final String key, final long start, final long end); public void zrevrange(final String key, final long start, final long end);
public void zrangeWithScores(final String key, final long start, public void zrangeWithScores(final String key, final long start,
final long end); final long end);
public void zrevrangeWithScores(final String key, final long start, public void zrevrangeWithScores(final String key, final long start,
final long end); final long end);
public void zcard(final String key); public void zcard(final String key);
@@ -183,79 +183,79 @@ public interface Commands {
public void blpop(final String[] args); public void blpop(final String[] args);
public void sort(final String key, final SortingParams sortingParameters, public void sort(final String key, final SortingParams sortingParameters,
final String dstkey); final String dstkey);
public void sort(final String key, final String dstkey); public void sort(final String key, final String dstkey);
public void brpop(final String[] args); public void brpop(final String[] args);
public void brpoplpush(final String source, final String destination, public void brpoplpush(final String source, final String destination,
final int timeout); final int timeout);
public void zcount(final String key, final double min, final double max); public void zcount(final String key, final double min, final double max);
public void zcount(final String key, final String min, final String max); public void zcount(final String key, final String min, final String max);
public void zrangeByScore(final String key, final double min, public void zrangeByScore(final String key, final double min,
final double max); final double max);
public void zrangeByScore(final String key, final String min, public void zrangeByScore(final String key, final String min,
final String max); final String max);
public void zrangeByScore(final String key, final double min, public void zrangeByScore(final String key, final double min,
final double max, final int offset, int count); final double max, final int offset, int count);
public void zrangeByScoreWithScores(final String key, final double min, public void zrangeByScoreWithScores(final String key, final double min,
final double max); final double max);
public void zrangeByScoreWithScores(final String key, final double min, public void zrangeByScoreWithScores(final String key, final double min,
final double max, final int offset, final int count); final double max, final int offset, final int count);
public void zrangeByScoreWithScores(final String key, final String min, public void zrangeByScoreWithScores(final String key, final String min,
final String max); final String max);
public void zrangeByScoreWithScores(final String key, final String min, public void zrangeByScoreWithScores(final String key, final String min,
final String max, final int offset, final int count); final String max, final int offset, final int count);
public void zrevrangeByScore(final String key, final double max, public void zrevrangeByScore(final String key, final double max,
final double min); final double min);
public void zrevrangeByScore(final String key, final String max, public void zrevrangeByScore(final String key, final String max,
final String min); final String min);
public void zrevrangeByScore(final String key, final double max, public void zrevrangeByScore(final String key, final double max,
final double min, final int offset, int count); final double min, final int offset, int count);
public void zrevrangeByScoreWithScores(final String key, final double max, public void zrevrangeByScoreWithScores(final String key, final double max,
final double min); final double min);
public void zrevrangeByScoreWithScores(final String key, final double max, public void zrevrangeByScoreWithScores(final String key, final double max,
final double min, final int offset, final int count); final double min, final int offset, final int count);
public void zrevrangeByScoreWithScores(final String key, final String max, public void zrevrangeByScoreWithScores(final String key, final String max,
final String min); final String min);
public void zrevrangeByScoreWithScores(final String key, final String max, public void zrevrangeByScoreWithScores(final String key, final String max,
final String min, final int offset, final int count); final String min, final int offset, final int count);
public void zremrangeByRank(final String key, final long start, public void zremrangeByRank(final String key, final long start,
final long end); final long end);
public void zremrangeByScore(final String key, final double start, public void zremrangeByScore(final String key, final double start,
final double end); final double end);
public void zremrangeByScore(final String key, final String start, public void zremrangeByScore(final String key, final String start,
final String end); final String end);
public void zunionstore(final String dstkey, final String... sets); public void zunionstore(final String dstkey, final String... sets);
public void zunionstore(final String dstkey, final ZParams params, public void zunionstore(final String dstkey, final ZParams params,
final String... sets); final String... sets);
public void zinterstore(final String dstkey, final String... sets); public void zinterstore(final String dstkey, final String... sets);
public void zinterstore(final String dstkey, final ZParams params, public void zinterstore(final String dstkey, final ZParams params,
final String... sets); final String... sets);
public void strlen(final String key); public void strlen(final String key);
@@ -268,7 +268,7 @@ public interface Commands {
public void echo(final String string); public void echo(final String string);
public void linsert(final String key, final LIST_POSITION where, public void linsert(final String key, final LIST_POSITION where,
final String pivot, final String value); final String pivot, final String value);
public void bgrewriteaof(); public void bgrewriteaof();
@@ -305,13 +305,13 @@ public interface Commands {
public void scan(final String cursor, final ScanParams params); public void scan(final String cursor, final ScanParams params);
public void hscan(final String key, final String cursor, public void hscan(final String key, final String cursor,
final ScanParams params); final ScanParams params);
public void sscan(final String key, final String cursor, public void sscan(final String key, final String cursor,
final ScanParams params); final ScanParams params);
public void zscan(final String key, final String cursor, public void zscan(final String key, final String cursor,
final ScanParams params); final ScanParams params);
public void waitReplicas(int replicas, long timeout); public void waitReplicas(int replicas, long timeout);
} }

View File

@@ -29,239 +29,239 @@ public class Connection implements Closeable {
} }
public Connection(final String host) { public Connection(final String host) {
this.host = host; this.host = host;
} }
public Connection(final String host, final int port) { public Connection(final String host, final int port) {
this.host = host; this.host = host;
this.port = port; this.port = port;
} }
public Socket getSocket() { public Socket getSocket() {
return socket; return socket;
} }
public int getTimeout() { public int getTimeout() {
return timeout; return timeout;
} }
public void setTimeout(final int timeout) { public void setTimeout(final int timeout) {
this.timeout = timeout; this.timeout = timeout;
} }
public void setTimeoutInfinite() { public void setTimeoutInfinite() {
try { try {
if (!isConnected()) { if (!isConnected()) {
connect(); connect();
} }
socket.setSoTimeout(0); socket.setSoTimeout(0);
} catch (SocketException ex) { } catch (SocketException ex) {
broken = true; broken = true;
throw new JedisConnectionException(ex); throw new JedisConnectionException(ex);
} }
} }
public void rollbackTimeout() { public void rollbackTimeout() {
try { try {
socket.setSoTimeout(timeout); socket.setSoTimeout(timeout);
} catch (SocketException ex) { } catch (SocketException ex) {
broken = true; broken = true;
throw new JedisConnectionException(ex); throw new JedisConnectionException(ex);
} }
} }
protected Connection sendCommand(final Command cmd, final String... args) { protected Connection sendCommand(final Command cmd, final String... args) {
final byte[][] bargs = new byte[args.length][]; final byte[][] bargs = new byte[args.length][];
for (int i = 0; i < args.length; i++) { for (int i = 0; i < args.length; i++) {
bargs[i] = SafeEncoder.encode(args[i]); bargs[i] = SafeEncoder.encode(args[i]);
} }
return sendCommand(cmd, bargs); return sendCommand(cmd, bargs);
} }
protected Connection sendCommand(final Command cmd, final byte[]... args) { protected Connection sendCommand(final Command cmd, final byte[]... args) {
try { try {
connect(); connect();
Protocol.sendCommand(outputStream, cmd, args); Protocol.sendCommand(outputStream, cmd, args);
return this; return this;
} catch (JedisConnectionException ex) { } catch (JedisConnectionException ex) {
// Any other exceptions related to connection? // Any other exceptions related to connection?
broken = true; broken = true;
throw ex; throw ex;
} }
} }
protected Connection sendCommand(final Command cmd) { protected Connection sendCommand(final Command cmd) {
try { try {
connect(); connect();
Protocol.sendCommand(outputStream, cmd, new byte[0][]); Protocol.sendCommand(outputStream, cmd, new byte[0][]);
return this; return this;
} catch (JedisConnectionException ex) { } catch (JedisConnectionException ex) {
// Any other exceptions related to connection? // Any other exceptions related to connection?
broken = true; broken = true;
throw ex; throw ex;
} }
} }
public String getHost() { public String getHost() {
return host; return host;
} }
public void setHost(final String host) { public void setHost(final String host) {
this.host = host; this.host = host;
} }
public int getPort() { public int getPort() {
return port; return port;
} }
public void setPort(final int port) { public void setPort(final int port) {
this.port = port; this.port = port;
} }
public void connect() { public void connect() {
if (!isConnected()) { if (!isConnected()) {
try { try {
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 socket.setKeepAlive(true); // Will monitor the TCP connection is
// valid // valid
socket.setTcpNoDelay(true); // Socket buffer Whetherclosed, to socket.setTcpNoDelay(true); // Socket buffer Whetherclosed, to
// ensure timely delivery of data // ensure timely delivery of data
socket.setSoLinger(true, 0); // Control calls close () method, socket.setSoLinger(true, 0); // Control calls close () method,
// the underlying socket is closed // the underlying socket is closed
// immediately // immediately
// <-@wjw_add // <-@wjw_add
socket.connect(new InetSocketAddress(host, port), timeout); socket.connect(new InetSocketAddress(host, port), timeout);
socket.setSoTimeout(timeout); socket.setSoTimeout(timeout);
outputStream = new RedisOutputStream(socket.getOutputStream()); outputStream = new RedisOutputStream(socket.getOutputStream());
inputStream = new RedisInputStream(socket.getInputStream()); inputStream = new RedisInputStream(socket.getInputStream());
} catch (IOException ex) { } catch (IOException ex) {
broken = true; broken = true;
throw new JedisConnectionException(ex); throw new JedisConnectionException(ex);
} }
} }
} }
@Override @Override
public void close() { public void close() {
disconnect(); disconnect();
} }
public void disconnect() { public void disconnect() {
if (isConnected()) { if (isConnected()) {
try { try {
inputStream.close(); inputStream.close();
if (!socket.isClosed()) { if (!socket.isClosed()) {
outputStream.close(); outputStream.close();
socket.close(); socket.close();
} }
} catch (IOException ex) { } catch (IOException ex) {
broken = true; broken = true;
throw new JedisConnectionException(ex); throw new JedisConnectionException(ex);
} }
} }
} }
public boolean isConnected() { public boolean isConnected() {
return socket != null && socket.isBound() && !socket.isClosed() return socket != null && socket.isBound() && !socket.isClosed()
&& socket.isConnected() && !socket.isInputShutdown() && socket.isConnected() && !socket.isInputShutdown()
&& !socket.isOutputShutdown(); && !socket.isOutputShutdown();
} }
public String getStatusCodeReply() { public String getStatusCodeReply() {
flush(); flush();
final byte[] resp = (byte[]) readProtocolWithCheckingBroken(); final byte[] resp = (byte[]) readProtocolWithCheckingBroken();
if (null == resp) { if (null == resp) {
return null; return null;
} else { } else {
return SafeEncoder.encode(resp); return SafeEncoder.encode(resp);
} }
} }
public String getBulkReply() { public String getBulkReply() {
final byte[] result = getBinaryBulkReply(); final byte[] result = getBinaryBulkReply();
if (null != result) { if (null != result) {
return SafeEncoder.encode(result); return SafeEncoder.encode(result);
} else { } else {
return null; return null;
} }
} }
public byte[] getBinaryBulkReply() { public byte[] getBinaryBulkReply() {
flush(); flush();
return (byte[]) readProtocolWithCheckingBroken(); return (byte[]) readProtocolWithCheckingBroken();
} }
public Long getIntegerReply() { public Long getIntegerReply() {
flush(); flush();
return (Long) readProtocolWithCheckingBroken(); return (Long) readProtocolWithCheckingBroken();
} }
public List<String> getMultiBulkReply() { public List<String> getMultiBulkReply() {
return BuilderFactory.STRING_LIST.build(getBinaryMultiBulkReply()); return BuilderFactory.STRING_LIST.build(getBinaryMultiBulkReply());
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public List<byte[]> getBinaryMultiBulkReply() { public List<byte[]> getBinaryMultiBulkReply() {
flush(); flush();
return (List<byte[]>) readProtocolWithCheckingBroken(); return (List<byte[]>) readProtocolWithCheckingBroken();
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public List<Object> getRawObjectMultiBulkReply() { public List<Object> getRawObjectMultiBulkReply() {
return (List<Object>) readProtocolWithCheckingBroken(); return (List<Object>) readProtocolWithCheckingBroken();
} }
public List<Object> getObjectMultiBulkReply() { public List<Object> getObjectMultiBulkReply() {
flush(); flush();
return getRawObjectMultiBulkReply(); return getRawObjectMultiBulkReply();
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public List<Long> getIntegerMultiBulkReply() { public List<Long> getIntegerMultiBulkReply() {
flush(); flush();
return (List<Long>) Protocol.read(inputStream); return (List<Long>) Protocol.read(inputStream);
} }
public Object getOne() { public Object getOne() {
flush(); flush();
return readProtocolWithCheckingBroken(); return readProtocolWithCheckingBroken();
} }
public boolean isBroken() { public boolean isBroken() {
return broken; return broken;
} }
protected void flush() { protected void flush() {
try { try {
outputStream.flush(); outputStream.flush();
} catch (IOException ex) { } catch (IOException ex) {
broken = true; broken = true;
throw new JedisConnectionException(ex); throw new JedisConnectionException(ex);
} }
} }
protected Object readProtocolWithCheckingBroken() { protected Object readProtocolWithCheckingBroken() {
try { try {
return Protocol.read(inputStream); return Protocol.read(inputStream);
} catch (JedisConnectionException exc) { } catch (JedisConnectionException exc) {
broken = true; broken = true;
throw exc; throw exc;
} }
} }
public List<Object> getMany(final int count) { public List<Object> getMany(final int count) {
flush(); flush();
final List<Object> responses = new ArrayList<Object>(count); final List<Object> responses = new ArrayList<Object>(count);
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
try { try {
responses.add(readProtocolWithCheckingBroken()); responses.add(readProtocolWithCheckingBroken());
} catch (JedisDataException e) { } catch (JedisDataException e) {
responses.add(e); responses.add(e);
} }
} }
return responses; return responses;
} }
} }

View File

@@ -4,7 +4,7 @@ public class DebugParams {
private String[] command; private String[] command;
public String[] getCommand() { public String[] getCommand() {
return command; return command;
} }
private DebugParams() { private DebugParams() {
@@ -12,20 +12,20 @@ public class DebugParams {
} }
public static DebugParams SEGFAULT() { public static DebugParams SEGFAULT() {
DebugParams debugParams = new DebugParams(); DebugParams debugParams = new DebugParams();
debugParams.command = new String[] { "SEGFAULT" }; debugParams.command = new String[] { "SEGFAULT" };
return debugParams; return debugParams;
} }
public static DebugParams OBJECT(String key) { public static DebugParams OBJECT(String key) {
DebugParams debugParams = new DebugParams(); DebugParams debugParams = new DebugParams();
debugParams.command = new String[] { "OBJECT", key }; debugParams.command = new String[] { "OBJECT", key };
return debugParams; return debugParams;
} }
public static DebugParams RELOAD() { public static DebugParams RELOAD() {
DebugParams debugParams = new DebugParams(); DebugParams debugParams = new DebugParams();
debugParams.command = new String[] { "RELOAD" }; debugParams.command = new String[] { "RELOAD" };
return debugParams; return debugParams;
} }
} }

View File

@@ -7,48 +7,48 @@ public class HostAndPort {
private int port; private int port;
public HostAndPort(String host, int port) { public HostAndPort(String host, int port) {
this.host = host; this.host = host;
this.port = port; this.port = port;
} }
public String getHost() { public String getHost() {
return host; return host;
} }
public int getPort() { public int getPort() {
return port; return port;
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (obj instanceof HostAndPort) { if (obj instanceof HostAndPort) {
HostAndPort hp = (HostAndPort) obj; HostAndPort hp = (HostAndPort) obj;
String thisHost = convertHost(host); String thisHost = convertHost(host);
String hpHost = convertHost(hp.host); String hpHost = convertHost(hp.host);
return port == hp.port && thisHost.equals(hpHost); return port == hp.port && thisHost.equals(hpHost);
} }
return false; return false;
} }
@Override @Override
public int hashCode() { public int hashCode() {
return 31 * convertHost(host).hashCode() + port; return 31 * convertHost(host).hashCode() + port;
} }
@Override @Override
public String toString() { public String toString() {
return host + ":" + port; return host + ":" + port;
} }
private String convertHost(String host) { private String convertHost(String host) {
if (host.equals("127.0.0.1")) if (host.equals("127.0.0.1"))
return LOCALHOST_STR; return LOCALHOST_STR;
else if (host.equals("::1")) else if (host.equals("::1"))
return LOCALHOST_STR; return LOCALHOST_STR;
return host; return host;
} }
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -16,94 +16,94 @@ public abstract class JedisClusterCommand<T> {
private ThreadLocal<Jedis> askConnection = new ThreadLocal<Jedis>(); private ThreadLocal<Jedis> askConnection = new ThreadLocal<Jedis>();
public JedisClusterCommand(JedisClusterConnectionHandler connectionHandler, public JedisClusterCommand(JedisClusterConnectionHandler connectionHandler,
int timeout, int maxRedirections) { int timeout, int maxRedirections) {
this.connectionHandler = connectionHandler; this.connectionHandler = connectionHandler;
this.commandTimeout = timeout; this.commandTimeout = timeout;
this.redirections = maxRedirections; this.redirections = maxRedirections;
} }
public abstract T execute(Jedis connection); public abstract T execute(Jedis connection);
public T run(String key) { public T run(String key) {
if (key == null) { if (key == null) {
throw new JedisClusterException( throw new JedisClusterException(
"No way to dispatch this command to Redis Cluster."); "No way to dispatch this command to Redis Cluster.");
} }
return runWithRetries(key, this.redirections, false, false); return runWithRetries(key, this.redirections, false, false);
} }
private T runWithRetries(String key, int redirections, private T runWithRetries(String key, int redirections,
boolean tryRandomNode, boolean asking) { boolean tryRandomNode, boolean asking) {
if (redirections <= 0) { if (redirections <= 0) {
throw new JedisClusterMaxRedirectionsException( throw new JedisClusterMaxRedirectionsException(
"Too many Cluster redirections?"); "Too many Cluster redirections?");
} }
Jedis connection = null; Jedis connection = null;
try { try {
if (asking) { if (asking) {
// TODO: Pipeline asking with the original command to make it // TODO: Pipeline asking with the original command to make it
// faster.... // faster....
connection = askConnection.get(); connection = askConnection.get();
connection.asking(); connection.asking();
// if asking success, reset asking flag // if asking success, reset asking flag
asking = false; asking = false;
} else { } else {
if (tryRandomNode) { if (tryRandomNode) {
connection = connectionHandler.getConnection(); connection = connectionHandler.getConnection();
} else { } else {
connection = connectionHandler connection = connectionHandler
.getConnectionFromSlot(JedisClusterCRC16 .getConnectionFromSlot(JedisClusterCRC16
.getSlot(key)); .getSlot(key));
} }
} }
return execute(connection); return execute(connection);
} catch (JedisConnectionException jce) { } catch (JedisConnectionException jce) {
if (tryRandomNode) { if (tryRandomNode) {
// maybe all connection is down // maybe all connection is down
throw jce; throw jce;
} }
releaseConnection(connection, true); releaseConnection(connection, true);
connection = null; connection = null;
// retry with random connection // retry with random connection
return runWithRetries(key, redirections - 1, true, asking); return runWithRetries(key, redirections - 1, true, asking);
} catch (JedisRedirectionException jre) { } catch (JedisRedirectionException jre) {
if (jre instanceof JedisAskDataException) { if (jre instanceof JedisAskDataException) {
asking = true; asking = true;
askConnection.set(this.connectionHandler askConnection.set(this.connectionHandler
.getConnectionFromNode(jre.getTargetNode())); .getConnectionFromNode(jre.getTargetNode()));
} else if (jre instanceof JedisMovedDataException) { } else if (jre instanceof JedisMovedDataException) {
// it rebuilds cluster's slot cache // it rebuilds cluster's slot cache
// recommended by Redis cluster specification // recommended by Redis cluster specification
this.connectionHandler.renewSlotCache(); this.connectionHandler.renewSlotCache();
} else { } else {
throw new JedisClusterException(jre); throw new JedisClusterException(jre);
} }
releaseConnection(connection, false); releaseConnection(connection, false);
connection = null; connection = null;
return runWithRetries(key, redirections - 1, false, asking); return runWithRetries(key, redirections - 1, false, asking);
} finally { } finally {
releaseConnection(connection, false); releaseConnection(connection, false);
} }
} }
private void releaseConnection(Jedis connection, boolean broken) { private void releaseConnection(Jedis connection, boolean broken) {
if (connection != null) { if (connection != null) {
if (broken) { if (broken) {
connectionHandler.returnBrokenConnection(connection); connectionHandler.returnBrokenConnection(connection);
} else { } else {
connectionHandler.returnConnection(connection); connectionHandler.returnConnection(connection);
} }
} }
} }
} }

View File

@@ -15,75 +15,75 @@ public abstract class JedisClusterConnectionHandler {
abstract Jedis getConnection(); abstract Jedis getConnection();
public void returnConnection(Jedis connection) { public void returnConnection(Jedis connection) {
cache.getNode(getNodeKey(connection.getClient())).returnResource( cache.getNode(getNodeKey(connection.getClient())).returnResource(
connection); connection);
} }
public void returnBrokenConnection(Jedis connection) { public void returnBrokenConnection(Jedis connection) {
cache.getNode(getNodeKey(connection.getClient())).returnBrokenResource( cache.getNode(getNodeKey(connection.getClient())).returnBrokenResource(
connection); connection);
} }
abstract Jedis getConnectionFromSlot(int slot); abstract Jedis getConnectionFromSlot(int slot);
public Jedis getConnectionFromNode(HostAndPort node) { public Jedis getConnectionFromNode(HostAndPort node) {
cache.setNodeIfNotExist(node); cache.setNodeIfNotExist(node);
return cache.getNode(JedisClusterInfoCache.getNodeKey(node)) return cache.getNode(JedisClusterInfoCache.getNodeKey(node))
.getResource(); .getResource();
} }
public JedisClusterConnectionHandler(Set<HostAndPort> nodes, public JedisClusterConnectionHandler(Set<HostAndPort> nodes,
final GenericObjectPoolConfig poolConfig) { final GenericObjectPoolConfig poolConfig) {
this.cache = new JedisClusterInfoCache(poolConfig); this.cache = new JedisClusterInfoCache(poolConfig);
initializeSlotsCache(nodes, poolConfig); initializeSlotsCache(nodes, poolConfig);
} }
public Map<String, JedisPool> getNodes() { public Map<String, JedisPool> getNodes() {
return cache.getNodes(); return cache.getNodes();
} }
public void assignSlotToNode(int slot, HostAndPort targetNode) { public void assignSlotToNode(int slot, HostAndPort targetNode) {
cache.assignSlotToNode(slot, targetNode); cache.assignSlotToNode(slot, targetNode);
} }
private void initializeSlotsCache(Set<HostAndPort> startNodes, private void initializeSlotsCache(Set<HostAndPort> startNodes,
GenericObjectPoolConfig poolConfig) { GenericObjectPoolConfig poolConfig) {
for (HostAndPort hostAndPort : startNodes) { for (HostAndPort hostAndPort : startNodes) {
JedisPool jp = new JedisPool(poolConfig, hostAndPort.getHost(), JedisPool jp = new JedisPool(poolConfig, hostAndPort.getHost(),
hostAndPort.getPort()); hostAndPort.getPort());
Jedis jedis = null; Jedis jedis = null;
try { try {
jedis = jp.getResource(); jedis = jp.getResource();
cache.discoverClusterNodesAndSlots(jedis); cache.discoverClusterNodesAndSlots(jedis);
break; break;
} catch (JedisConnectionException e) { } catch (JedisConnectionException e) {
// try next nodes // try next nodes
} finally { } finally {
if (jedis != null) { if (jedis != null) {
jedis.close(); jedis.close();
} }
} }
} }
for (HostAndPort node : startNodes) { for (HostAndPort node : startNodes) {
cache.setNodeIfNotExist(node); cache.setNodeIfNotExist(node);
} }
} }
public void renewSlotCache() { public void renewSlotCache() {
for (JedisPool jp : cache.getNodes().values()) { for (JedisPool jp : cache.getNodes().values()) {
Jedis jedis = null; Jedis jedis = null;
try { try {
jedis = jp.getResource(); jedis = jp.getResource();
cache.discoverClusterSlots(jedis); cache.discoverClusterSlots(jedis);
break; break;
} finally { } finally {
if (jedis != null) { if (jedis != null) {
jedis.close(); jedis.close();
} }
} }
} }
} }
} }

View File

@@ -25,166 +25,166 @@ public class JedisClusterInfoCache {
private final GenericObjectPoolConfig poolConfig; private final GenericObjectPoolConfig poolConfig;
public JedisClusterInfoCache(final GenericObjectPoolConfig poolConfig) { public JedisClusterInfoCache(final GenericObjectPoolConfig poolConfig) {
this.poolConfig = poolConfig; this.poolConfig = poolConfig;
} }
public void discoverClusterNodesAndSlots(Jedis jedis) { public void discoverClusterNodesAndSlots(Jedis jedis) {
w.lock(); w.lock();
try { try {
this.nodes.clear(); this.nodes.clear();
this.slots.clear(); this.slots.clear();
String localNodes = jedis.clusterNodes(); String localNodes = jedis.clusterNodes();
for (String nodeInfo : localNodes.split("\n")) { for (String nodeInfo : localNodes.split("\n")) {
ClusterNodeInformation clusterNodeInfo = nodeInfoParser.parse( ClusterNodeInformation clusterNodeInfo = nodeInfoParser.parse(
nodeInfo, new HostAndPort(jedis.getClient().getHost(), nodeInfo, new HostAndPort(jedis.getClient().getHost(),
jedis.getClient().getPort())); jedis.getClient().getPort()));
HostAndPort targetNode = clusterNodeInfo.getNode(); HostAndPort targetNode = clusterNodeInfo.getNode();
setNodeIfNotExist(targetNode); setNodeIfNotExist(targetNode);
assignSlotsToNode(clusterNodeInfo.getAvailableSlots(), assignSlotsToNode(clusterNodeInfo.getAvailableSlots(),
targetNode); targetNode);
} }
} finally { } finally {
w.unlock(); w.unlock();
} }
} }
public void discoverClusterSlots(Jedis jedis) { public void discoverClusterSlots(Jedis jedis) {
w.lock(); w.lock();
try { try {
this.slots.clear(); this.slots.clear();
List<Object> slots = jedis.clusterSlots(); List<Object> slots = jedis.clusterSlots();
for (Object slotInfoObj : slots) { for (Object slotInfoObj : slots) {
List<Object> slotInfo = (List<Object>) slotInfoObj; List<Object> slotInfo = (List<Object>) slotInfoObj;
if (slotInfo.size() <= 2) { if (slotInfo.size() <= 2) {
continue; continue;
} }
List<Integer> slotNums = getAssignedSlotArray(slotInfo); List<Integer> slotNums = getAssignedSlotArray(slotInfo);
// hostInfos // hostInfos
List<Object> hostInfos = (List<Object>) slotInfo.get(2); List<Object> hostInfos = (List<Object>) slotInfo.get(2);
if (hostInfos.size() <= 0) { if (hostInfos.size() <= 0) {
continue; continue;
} }
// at this time, we just use master, discard slave information // at this time, we just use master, discard slave information
HostAndPort targetNode = generateHostAndPort(hostInfos); HostAndPort targetNode = generateHostAndPort(hostInfos);
setNodeIfNotExist(targetNode); setNodeIfNotExist(targetNode);
assignSlotsToNode(slotNums, targetNode); assignSlotsToNode(slotNums, targetNode);
} }
} finally { } finally {
w.unlock(); w.unlock();
} }
} }
private HostAndPort generateHostAndPort(List<Object> hostInfos) { private HostAndPort generateHostAndPort(List<Object> hostInfos) {
return new HostAndPort(SafeEncoder.encode((byte[]) hostInfos.get(0)), return new HostAndPort(SafeEncoder.encode((byte[]) hostInfos.get(0)),
((Long) hostInfos.get(1)).intValue()); ((Long) hostInfos.get(1)).intValue());
} }
public void setNodeIfNotExist(HostAndPort node) { public void setNodeIfNotExist(HostAndPort node) {
w.lock(); w.lock();
try { try {
String nodeKey = getNodeKey(node); String nodeKey = getNodeKey(node);
if (nodes.containsKey(nodeKey)) if (nodes.containsKey(nodeKey))
return; return;
JedisPool nodePool = new JedisPool(poolConfig, node.getHost(), JedisPool nodePool = new JedisPool(poolConfig, node.getHost(),
node.getPort()); node.getPort());
nodes.put(nodeKey, nodePool); nodes.put(nodeKey, nodePool);
} finally { } finally {
w.unlock(); w.unlock();
} }
} }
public void assignSlotToNode(int slot, HostAndPort targetNode) { public void assignSlotToNode(int slot, HostAndPort targetNode) {
w.lock(); w.lock();
try { try {
JedisPool targetPool = nodes.get(getNodeKey(targetNode)); JedisPool targetPool = nodes.get(getNodeKey(targetNode));
if (targetPool == null) { if (targetPool == null) {
setNodeIfNotExist(targetNode); setNodeIfNotExist(targetNode);
targetPool = nodes.get(getNodeKey(targetNode)); targetPool = nodes.get(getNodeKey(targetNode));
} }
slots.put(slot, targetPool); slots.put(slot, targetPool);
} finally { } finally {
w.unlock(); w.unlock();
} }
} }
public void assignSlotsToNode(List<Integer> targetSlots, public void assignSlotsToNode(List<Integer> targetSlots,
HostAndPort targetNode) { HostAndPort targetNode) {
w.lock(); w.lock();
try { try {
JedisPool targetPool = nodes.get(getNodeKey(targetNode)); JedisPool targetPool = nodes.get(getNodeKey(targetNode));
if (targetPool == null) { if (targetPool == null) {
setNodeIfNotExist(targetNode); setNodeIfNotExist(targetNode);
targetPool = nodes.get(getNodeKey(targetNode)); targetPool = nodes.get(getNodeKey(targetNode));
} }
for (Integer slot : targetSlots) { for (Integer slot : targetSlots) {
slots.put(slot, targetPool); slots.put(slot, targetPool);
} }
} finally { } finally {
w.unlock(); w.unlock();
} }
} }
public JedisPool getNode(String nodeKey) { public JedisPool getNode(String nodeKey) {
r.lock(); r.lock();
try { try {
return nodes.get(nodeKey); return nodes.get(nodeKey);
} finally { } finally {
r.unlock(); r.unlock();
} }
} }
public JedisPool getSlotPool(int slot) { public JedisPool getSlotPool(int slot) {
r.lock(); r.lock();
try { try {
return slots.get(slot); return slots.get(slot);
} finally { } finally {
r.unlock(); r.unlock();
} }
} }
public Map<String, JedisPool> getNodes() { public Map<String, JedisPool> getNodes() {
r.lock(); r.lock();
try { try {
return new HashMap<String, JedisPool>(nodes); return new HashMap<String, JedisPool>(nodes);
} finally { } finally {
r.unlock(); r.unlock();
} }
} }
public static String getNodeKey(HostAndPort hnp) { public static String getNodeKey(HostAndPort hnp) {
return hnp.getHost() + ":" + hnp.getPort(); return hnp.getHost() + ":" + hnp.getPort();
} }
public static String getNodeKey(Client client) { public static String getNodeKey(Client client) {
return client.getHost() + ":" + client.getPort(); return client.getHost() + ":" + client.getPort();
} }
public static String getNodeKey(Jedis jedis) { public static String getNodeKey(Jedis jedis) {
return getNodeKey(jedis.getClient()); return getNodeKey(jedis.getClient());
} }
private List<Integer> getAssignedSlotArray(List<Object> slotInfo) { private List<Integer> getAssignedSlotArray(List<Object> slotInfo) {
List<Integer> slotNums = new ArrayList<Integer>(); List<Integer> slotNums = new ArrayList<Integer>();
for (int slot = ((Long) slotInfo.get(0)).intValue(); slot <= ((Long) slotInfo for (int slot = ((Long) slotInfo.get(0)).intValue(); slot <= ((Long) slotInfo
.get(1)).intValue(); slot++) { .get(1)).intValue(); slot++) {
slotNums.add(slot); slotNums.add(slot);
} }
return slotNums; return slotNums;
} }
} }

View File

@@ -157,38 +157,38 @@ public interface JedisCommands {
Set<String> zrevrangeByScore(String key, double max, double min); Set<String> zrevrangeByScore(String key, double max, double min);
Set<String> zrangeByScore(String key, double min, double max, int offset, Set<String> zrangeByScore(String key, double min, double max, int offset,
int count); int count);
Set<String> zrevrangeByScore(String key, String max, String min); Set<String> zrevrangeByScore(String key, String max, String min);
Set<String> zrangeByScore(String key, String min, String max, int offset, Set<String> zrangeByScore(String key, String min, String max, int offset,
int count); int count);
Set<String> zrevrangeByScore(String key, double max, double min, Set<String> zrevrangeByScore(String key, double max, double min,
int offset, int count); int offset, int count);
Set<Tuple> zrangeByScoreWithScores(String key, double min, double max); Set<Tuple> zrangeByScoreWithScores(String key, double min, double max);
Set<Tuple> zrevrangeByScoreWithScores(String key, double max, double min); Set<Tuple> zrevrangeByScoreWithScores(String key, double max, double min);
Set<Tuple> zrangeByScoreWithScores(String key, double min, double max, Set<Tuple> zrangeByScoreWithScores(String key, double min, double max,
int offset, int count); int offset, int count);
Set<String> zrevrangeByScore(String key, String max, String min, Set<String> zrevrangeByScore(String key, String max, String min,
int offset, int count); int offset, int count);
Set<Tuple> zrangeByScoreWithScores(String key, String min, String max); Set<Tuple> zrangeByScoreWithScores(String key, String min, String max);
Set<Tuple> zrevrangeByScoreWithScores(String key, String max, String min); Set<Tuple> zrevrangeByScoreWithScores(String key, String max, String min);
Set<Tuple> zrangeByScoreWithScores(String key, String min, String max, Set<Tuple> zrangeByScoreWithScores(String key, String min, String max,
int offset, int count); int offset, int count);
Set<Tuple> zrevrangeByScoreWithScores(String key, double max, double min, Set<Tuple> zrevrangeByScoreWithScores(String key, double max, double min,
int offset, int count); int offset, int count);
Set<Tuple> zrevrangeByScoreWithScores(String key, String max, String min, Set<Tuple> zrevrangeByScoreWithScores(String key, String max, String min,
int offset, int count); int offset, int count);
Long zremrangeByRank(String key, long start, long end); Long zremrangeByRank(String key, long start, long end);
@@ -201,18 +201,18 @@ public interface JedisCommands {
Set<String> zrangeByLex(final String key, final String min, final String max); Set<String> zrangeByLex(final String key, final String min, final String max);
Set<String> zrangeByLex(final String key, final String min, Set<String> zrangeByLex(final String key, final String min,
final String max, final int offset, final int count); final String max, final int offset, final int count);
Set<String> zrevrangeByLex(final String key, final String max, Set<String> zrevrangeByLex(final String key, final String max,
final String min); final String min);
Set<String> zrevrangeByLex(final String key, final String max, Set<String> zrevrangeByLex(final String key, final String max,
final String min, final int offset, final int count); final String min, final int offset, final int count);
Long zremrangeByLex(final String key, final String min, final String max); Long zremrangeByLex(final String key, final String min, final String max);
Long linsert(String key, Client.LIST_POSITION where, String pivot, Long linsert(String key, Client.LIST_POSITION where, String pivot,
String value); String value);
Long lpushx(String key, String... string); Long lpushx(String key, String... string);
@@ -245,7 +245,7 @@ public interface JedisCommands {
Long bitcount(final String key, long start, long end); Long bitcount(final String key, long start, long end);
ScanResult<Map.Entry<String, String>> hscan(final String key, ScanResult<Map.Entry<String, String>> hscan(final String key,
final String cursor); final String cursor);
ScanResult<String> sscan(final String key, final String cursor); ScanResult<String> sscan(final String key, final String cursor);

View File

@@ -17,91 +17,91 @@ class JedisFactory implements PooledObjectFactory<Jedis> {
private final String clientName; private final String clientName;
public JedisFactory(final String host, final int port, final int timeout, public JedisFactory(final String host, final int port, final int timeout,
final String password, final int database) { final String password, final int database) {
this(host, port, timeout, password, database, null); this(host, port, timeout, password, database, null);
} }
public JedisFactory(final String host, final int port, final int timeout, public JedisFactory(final String host, final int port, final int timeout,
final String password, final int database, final String clientName) { final String password, final int database, final String clientName) {
super(); super();
this.hostAndPort.set(new HostAndPort(host, port)); this.hostAndPort.set(new HostAndPort(host, port));
this.timeout = timeout; this.timeout = timeout;
this.password = password; this.password = password;
this.database = database; this.database = database;
this.clientName = clientName; this.clientName = clientName;
} }
public void setHostAndPort(final HostAndPort hostAndPort) { public void setHostAndPort(final HostAndPort hostAndPort) {
this.hostAndPort.set(hostAndPort); this.hostAndPort.set(hostAndPort);
} }
@Override @Override
public void activateObject(PooledObject<Jedis> pooledJedis) public void activateObject(PooledObject<Jedis> pooledJedis)
throws Exception { throws Exception {
final BinaryJedis jedis = pooledJedis.getObject(); final BinaryJedis jedis = pooledJedis.getObject();
if (jedis.getDB() != database) { if (jedis.getDB() != database) {
jedis.select(database); jedis.select(database);
} }
} }
@Override @Override
public void destroyObject(PooledObject<Jedis> pooledJedis) throws Exception { public void destroyObject(PooledObject<Jedis> pooledJedis) throws Exception {
final BinaryJedis jedis = pooledJedis.getObject(); final BinaryJedis jedis = pooledJedis.getObject();
if (jedis.isConnected()) { if (jedis.isConnected()) {
try { try {
try { try {
jedis.quit(); jedis.quit();
} catch (Exception e) { } catch (Exception e) {
} }
jedis.disconnect(); jedis.disconnect();
} catch (Exception e) { } catch (Exception e) {
} }
} }
} }
@Override @Override
public PooledObject<Jedis> makeObject() throws Exception { public PooledObject<Jedis> makeObject() throws Exception {
final HostAndPort hostAndPort = this.hostAndPort.get(); final HostAndPort hostAndPort = this.hostAndPort.get();
final Jedis jedis = new Jedis(hostAndPort.getHost(), final Jedis jedis = new Jedis(hostAndPort.getHost(),
hostAndPort.getPort(), this.timeout); hostAndPort.getPort(), this.timeout);
jedis.connect(); jedis.connect();
if (null != this.password) { if (null != this.password) {
jedis.auth(this.password); jedis.auth(this.password);
} }
if (database != 0) { if (database != 0) {
jedis.select(database); jedis.select(database);
} }
if (clientName != null) { if (clientName != null) {
jedis.clientSetname(clientName); jedis.clientSetname(clientName);
} }
return new DefaultPooledObject<Jedis>(jedis); return new DefaultPooledObject<Jedis>(jedis);
} }
@Override @Override
public void passivateObject(PooledObject<Jedis> pooledJedis) public void passivateObject(PooledObject<Jedis> pooledJedis)
throws Exception { throws Exception {
// TODO maybe should select db 0? Not sure right now. // TODO maybe should select db 0? Not sure right now.
} }
@Override @Override
public boolean validateObject(PooledObject<Jedis> pooledJedis) { public boolean validateObject(PooledObject<Jedis> pooledJedis) {
final BinaryJedis jedis = pooledJedis.getObject(); final BinaryJedis jedis = pooledJedis.getObject();
try { try {
HostAndPort hostAndPort = this.hostAndPort.get(); HostAndPort hostAndPort = this.hostAndPort.get();
String connectionHost = jedis.getClient().getHost(); String connectionHost = jedis.getClient().getHost();
int connectionPort = jedis.getClient().getPort(); int connectionPort = jedis.getClient().getPort();
return hostAndPort.getHost().equals(connectionHost) return hostAndPort.getHost().equals(connectionHost)
&& hostAndPort.getPort() == connectionPort && hostAndPort.getPort() == connectionPort
&& jedis.isConnected() && jedis.ping().equals("PONG"); && jedis.isConnected() && jedis.ping().equals("PONG");
} catch (final Exception e) { } catch (final Exception e) {
return false; return false;
} }
} }
} }

View File

@@ -4,12 +4,12 @@ public abstract class JedisMonitor {
protected Client client; protected Client client;
public void proceed(Client client) { public void proceed(Client client) {
this.client = client; this.client = client;
this.client.setTimeoutInfinite(); this.client.setTimeoutInfinite();
do { do {
String command = client.getBulkReply(); String command = client.getBulkReply();
onCommand(command); onCommand(command);
} while (client.isConnected()); } while (client.isConnected());
} }
public abstract void onCommand(String command); public abstract void onCommand(String command);

View File

@@ -12,104 +12,104 @@ import redis.clients.util.Pool;
public class JedisPool extends Pool<Jedis> { public class JedisPool extends Pool<Jedis> {
public JedisPool() { public JedisPool() {
this(Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT); this(Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT);
} }
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host) { public JedisPool(final GenericObjectPoolConfig poolConfig, final String host) {
this(poolConfig, host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT, this(poolConfig, host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT,
null, Protocol.DEFAULT_DATABASE, null); null, Protocol.DEFAULT_DATABASE, null);
} }
public JedisPool(String host, int port) { public JedisPool(String host, int port) {
this(new GenericObjectPoolConfig(), host, port, this(new GenericObjectPoolConfig(), host, port,
Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE, null); Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE, null);
} }
public JedisPool(final String host) { public JedisPool(final String host) {
URI uri = URI.create(host); URI uri = URI.create(host);
if (uri.getScheme() != null && uri.getScheme().equals("redis")) { if (uri.getScheme() != null && uri.getScheme().equals("redis")) {
String h = uri.getHost(); String h = uri.getHost();
int port = uri.getPort(); int port = uri.getPort();
String password = JedisURIHelper.getPassword(uri); String password = JedisURIHelper.getPassword(uri);
int database = 0; int database = 0;
Integer dbIndex = JedisURIHelper.getDBIndex(uri); Integer dbIndex = JedisURIHelper.getDBIndex(uri);
if (dbIndex != null) { if (dbIndex != null) {
database = dbIndex.intValue(); database = dbIndex.intValue();
} }
this.internalPool = new GenericObjectPool<Jedis>( this.internalPool = new GenericObjectPool<Jedis>(
new JedisFactory(h, port, Protocol.DEFAULT_TIMEOUT, new JedisFactory(h, port, Protocol.DEFAULT_TIMEOUT,
password, database, null), password, database, null),
new GenericObjectPoolConfig()); new GenericObjectPoolConfig());
} else { } else {
this.internalPool = new GenericObjectPool<Jedis>(new JedisFactory( this.internalPool = new GenericObjectPool<Jedis>(new JedisFactory(
host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT, host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT,
null, Protocol.DEFAULT_DATABASE, null), null, Protocol.DEFAULT_DATABASE, null),
new GenericObjectPoolConfig()); new GenericObjectPoolConfig());
} }
} }
public JedisPool(final URI uri) { public JedisPool(final URI uri) {
this(new GenericObjectPoolConfig(), uri, Protocol.DEFAULT_TIMEOUT); this(new GenericObjectPoolConfig(), uri, Protocol.DEFAULT_TIMEOUT);
} }
public JedisPool(final URI uri, final int timeout) { public JedisPool(final URI uri, final int timeout) {
this(new GenericObjectPoolConfig(), uri, timeout); this(new GenericObjectPoolConfig(), uri, timeout);
} }
public JedisPool(final GenericObjectPoolConfig poolConfig, public JedisPool(final GenericObjectPoolConfig poolConfig,
final String host, int port, int timeout, final String password) { final String host, int port, int timeout, final String password) {
this(poolConfig, host, port, timeout, password, this(poolConfig, host, port, timeout, password,
Protocol.DEFAULT_DATABASE, null); Protocol.DEFAULT_DATABASE, null);
} }
public JedisPool(final GenericObjectPoolConfig poolConfig, public JedisPool(final GenericObjectPoolConfig poolConfig,
final String host, final int port) { final String host, final int port) {
this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT, null, this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT, null,
Protocol.DEFAULT_DATABASE, null); Protocol.DEFAULT_DATABASE, null);
} }
public JedisPool(final GenericObjectPoolConfig poolConfig, public JedisPool(final GenericObjectPoolConfig poolConfig,
final String host, final int port, final int timeout) { final String host, final int port, final int timeout) {
this(poolConfig, host, port, timeout, null, Protocol.DEFAULT_DATABASE, this(poolConfig, host, port, timeout, null, Protocol.DEFAULT_DATABASE,
null); null);
} }
public JedisPool(final GenericObjectPoolConfig poolConfig, public JedisPool(final GenericObjectPoolConfig poolConfig,
final String host, int port, int timeout, final String password, final String host, int port, int timeout, final String password,
final int database) { final int database) {
this(poolConfig, host, port, timeout, password, database, null); this(poolConfig, host, port, timeout, password, database, null);
} }
public JedisPool(final GenericObjectPoolConfig poolConfig, public JedisPool(final GenericObjectPoolConfig poolConfig,
final String host, int port, int timeout, final String password, final String host, int port, int timeout, final String password,
final int database, final String clientName) { final int database, final String clientName) {
super(poolConfig, new JedisFactory(host, port, timeout, password, super(poolConfig, new JedisFactory(host, port, timeout, password,
database, clientName)); database, clientName));
} }
public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri) { public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri) {
this(poolConfig, uri, Protocol.DEFAULT_TIMEOUT); this(poolConfig, uri, Protocol.DEFAULT_TIMEOUT);
} }
public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri,
final int timeout) { final int timeout) {
super(poolConfig, new JedisFactory(uri.getHost(), uri.getPort(), super(poolConfig, new JedisFactory(uri.getHost(), uri.getPort(),
timeout, JedisURIHelper.getPassword(uri), timeout, JedisURIHelper.getPassword(uri),
JedisURIHelper.getDBIndex(uri) != null ? JedisURIHelper JedisURIHelper.getDBIndex(uri) != null ? JedisURIHelper
.getDBIndex(uri) : 0, null)); .getDBIndex(uri) : 0, null));
} }
@Override @Override
public Jedis getResource() { public Jedis getResource() {
Jedis jedis = super.getResource(); Jedis jedis = super.getResource();
jedis.setDataSource(this); jedis.setDataSource(this);
return jedis; return jedis;
} }
public void returnBrokenResource(final Jedis resource) { public void returnBrokenResource(final Jedis resource) {
if (resource != null) { if (resource != null) {
returnBrokenResourceObject(resource); returnBrokenResourceObject(resource);
} }
} }
public void returnResource(final Jedis resource) { public void returnResource(final Jedis resource) {
@@ -127,10 +127,10 @@ public class JedisPool extends Pool<Jedis> {
} }
public int getNumActive() { public int getNumActive() {
if (this.internalPool == null || this.internalPool.isClosed()) { if (this.internalPool == null || this.internalPool.isClosed()) {
return -1; return -1;
} }
return this.internalPool.getNumActive(); return this.internalPool.getNumActive();
} }
} }

View File

@@ -4,10 +4,10 @@ import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
public class JedisPoolConfig extends GenericObjectPoolConfig { public class JedisPoolConfig extends GenericObjectPoolConfig {
public JedisPoolConfig() { public JedisPoolConfig() {
// defaults to make your life with connection pool easier :) // defaults to make your life with connection pool easier :)
setTestWhileIdle(true); setTestWhileIdle(true);
setMinEvictableIdleTimeMillis(60000); setMinEvictableIdleTimeMillis(60000);
setTimeBetweenEvictionRunsMillis(30000); setTimeBetweenEvictionRunsMillis(30000);
setNumTestsPerEvictionRun(-1); setNumTestsPerEvictionRun(-1);
} }
} }

View File

@@ -18,152 +18,152 @@ public abstract class JedisPubSub {
private int subscribedChannels = 0; private int subscribedChannels = 0;
private volatile Client client; private volatile Client client;
public void onMessage(String channel, String message) {} public void onMessage(String channel, String message) {}
public void onPMessage(String pattern, String channel, String message) {} public void onPMessage(String pattern, String channel, String message) {}
public void onSubscribe(String channel, int subscribedChannels) {} public void onSubscribe(String channel, int subscribedChannels) {}
public void onUnsubscribe(String channel, int subscribedChannels) {} public void onUnsubscribe(String channel, int subscribedChannels) {}
public void onPUnsubscribe(String pattern, int subscribedChannels) {} public void onPUnsubscribe(String pattern, int subscribedChannels) {}
public void onPSubscribe(String pattern, int subscribedChannels) {} public void onPSubscribe(String pattern, int subscribedChannels) {}
public void unsubscribe() { public void unsubscribe() {
if (client == null) { if (client == null) {
throw new JedisConnectionException( throw new JedisConnectionException(
"JedisPubSub was not subscribed to a Jedis instance."); "JedisPubSub was not subscribed to a Jedis instance.");
} }
client.unsubscribe(); client.unsubscribe();
client.flush(); client.flush();
} }
public void unsubscribe(String... channels) { public void unsubscribe(String... channels) {
if (client == null) { if (client == null) {
throw new JedisConnectionException( throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance."); "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) { if (client == null) {
throw new JedisConnectionException( throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance."); "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) { if (client == null) {
throw new JedisConnectionException( throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance."); "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) { if (client == null) {
throw new JedisConnectionException( throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance."); "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) { if (client == null) {
throw new JedisConnectionException( throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance."); "JedisPubSub is not subscribed to a Jedis instance.");
} }
client.punsubscribe(patterns); client.punsubscribe(patterns);
client.flush(); client.flush();
} }
public boolean isSubscribed() { public boolean isSubscribed() {
return subscribedChannels > 0; return subscribedChannels > 0;
} }
public void proceedWithPatterns(Client client, String... patterns) { public void proceedWithPatterns(Client client, String... patterns) {
this.client = client; this.client = client;
client.psubscribe(patterns); client.psubscribe(patterns);
client.flush(); client.flush();
process(client); process(client);
} }
public void proceed(Client client, String... channels) { public void proceed(Client client, String... channels) {
this.client = client; this.client = client;
client.subscribe(channels); client.subscribe(channels);
client.flush(); client.flush();
process(client); process(client);
} }
private void process(Client client) { private void process(Client client) {
do { do {
List<Object> reply = client.getRawObjectMultiBulkReply(); 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);
} }
final byte[] resp = (byte[]) firstObj; final byte[] resp = (byte[]) firstObj;
if (Arrays.equals(SUBSCRIBE.raw, resp)) { if (Arrays.equals(SUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue(); subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bchannel = (byte[]) reply.get(1); final byte[] bchannel = (byte[]) reply.get(1);
final String strchannel = (bchannel == null) ? null final String strchannel = (bchannel == null) ? null
: SafeEncoder.encode(bchannel); : SafeEncoder.encode(bchannel);
onSubscribe(strchannel, subscribedChannels); onSubscribe(strchannel, subscribedChannels);
} else if (Arrays.equals(UNSUBSCRIBE.raw, resp)) { } else if (Arrays.equals(UNSUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue(); subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bchannel = (byte[]) reply.get(1); final byte[] bchannel = (byte[]) reply.get(1);
final String strchannel = (bchannel == null) ? null final String strchannel = (bchannel == null) ? null
: SafeEncoder.encode(bchannel); : SafeEncoder.encode(bchannel);
onUnsubscribe(strchannel, subscribedChannels); onUnsubscribe(strchannel, subscribedChannels);
} else if (Arrays.equals(MESSAGE.raw, resp)) { } else if (Arrays.equals(MESSAGE.raw, resp)) {
final byte[] bchannel = (byte[]) reply.get(1); final byte[] bchannel = (byte[]) reply.get(1);
final byte[] bmesg = (byte[]) reply.get(2); final byte[] bmesg = (byte[]) reply.get(2);
final String strchannel = (bchannel == null) ? null final String strchannel = (bchannel == null) ? null
: SafeEncoder.encode(bchannel); : SafeEncoder.encode(bchannel);
final String strmesg = (bmesg == null) ? null : SafeEncoder final String strmesg = (bmesg == null) ? null : SafeEncoder
.encode(bmesg); .encode(bmesg);
onMessage(strchannel, strmesg); onMessage(strchannel, strmesg);
} else if (Arrays.equals(PMESSAGE.raw, resp)) { } else if (Arrays.equals(PMESSAGE.raw, resp)) {
final byte[] bpattern = (byte[]) reply.get(1); final byte[] bpattern = (byte[]) reply.get(1);
final byte[] bchannel = (byte[]) reply.get(2); final byte[] bchannel = (byte[]) reply.get(2);
final byte[] bmesg = (byte[]) reply.get(3); final byte[] bmesg = (byte[]) reply.get(3);
final String strpattern = (bpattern == null) ? null final String strpattern = (bpattern == null) ? null
: SafeEncoder.encode(bpattern); : SafeEncoder.encode(bpattern);
final String strchannel = (bchannel == null) ? null final String strchannel = (bchannel == null) ? null
: SafeEncoder.encode(bchannel); : SafeEncoder.encode(bchannel);
final String strmesg = (bmesg == null) ? null : SafeEncoder final String strmesg = (bmesg == null) ? null : SafeEncoder
.encode(bmesg); .encode(bmesg);
onPMessage(strpattern, strchannel, strmesg); onPMessage(strpattern, strchannel, strmesg);
} else if (Arrays.equals(PSUBSCRIBE.raw, resp)) { } else if (Arrays.equals(PSUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue(); subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bpattern = (byte[]) reply.get(1); final byte[] bpattern = (byte[]) reply.get(1);
final String strpattern = (bpattern == null) ? null final String strpattern = (bpattern == null) ? null
: SafeEncoder.encode(bpattern); : SafeEncoder.encode(bpattern);
onPSubscribe(strpattern, subscribedChannels); onPSubscribe(strpattern, subscribedChannels);
} else if (Arrays.equals(PUNSUBSCRIBE.raw, resp)) { } else if (Arrays.equals(PUNSUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue(); subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bpattern = (byte[]) reply.get(1); final byte[] bpattern = (byte[]) reply.get(1);
final String strpattern = (bpattern == null) ? null final String strpattern = (bpattern == null) ? null
: SafeEncoder.encode(bpattern); : SafeEncoder.encode(bpattern);
onPUnsubscribe(strpattern, subscribedChannels); onPUnsubscribe(strpattern, subscribedChannels);
} else { } else {
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 */ /* Invalidate instance since this thread is no longer listening */
this.client = null; this.client = null;
} }
public int getSubscribedChannels() { public int getSubscribedChannels() {
return subscribedChannels; return subscribedChannels;
} }
} }

View File

@@ -28,294 +28,294 @@ public class JedisSentinelPool extends Pool<Jedis> {
protected Logger log = Logger.getLogger(getClass().getName()); protected Logger log = Logger.getLogger(getClass().getName());
public JedisSentinelPool(String masterName, Set<String> sentinels, public JedisSentinelPool(String masterName, Set<String> sentinels,
final GenericObjectPoolConfig poolConfig) { final GenericObjectPoolConfig poolConfig) {
this(masterName, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT, null, this(masterName, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT, null,
Protocol.DEFAULT_DATABASE); Protocol.DEFAULT_DATABASE);
} }
public JedisSentinelPool(String masterName, Set<String> sentinels) { public JedisSentinelPool(String masterName, Set<String> sentinels) {
this(masterName, sentinels, new GenericObjectPoolConfig(), this(masterName, sentinels, new GenericObjectPoolConfig(),
Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE); Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE);
} }
public JedisSentinelPool(String masterName, Set<String> sentinels, public JedisSentinelPool(String masterName, Set<String> sentinels,
String password) { String password) {
this(masterName, sentinels, new GenericObjectPoolConfig(), this(masterName, sentinels, new GenericObjectPoolConfig(),
Protocol.DEFAULT_TIMEOUT, password); Protocol.DEFAULT_TIMEOUT, password);
} }
public JedisSentinelPool(String masterName, Set<String> sentinels, public JedisSentinelPool(String masterName, Set<String> sentinels,
final GenericObjectPoolConfig poolConfig, int timeout, final GenericObjectPoolConfig poolConfig, int timeout,
final String password) { final String password) {
this(masterName, sentinels, poolConfig, timeout, password, this(masterName, sentinels, poolConfig, timeout, password,
Protocol.DEFAULT_DATABASE); Protocol.DEFAULT_DATABASE);
} }
public JedisSentinelPool(String masterName, Set<String> sentinels, public JedisSentinelPool(String masterName, Set<String> sentinels,
final GenericObjectPoolConfig poolConfig, final int timeout) { final GenericObjectPoolConfig poolConfig, final int timeout) {
this(masterName, sentinels, poolConfig, timeout, null, this(masterName, sentinels, poolConfig, timeout, null,
Protocol.DEFAULT_DATABASE); Protocol.DEFAULT_DATABASE);
} }
public JedisSentinelPool(String masterName, Set<String> sentinels, public JedisSentinelPool(String masterName, Set<String> sentinels,
final GenericObjectPoolConfig poolConfig, final String password) { final GenericObjectPoolConfig poolConfig, final String password) {
this(masterName, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT, this(masterName, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT,
password); password);
} }
public JedisSentinelPool(String masterName, Set<String> sentinels, public JedisSentinelPool(String masterName, Set<String> sentinels,
final GenericObjectPoolConfig poolConfig, int timeout, final GenericObjectPoolConfig poolConfig, int timeout,
final String password, final int database) { final String password, final int database) {
this.poolConfig = poolConfig; this.poolConfig = poolConfig;
this.timeout = timeout; this.timeout = timeout;
this.password = password; this.password = password;
this.database = database; this.database = database;
HostAndPort master = initSentinels(sentinels, masterName); HostAndPort master = initSentinels(sentinels, masterName);
initPool(master); initPool(master);
} }
private volatile JedisFactory factory; private volatile JedisFactory factory;
private volatile HostAndPort currentHostMaster; private volatile HostAndPort currentHostMaster;
public void destroy() { public void destroy() {
for (MasterListener m : masterListeners) { for (MasterListener m : masterListeners) {
m.shutdown(); m.shutdown();
} }
super.destroy(); super.destroy();
} }
public HostAndPort getCurrentHostMaster() { public HostAndPort getCurrentHostMaster() {
return currentHostMaster; return currentHostMaster;
} }
private void initPool(HostAndPort master) { private void initPool(HostAndPort master) {
if (!master.equals(currentHostMaster)) { if (!master.equals(currentHostMaster)) {
currentHostMaster = master; currentHostMaster = master;
if (factory == null) { if (factory == null) {
factory = new JedisFactory(master.getHost(), master.getPort(), factory = new JedisFactory(master.getHost(), master.getPort(),
timeout, password, database); timeout, password, database);
initPool(poolConfig, factory); initPool(poolConfig, factory);
} else { } else {
factory.setHostAndPort(currentHostMaster); factory.setHostAndPort(currentHostMaster);
// although we clear the pool, we still have to check the // although we clear the pool, we still have to check the
// returned object // returned object
// in getResource, this call only clears idle instances, not // in getResource, this call only clears idle instances, not
// borrowed instances // borrowed instances
internalPool.clear(); internalPool.clear();
} }
log.info("Created JedisPool to master at " + master); log.info("Created JedisPool to master at " + master);
} }
} }
private HostAndPort initSentinels(Set<String> sentinels, private HostAndPort initSentinels(Set<String> sentinels,
final String masterName) { final String masterName) {
HostAndPort master = null; HostAndPort master = null;
boolean sentinelAvailable = false; boolean sentinelAvailable = false;
log.info("Trying to find master from available Sentinels..."); log.info("Trying to find master from available Sentinels...");
for (String sentinel : sentinels) { for (String sentinel : sentinels) {
final HostAndPort hap = toHostAndPort(Arrays.asList(sentinel final HostAndPort hap = toHostAndPort(Arrays.asList(sentinel
.split(":"))); .split(":")));
log.fine("Connecting to Sentinel " + hap); log.fine("Connecting to Sentinel " + hap);
Jedis jedis = null; Jedis jedis = null;
try { try {
jedis = new Jedis(hap.getHost(), hap.getPort()); jedis = new Jedis(hap.getHost(), hap.getPort());
List<String> masterAddr = jedis List<String> masterAddr = jedis
.sentinelGetMasterAddrByName(masterName); .sentinelGetMasterAddrByName(masterName);
// connected to sentinel... // connected to sentinel...
sentinelAvailable = true; sentinelAvailable = true;
if (masterAddr == null || masterAddr.size() != 2) { if (masterAddr == null || masterAddr.size() != 2) {
log.warning("Can not get master addr, master name: " log.warning("Can not get master addr, master name: "
+ masterName + ". Sentinel: " + hap + "."); + masterName + ". Sentinel: " + hap + ".");
continue; continue;
} }
master = toHostAndPort(masterAddr); master = toHostAndPort(masterAddr);
log.fine("Found Redis master at " + master); log.fine("Found Redis master at " + master);
break; break;
} catch (JedisConnectionException e) { } catch (JedisConnectionException e) {
log.warning("Cannot connect to sentinel running @ " + hap log.warning("Cannot connect to sentinel running @ " + hap
+ ". Trying next one."); + ". Trying next one.");
} finally { } finally {
if (jedis != null) { if (jedis != null) {
jedis.close(); jedis.close();
} }
} }
} }
if (master == null) { if (master == null) {
if (sentinelAvailable) { if (sentinelAvailable) {
// can connect to sentinel, but master name seems to not // can connect to sentinel, but master name seems to not
// monitored // monitored
throw new JedisException("Can connect to sentinel, but " throw new JedisException("Can connect to sentinel, but "
+ masterName + " seems to be not monitored..."); + masterName + " seems to be not monitored...");
} else { } else {
throw new JedisConnectionException( throw new JedisConnectionException(
"All sentinels down, cannot determine where is " "All sentinels down, cannot determine where is "
+ masterName + " master is running..."); + masterName + " master is running...");
} }
} }
log.info("Redis master running at " + master log.info("Redis master running at " + master
+ ", starting Sentinel listeners..."); + ", starting Sentinel listeners...");
for (String sentinel : sentinels) { for (String sentinel : sentinels) {
final HostAndPort hap = toHostAndPort(Arrays.asList(sentinel final HostAndPort hap = toHostAndPort(Arrays.asList(sentinel
.split(":"))); .split(":")));
MasterListener masterListener = new MasterListener(masterName, MasterListener masterListener = new MasterListener(masterName,
hap.getHost(), hap.getPort()); hap.getHost(), hap.getPort());
masterListeners.add(masterListener); masterListeners.add(masterListener);
masterListener.start(); masterListener.start();
} }
return master; return master;
} }
private HostAndPort toHostAndPort(List<String> getMasterAddrByNameResult) { private HostAndPort toHostAndPort(List<String> getMasterAddrByNameResult) {
String host = getMasterAddrByNameResult.get(0); String host = getMasterAddrByNameResult.get(0);
int port = Integer.parseInt(getMasterAddrByNameResult.get(1)); int port = Integer.parseInt(getMasterAddrByNameResult.get(1));
return new HostAndPort(host, port); return new HostAndPort(host, port);
} }
@Override @Override
public Jedis getResource() { public Jedis getResource() {
while (true) { while (true) {
Jedis jedis = super.getResource(); Jedis jedis = super.getResource();
jedis.setDataSource(this); jedis.setDataSource(this);
// get a reference because it can change concurrently // get a reference because it can change concurrently
final HostAndPort master = currentHostMaster; final HostAndPort master = currentHostMaster;
final HostAndPort connection = new HostAndPort(jedis.getClient() final HostAndPort connection = new HostAndPort(jedis.getClient()
.getHost(), jedis.getClient().getPort()); .getHost(), jedis.getClient().getPort());
if (master.equals(connection)) { if (master.equals(connection)) {
// connected to the correct master // connected to the correct master
return jedis; return jedis;
} else { } else {
returnBrokenResource(jedis); returnBrokenResource(jedis);
} }
} }
} }
public void returnBrokenResource(final Jedis resource) { public void returnBrokenResource(final Jedis resource) {
if (resource != null) { if (resource != null) {
returnBrokenResourceObject(resource); returnBrokenResourceObject(resource);
} }
} }
public void returnResource(final Jedis resource) { public void returnResource(final Jedis resource) {
if (resource != null) { if (resource != null) {
resource.resetState(); resource.resetState();
returnResourceObject(resource); returnResourceObject(resource);
} }
} }
protected class MasterListener extends Thread { protected class MasterListener extends Thread {
protected String masterName; protected String masterName;
protected String host; protected String host;
protected int port; protected int port;
protected long subscribeRetryWaitTimeMillis = 5000; protected long subscribeRetryWaitTimeMillis = 5000;
protected Jedis j; protected Jedis j;
protected AtomicBoolean running = new AtomicBoolean(false); protected AtomicBoolean running = new AtomicBoolean(false);
protected MasterListener() { protected MasterListener() {
} }
public MasterListener(String masterName, String host, int port) { public MasterListener(String masterName, String host, int port) {
this.masterName = masterName; this.masterName = masterName;
this.host = host; this.host = host;
this.port = port; this.port = port;
} }
public MasterListener(String masterName, String host, int port, public MasterListener(String masterName, String host, int port,
long subscribeRetryWaitTimeMillis) { long subscribeRetryWaitTimeMillis) {
this(masterName, host, port); this(masterName, host, port);
this.subscribeRetryWaitTimeMillis = subscribeRetryWaitTimeMillis; this.subscribeRetryWaitTimeMillis = subscribeRetryWaitTimeMillis;
} }
public void run() { public void run() {
running.set(true); running.set(true);
while (running.get()) { while (running.get()) {
j = new Jedis(host, port); j = new Jedis(host, port);
try { try {
j.subscribe(new JedisPubSub() { j.subscribe(new JedisPubSub() {
@Override @Override
public void onMessage(String channel, String message) { public void onMessage(String channel, String message) {
log.fine("Sentinel " + host + ":" + port log.fine("Sentinel " + host + ":" + port
+ " published: " + message + "."); + " published: " + message + ".");
String[] switchMasterMsg = message.split(" "); String[] switchMasterMsg = message.split(" ");
if (switchMasterMsg.length > 3) { if (switchMasterMsg.length > 3) {
if (masterName.equals(switchMasterMsg[0])) { if (masterName.equals(switchMasterMsg[0])) {
initPool(toHostAndPort(Arrays.asList( initPool(toHostAndPort(Arrays.asList(
switchMasterMsg[3], switchMasterMsg[3],
switchMasterMsg[4]))); switchMasterMsg[4])));
} else { } else {
log.fine("Ignoring message on +switch-master for master name " log.fine("Ignoring message on +switch-master for master name "
+ switchMasterMsg[0] + switchMasterMsg[0]
+ ", our master name is " + ", our master name is "
+ masterName); + masterName);
} }
} else { } else {
log.severe("Invalid message received on Sentinel " log.severe("Invalid message received on Sentinel "
+ host + host
+ ":" + ":"
+ port + port
+ " on channel +switch-master: " + " on channel +switch-master: "
+ message); + message);
} }
} }
}, "+switch-master"); }, "+switch-master");
} catch (JedisConnectionException e) { } catch (JedisConnectionException e) {
if (running.get()) { if (running.get()) {
log.severe("Lost connection to Sentinel at " + host log.severe("Lost connection to Sentinel at " + host
+ ":" + port + ":" + port
+ ". Sleeping 5000ms and retrying."); + ". Sleeping 5000ms and retrying.");
try { try {
Thread.sleep(subscribeRetryWaitTimeMillis); Thread.sleep(subscribeRetryWaitTimeMillis);
} catch (InterruptedException e1) { } catch (InterruptedException e1) {
e1.printStackTrace(); e1.printStackTrace();
} }
} else { } else {
log.fine("Unsubscribing from Sentinel at " + host + ":" log.fine("Unsubscribing from Sentinel at " + host + ":"
+ port); + port);
} }
} }
} }
} }
public void shutdown() { public void shutdown() {
try { try {
log.fine("Shutting down listener on " + host + ":" + port); log.fine("Shutting down listener on " + host + ":" + port);
running.set(false); running.set(false);
// This isn't good, the Jedis object is not thread safe // This isn't good, the Jedis object is not thread safe
j.disconnect(); j.disconnect();
} catch (Exception e) { } catch (Exception e) {
log.severe("Caught exception while shutting down: " log.severe("Caught exception while shutting down: "
+ e.getMessage()); + e.getMessage());
} }
} }
} }
} }

View File

@@ -7,7 +7,7 @@ import redis.clients.util.Sharded;
public class JedisShardInfo extends ShardInfo<Jedis> { public class JedisShardInfo extends ShardInfo<Jedis> {
public String toString() { public String toString() {
return host + ":" + port + "*" + getWeight(); return host + ":" + port + "*" + getWeight();
} }
private int timeout; private int timeout;
@@ -17,83 +17,83 @@ public class JedisShardInfo extends ShardInfo<Jedis> {
private String name = null; private String name = null;
public String getHost() { public String getHost() {
return host; return host;
} }
public int getPort() { public int getPort() {
return port; return port;
} }
public JedisShardInfo(String host) { public JedisShardInfo(String host) {
super(Sharded.DEFAULT_WEIGHT); super(Sharded.DEFAULT_WEIGHT);
URI uri = URI.create(host); URI uri = URI.create(host);
if (uri.getScheme() != null && uri.getScheme().equals("redis")) { if (uri.getScheme() != null && uri.getScheme().equals("redis")) {
this.host = uri.getHost(); this.host = uri.getHost();
this.port = uri.getPort(); this.port = uri.getPort();
this.password = uri.getUserInfo().split(":", 2)[1]; this.password = uri.getUserInfo().split(":", 2)[1];
} else { } else {
this.host = host; this.host = host;
this.port = Protocol.DEFAULT_PORT; this.port = Protocol.DEFAULT_PORT;
} }
} }
public JedisShardInfo(String host, String name) { public JedisShardInfo(String host, String name) {
this(host, Protocol.DEFAULT_PORT, name); this(host, Protocol.DEFAULT_PORT, name);
} }
public JedisShardInfo(String host, int port) { public JedisShardInfo(String host, int port) {
this(host, port, 2000); this(host, port, 2000);
} }
public JedisShardInfo(String host, int port, String name) { public JedisShardInfo(String host, int port, String name) {
this(host, port, 2000, name); this(host, port, 2000, name);
} }
public JedisShardInfo(String host, int port, int timeout) { public JedisShardInfo(String host, int port, int timeout) {
this(host, port, timeout, Sharded.DEFAULT_WEIGHT); this(host, port, timeout, Sharded.DEFAULT_WEIGHT);
} }
public JedisShardInfo(String host, int port, int timeout, String name) { public JedisShardInfo(String host, int port, int timeout, String name) {
this(host, port, timeout, Sharded.DEFAULT_WEIGHT); this(host, port, timeout, Sharded.DEFAULT_WEIGHT);
this.name = name; this.name = name;
} }
public JedisShardInfo(String host, int port, int timeout, int weight) { public JedisShardInfo(String host, int port, int timeout, int weight) {
super(weight); super(weight);
this.host = host; this.host = host;
this.port = port; this.port = port;
this.timeout = timeout; this.timeout = timeout;
} }
public JedisShardInfo(URI uri) { public JedisShardInfo(URI uri) {
super(Sharded.DEFAULT_WEIGHT); super(Sharded.DEFAULT_WEIGHT);
this.host = uri.getHost(); this.host = uri.getHost();
this.port = uri.getPort(); this.port = uri.getPort();
this.password = uri.getUserInfo().split(":", 2)[1]; this.password = uri.getUserInfo().split(":", 2)[1];
} }
public String getPassword() { public String getPassword() {
return password; return password;
} }
public void setPassword(String auth) { public void setPassword(String auth) {
this.password = auth; this.password = auth;
} }
public int getTimeout() { public int getTimeout() {
return timeout; return timeout;
} }
public void setTimeout(int timeout) { public void setTimeout(int timeout) {
this.timeout = timeout; this.timeout = timeout;
} }
public String getName() { public String getName() {
return name; return name;
} }
@Override @Override
public Jedis createResource() { public Jedis createResource() {
return new Jedis(this); return new Jedis(this);
} }
} }

View File

@@ -10,63 +10,63 @@ import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisConnectionException;
public class JedisSlotBasedConnectionHandler extends public class JedisSlotBasedConnectionHandler extends
JedisClusterConnectionHandler { JedisClusterConnectionHandler {
public JedisSlotBasedConnectionHandler(Set<HostAndPort> nodes, public JedisSlotBasedConnectionHandler(Set<HostAndPort> nodes,
final GenericObjectPoolConfig poolConfig) { final GenericObjectPoolConfig poolConfig) {
super(nodes, poolConfig); super(nodes, poolConfig);
} }
public Jedis getConnection() { public Jedis getConnection() {
// In antirez's redis-rb-cluster implementation, // In antirez's redis-rb-cluster implementation,
// getRandomConnection always return valid connection (able to // getRandomConnection always return valid connection (able to
// ping-pong) // ping-pong)
// or exception if all connections are invalid // or exception if all connections are invalid
List<JedisPool> pools = getShuffledNodesPool(); List<JedisPool> pools = getShuffledNodesPool();
for (JedisPool pool : pools) { for (JedisPool pool : pools) {
Jedis jedis = null; Jedis jedis = null;
try { try {
jedis = pool.getResource(); jedis = pool.getResource();
if (jedis == null) { if (jedis == null) {
continue; continue;
} }
String result = jedis.ping(); String result = jedis.ping();
if (result.equalsIgnoreCase("pong")) if (result.equalsIgnoreCase("pong"))
return jedis; return jedis;
pool.returnBrokenResource(jedis); pool.returnBrokenResource(jedis);
} catch (JedisConnectionException ex) { } catch (JedisConnectionException ex) {
if (jedis != null) { if (jedis != null) {
pool.returnBrokenResource(jedis); pool.returnBrokenResource(jedis);
} }
} }
} }
throw new JedisConnectionException("no reachable node in cluster"); throw new JedisConnectionException("no reachable node in cluster");
} }
@Override @Override
public Jedis getConnectionFromSlot(int slot) { public Jedis getConnectionFromSlot(int slot) {
JedisPool connectionPool = cache.getSlotPool(slot); JedisPool connectionPool = cache.getSlotPool(slot);
if (connectionPool != null) { if (connectionPool != null) {
// It can't guaranteed to get valid connection because of node // It can't guaranteed to get valid connection because of node
// assignment // assignment
return connectionPool.getResource(); return connectionPool.getResource();
} else { } else {
return getConnection(); return getConnection();
} }
} }
private List<JedisPool> getShuffledNodesPool() { private List<JedisPool> getShuffledNodesPool() {
List<JedisPool> pools = new ArrayList<JedisPool>(); List<JedisPool> pools = new ArrayList<JedisPool>();
pools.addAll(cache.getNodes().values()); pools.addAll(cache.getNodes().values());
Collections.shuffle(pools); Collections.shuffle(pools);
return pools; return pools;
} }
} }

View File

@@ -40,7 +40,7 @@ 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, Response<Long> sort(byte[] key, SortingParams sortingParameters,
byte[] dstkey); byte[] dstkey);
Response<Long> sort(byte[] key, byte[] dstkey); Response<Long> sort(byte[] key, byte[] dstkey);

View File

@@ -39,7 +39,7 @@ 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, Response<Long> sort(String key, SortingParams sortingParameters,
String dstkey); String dstkey);
Response<Long> sort(String key, String dstkey); Response<Long> sort(String key, String dstkey);

View File

@@ -5,474 +5,474 @@ 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, MultiKeyBinaryRedisPipeline, BasicRedisPipeline, MultiKeyBinaryRedisPipeline,
MultiKeyCommandsPipeline, ClusterPipeline { MultiKeyCommandsPipeline, ClusterPipeline {
protected Client client = null; protected Client client = null;
public Response<List<String>> brpop(String... args) { public Response<List<String>> brpop(String... args) {
client.brpop(args); client.brpop(args);
return getResponse(BuilderFactory.STRING_LIST); return getResponse(BuilderFactory.STRING_LIST);
} }
public Response<List<String>> brpop(int timeout, String... keys) { public Response<List<String>> brpop(int timeout, String... keys) {
client.brpop(timeout, keys); client.brpop(timeout, keys);
return getResponse(BuilderFactory.STRING_LIST); return getResponse(BuilderFactory.STRING_LIST);
} }
public Response<List<String>> blpop(String... args) { public Response<List<String>> blpop(String... args) {
client.blpop(args); client.blpop(args);
return getResponse(BuilderFactory.STRING_LIST); return getResponse(BuilderFactory.STRING_LIST);
} }
public Response<List<String>> blpop(int timeout, String... keys) { public Response<List<String>> blpop(int timeout, String... keys) {
client.blpop(timeout, keys); client.blpop(timeout, keys);
return getResponse(BuilderFactory.STRING_LIST); return getResponse(BuilderFactory.STRING_LIST);
} }
public Response<Map<String, String>> blpopMap(int timeout, String... keys) { public Response<Map<String, String>> blpopMap(int timeout, String... keys) {
client.blpop(timeout, keys); client.blpop(timeout, keys);
return getResponse(BuilderFactory.STRING_MAP); return getResponse(BuilderFactory.STRING_MAP);
} }
public Response<List<byte[]>> brpop(byte[]... args) { public Response<List<byte[]>> brpop(byte[]... args) {
client.brpop(args); client.brpop(args);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST); return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
} }
public Response<List<String>> brpop(int timeout, byte[]... keys) { public Response<List<String>> brpop(int timeout, byte[]... keys) {
client.brpop(timeout, keys); client.brpop(timeout, keys);
return getResponse(BuilderFactory.STRING_LIST); return getResponse(BuilderFactory.STRING_LIST);
} }
public Response<Map<String, String>> brpopMap(int timeout, String... keys) { public Response<Map<String, String>> brpopMap(int timeout, String... keys) {
client.blpop(timeout, keys); client.blpop(timeout, keys);
return getResponse(BuilderFactory.STRING_MAP); return getResponse(BuilderFactory.STRING_MAP);
} }
public Response<List<byte[]>> blpop(byte[]... args) { public Response<List<byte[]>> blpop(byte[]... args) {
client.blpop(args); client.blpop(args);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST); return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
} }
public Response<List<String>> blpop(int timeout, byte[]... keys) { public Response<List<String>> blpop(int timeout, byte[]... keys) {
client.blpop(timeout, keys); client.blpop(timeout, keys);
return getResponse(BuilderFactory.STRING_LIST); return getResponse(BuilderFactory.STRING_LIST);
} }
public Response<Long> del(String... keys) { public Response<Long> del(String... keys) {
client.del(keys); client.del(keys);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Long> del(byte[]... keys) { public Response<Long> del(byte[]... keys) {
client.del(keys); client.del(keys);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Set<String>> keys(String pattern) { public Response<Set<String>> keys(String pattern) {
getClient(pattern).keys(pattern); getClient(pattern).keys(pattern);
return getResponse(BuilderFactory.STRING_SET); return getResponse(BuilderFactory.STRING_SET);
} }
public Response<Set<byte[]>> keys(byte[] pattern) { public Response<Set<byte[]>> keys(byte[] pattern) {
getClient(pattern).keys(pattern); getClient(pattern).keys(pattern);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
} }
public Response<List<String>> mget(String... keys) { public Response<List<String>> mget(String... keys) {
client.mget(keys); client.mget(keys);
return getResponse(BuilderFactory.STRING_LIST); return getResponse(BuilderFactory.STRING_LIST);
} }
public Response<List<byte[]>> mget(byte[]... keys) { public Response<List<byte[]>> mget(byte[]... keys) {
client.mget(keys); client.mget(keys);
return getResponse(BuilderFactory.BYTE_ARRAY_LIST); return getResponse(BuilderFactory.BYTE_ARRAY_LIST);
} }
public Response<String> mset(String... keysvalues) { public Response<String> mset(String... keysvalues) {
client.mset(keysvalues); client.mset(keysvalues);
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<String> mset(byte[]... keysvalues) { public Response<String> mset(byte[]... keysvalues) {
client.mset(keysvalues); client.mset(keysvalues);
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<Long> msetnx(String... keysvalues) { public Response<Long> msetnx(String... keysvalues) {
client.msetnx(keysvalues); client.msetnx(keysvalues);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Long> msetnx(byte[]... keysvalues) { public Response<Long> msetnx(byte[]... keysvalues) {
client.msetnx(keysvalues); client.msetnx(keysvalues);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<String> rename(String oldkey, String newkey) { public Response<String> rename(String oldkey, String newkey) {
client.rename(oldkey, newkey); client.rename(oldkey, newkey);
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<String> rename(byte[] oldkey, byte[] newkey) { public Response<String> rename(byte[] oldkey, byte[] newkey) {
client.rename(oldkey, newkey); client.rename(oldkey, newkey);
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<Long> renamenx(String oldkey, String newkey) { public Response<Long> renamenx(String oldkey, String newkey) {
client.renamenx(oldkey, newkey); client.renamenx(oldkey, newkey);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Long> renamenx(byte[] oldkey, byte[] newkey) { public Response<Long> renamenx(byte[] oldkey, byte[] newkey) {
client.renamenx(oldkey, newkey); client.renamenx(oldkey, newkey);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<String> rpoplpush(String srckey, String dstkey) { public Response<String> rpoplpush(String srckey, String dstkey) {
client.rpoplpush(srckey, dstkey); client.rpoplpush(srckey, dstkey);
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<byte[]> rpoplpush(byte[] srckey, byte[] dstkey) { public Response<byte[]> rpoplpush(byte[] srckey, byte[] dstkey) {
client.rpoplpush(srckey, dstkey); client.rpoplpush(srckey, dstkey);
return getResponse(BuilderFactory.BYTE_ARRAY); return getResponse(BuilderFactory.BYTE_ARRAY);
} }
public Response<Set<String>> sdiff(String... keys) { public Response<Set<String>> sdiff(String... keys) {
client.sdiff(keys); client.sdiff(keys);
return getResponse(BuilderFactory.STRING_SET); return getResponse(BuilderFactory.STRING_SET);
} }
public Response<Set<byte[]>> sdiff(byte[]... keys) { public Response<Set<byte[]>> sdiff(byte[]... keys) {
client.sdiff(keys); client.sdiff(keys);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
} }
public Response<Long> sdiffstore(String dstkey, String... keys) { public Response<Long> sdiffstore(String dstkey, String... keys) {
client.sdiffstore(dstkey, keys); client.sdiffstore(dstkey, keys);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Long> sdiffstore(byte[] dstkey, byte[]... keys) { public Response<Long> sdiffstore(byte[] dstkey, byte[]... keys) {
client.sdiffstore(dstkey, keys); client.sdiffstore(dstkey, keys);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Set<String>> sinter(String... keys) { public Response<Set<String>> sinter(String... keys) {
client.sinter(keys); client.sinter(keys);
return getResponse(BuilderFactory.STRING_SET); return getResponse(BuilderFactory.STRING_SET);
} }
public Response<Set<byte[]>> sinter(byte[]... keys) { public Response<Set<byte[]>> sinter(byte[]... keys) {
client.sinter(keys); client.sinter(keys);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
} }
public Response<Long> sinterstore(String dstkey, String... keys) { public Response<Long> sinterstore(String dstkey, String... keys) {
client.sinterstore(dstkey, keys); client.sinterstore(dstkey, keys);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Long> sinterstore(byte[] dstkey, byte[]... keys) { public Response<Long> sinterstore(byte[] dstkey, byte[]... keys) {
client.sinterstore(dstkey, keys); client.sinterstore(dstkey, keys);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Long> smove(String srckey, String dstkey, String member) { public Response<Long> smove(String srckey, String dstkey, String member) {
client.smove(srckey, dstkey, member); client.smove(srckey, dstkey, member);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Long> smove(byte[] srckey, byte[] dstkey, byte[] member) { public Response<Long> smove(byte[] srckey, byte[] dstkey, byte[] member) {
client.smove(srckey, dstkey, member); client.smove(srckey, dstkey, member);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Long> sort(String key, SortingParams sortingParameters, public Response<Long> sort(String key, 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, SortingParams sortingParameters, public Response<Long> sort(byte[] key, SortingParams sortingParameters,
byte[] dstkey) { byte[] dstkey) {
client.sort(key, sortingParameters, dstkey); client.sort(key, sortingParameters, dstkey);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Long> sort(String key, String dstkey) { public Response<Long> sort(String key, String dstkey) {
client.sort(key, dstkey); client.sort(key, dstkey);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Long> sort(byte[] key, byte[] dstkey) { public Response<Long> sort(byte[] key, byte[] dstkey) {
client.sort(key, dstkey); client.sort(key, dstkey);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Set<String>> sunion(String... keys) { public Response<Set<String>> sunion(String... keys) {
client.sunion(keys); client.sunion(keys);
return getResponse(BuilderFactory.STRING_SET); return getResponse(BuilderFactory.STRING_SET);
} }
public Response<Set<byte[]>> sunion(byte[]... keys) { public Response<Set<byte[]>> sunion(byte[]... keys) {
client.sunion(keys); client.sunion(keys);
return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); return getResponse(BuilderFactory.BYTE_ARRAY_ZSET);
} }
public Response<Long> sunionstore(String dstkey, String... keys) { public Response<Long> sunionstore(String dstkey, String... keys) {
client.sunionstore(dstkey, keys); client.sunionstore(dstkey, keys);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Long> sunionstore(byte[] dstkey, byte[]... keys) { public Response<Long> sunionstore(byte[] dstkey, byte[]... keys) {
client.sunionstore(dstkey, keys); client.sunionstore(dstkey, keys);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<String> watch(String... keys) { public Response<String> watch(String... keys) {
client.watch(keys); client.watch(keys);
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<String> watch(byte[]... keys) { public Response<String> watch(byte[]... keys) {
client.watch(keys); client.watch(keys);
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<Long> zinterstore(String dstkey, String... sets) { public Response<Long> zinterstore(String dstkey, String... sets) {
client.zinterstore(dstkey, sets); client.zinterstore(dstkey, sets);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Long> zinterstore(byte[] dstkey, byte[]... sets) { public Response<Long> zinterstore(byte[] dstkey, byte[]... sets) {
client.zinterstore(dstkey, sets); client.zinterstore(dstkey, sets);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Long> zinterstore(String dstkey, ZParams params, public Response<Long> zinterstore(String dstkey, ZParams params,
String... sets) { String... sets) {
client.zinterstore(dstkey, params, sets); client.zinterstore(dstkey, params, sets);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Long> zinterstore(byte[] dstkey, ZParams params, public Response<Long> zinterstore(byte[] dstkey, ZParams params,
byte[]... sets) { byte[]... sets) {
client.zinterstore(dstkey, params, sets); client.zinterstore(dstkey, params, sets);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Long> zunionstore(String dstkey, String... sets) { public Response<Long> zunionstore(String dstkey, String... sets) {
client.zunionstore(dstkey, sets); client.zunionstore(dstkey, sets);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Long> zunionstore(byte[] dstkey, byte[]... sets) { public Response<Long> zunionstore(byte[] dstkey, byte[]... sets) {
client.zunionstore(dstkey, sets); client.zunionstore(dstkey, sets);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Long> zunionstore(String dstkey, ZParams params, public Response<Long> zunionstore(String dstkey, ZParams params,
String... sets) { String... sets) {
client.zunionstore(dstkey, params, sets); client.zunionstore(dstkey, params, sets);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Long> zunionstore(byte[] dstkey, ZParams params, public Response<Long> zunionstore(byte[] dstkey, ZParams params,
byte[]... sets) { byte[]... sets) {
client.zunionstore(dstkey, params, sets); client.zunionstore(dstkey, params, sets);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<String> bgrewriteaof() { public Response<String> bgrewriteaof() {
client.bgrewriteaof(); client.bgrewriteaof();
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<String> bgsave() { public Response<String> bgsave() {
client.bgsave(); client.bgsave();
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<String> configGet(String pattern) { public Response<String> configGet(String pattern) {
client.configGet(pattern); client.configGet(pattern);
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<String> configSet(String parameter, String value) { public Response<String> configSet(String parameter, String value) {
client.configSet(parameter, value); client.configSet(parameter, value);
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<String> brpoplpush(String source, String destination, public Response<String> brpoplpush(String source, String destination,
int timeout) { int timeout) {
client.brpoplpush(source, destination, timeout); client.brpoplpush(source, destination, timeout);
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<byte[]> brpoplpush(byte[] source, byte[] destination, public Response<byte[]> brpoplpush(byte[] source, byte[] destination,
int timeout) { int timeout) {
client.brpoplpush(source, destination, timeout); client.brpoplpush(source, destination, timeout);
return getResponse(BuilderFactory.BYTE_ARRAY); return getResponse(BuilderFactory.BYTE_ARRAY);
} }
public Response<String> configResetStat() { public Response<String> configResetStat() {
client.configResetStat(); client.configResetStat();
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<String> save() { public Response<String> save() {
client.save(); client.save();
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<Long> lastsave() { public Response<Long> lastsave() {
client.lastsave(); client.lastsave();
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Long> publish(String channel, String message) { public Response<Long> publish(String channel, String message) {
client.publish(channel, message); client.publish(channel, message);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Long> publish(byte[] channel, byte[] message) { public Response<Long> publish(byte[] channel, byte[] message) {
client.publish(channel, message); client.publish(channel, message);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<String> randomKey() { public Response<String> randomKey() {
client.randomKey(); client.randomKey();
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<byte[]> randomKeyBinary() { public Response<byte[]> randomKeyBinary() {
client.randomKey(); client.randomKey();
return getResponse(BuilderFactory.BYTE_ARRAY); return getResponse(BuilderFactory.BYTE_ARRAY);
} }
public Response<String> flushDB() { public Response<String> flushDB() {
client.flushDB(); client.flushDB();
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<String> flushAll() { public Response<String> flushAll() {
client.flushAll(); client.flushAll();
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<String> info() { public Response<String> info() {
client.info(); client.info();
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<List<String>> time() { public Response<List<String>> time() {
client.time(); client.time();
return getResponse(BuilderFactory.STRING_LIST); return getResponse(BuilderFactory.STRING_LIST);
} }
public Response<Long> dbSize() { public Response<Long> dbSize() {
client.dbSize(); client.dbSize();
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<String> shutdown() { public Response<String> shutdown() {
client.shutdown(); client.shutdown();
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<String> ping() { public Response<String> ping() {
client.ping(); client.ping();
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<String> select(int index) { public Response<String> select(int index) {
client.select(index); client.select(index);
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<Long> bitop(BitOP op, byte[] destKey, byte[]... srcKeys) { public Response<Long> bitop(BitOP op, byte[] destKey, byte[]... srcKeys) {
client.bitop(op, destKey, srcKeys); client.bitop(op, destKey, srcKeys);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<Long> bitop(BitOP op, String destKey, String... srcKeys) { public Response<Long> bitop(BitOP op, String destKey, String... srcKeys) {
client.bitop(op, destKey, srcKeys); client.bitop(op, destKey, srcKeys);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
public Response<String> clusterNodes() { public Response<String> clusterNodes() {
client.clusterNodes(); client.clusterNodes();
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<String> clusterMeet(final String ip, final int port) { public Response<String> clusterMeet(final String ip, final int port) {
client.clusterMeet(ip, port); client.clusterMeet(ip, port);
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<String> clusterAddSlots(final int... slots) { public Response<String> clusterAddSlots(final int... slots) {
client.clusterAddSlots(slots); client.clusterAddSlots(slots);
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<String> clusterDelSlots(final int... slots) { public Response<String> clusterDelSlots(final int... slots) {
client.clusterDelSlots(slots); client.clusterDelSlots(slots);
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<String> clusterInfo() { public Response<String> clusterInfo() {
client.clusterInfo(); client.clusterInfo();
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<List<String>> clusterGetKeysInSlot(final int slot, public Response<List<String>> clusterGetKeysInSlot(final int slot,
final int count) { 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, public Response<String> clusterSetSlotNode(final int slot,
final String nodeId) { 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, public Response<String> clusterSetSlotMigrating(final int slot,
final String nodeId) { 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, public Response<String> clusterSetSlotImporting(final int slot,
final String nodeId) { final String nodeId) {
client.clusterSetSlotImporting(slot, nodeId); client.clusterSetSlotImporting(slot, nodeId);
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
@Override @Override
public Response<String> pfmerge(byte[] destkey, byte[]... sourcekeys) { public Response<String> pfmerge(byte[] destkey, byte[]... sourcekeys) {
client.pfmerge(destkey, sourcekeys); client.pfmerge(destkey, sourcekeys);
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
@Override @Override
public Response<String> pfmerge(String destkey, String... sourcekeys) { public Response<String> pfmerge(String destkey, String... sourcekeys) {
client.pfmerge(destkey, sourcekeys); client.pfmerge(destkey, sourcekeys);
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
@Override @Override
public Response<Long> pfcount(String... keys) { public Response<Long> pfcount(String... keys) {
client.pfcount(keys); client.pfcount(keys);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
@Override @Override
public Response<Long> pfcount(final byte[]... keys) { public Response<Long> pfcount(final byte[]... keys) {
client.pfcount(keys); client.pfcount(keys);
return getResponse(BuilderFactory.LONG); return getResponse(BuilderFactory.LONG);
} }
} }

View File

@@ -10,81 +10,81 @@ public class Pipeline extends MultiKeyPipelineBase {
private MultiResponseBuilder currentMulti; private MultiResponseBuilder currentMulti;
private class MultiResponseBuilder extends Builder<List<Object>> { private class MultiResponseBuilder extends Builder<List<Object>> {
private List<Response<?>> responses = new ArrayList<Response<?>>(); private List<Response<?>> responses = new ArrayList<Response<?>>();
@Override @Override
public List<Object> build(Object data) { public List<Object> build(Object data) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
List<Object> list = (List<Object>) data; List<Object> list = (List<Object>) data;
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 " throw new JedisDataException("Expected data size "
+ responses.size() + " but was " + list.size()); + responses.size() + " but was " + list.size());
} }
for (int i = 0; i < list.size(); i++) { for (int i = 0; i < list.size(); i++) {
Response<?> response = responses.get(i); Response<?> response = responses.get(i);
response.set(list.get(i)); response.set(list.get(i));
Object builtResponse; Object builtResponse;
try { try {
builtResponse = response.get(); builtResponse = response.get();
} catch (JedisDataException e) { } catch (JedisDataException e) {
builtResponse = e; builtResponse = e;
} }
values.add(builtResponse); values.add(builtResponse);
} }
return values; return values;
} }
public void setResponseDependency(Response<?> dependency) { public void setResponseDependency(Response<?> dependency) {
for (Response<?> response : responses) { for (Response<?> response : responses) {
response.setDependency(dependency); response.setDependency(dependency);
} }
} }
public void addResponse(Response<?> response) { public void addResponse(Response<?> response) {
responses.add(response); responses.add(response);
} }
} }
@Override @Override
protected <T> Response<T> getResponse(Builder<T> builder) { protected <T> Response<T> getResponse(Builder<T> builder) {
if (currentMulti != null) { if (currentMulti != null) {
super.getResponse(BuilderFactory.STRING); // Expected QUEUED super.getResponse(BuilderFactory.STRING); // Expected QUEUED
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);
} }
} }
public void setClient(Client client) { public void setClient(Client client) {
this.client = client; this.client = client;
} }
@Override @Override
protected Client getClient(byte[] key) { protected Client getClient(byte[] key) {
return client; return client;
} }
@Override @Override
protected Client getClient(String key) { protected Client getClient(String key) {
return client; return client;
} }
public void clear() { public void clear() {
if (isInMulti()) { if (isInMulti()) {
discard(); discard();
} }
sync(); sync();
} }
public boolean isInMulti() { public boolean isInMulti() {
return currentMulti != null; return currentMulti != null;
} }
/** /**
@@ -93,12 +93,12 @@ public class Pipeline extends MultiKeyPipelineBase {
* the different Response<?> of the commands you execute. * the different Response<?> of the commands you execute.
*/ */
public void sync() { public void sync() {
if (getPipelinedResponseLength() > 0) { if (getPipelinedResponseLength() > 0) {
List<Object> unformatted = client.getMany(getPipelinedResponseLength()); List<Object> unformatted = client.getMany(getPipelinedResponseLength());
for (Object o : unformatted) { for (Object o : unformatted) {
generateResponse(o); generateResponse(o);
} }
} }
} }
/** /**
* Synchronize pipeline by reading all responses. This operation close the * Synchronize pipeline by reading all responses. This operation close the
@@ -126,33 +126,33 @@ public class Pipeline extends MultiKeyPipelineBase {
} }
public Response<String> discard() { public Response<String> discard() {
if (currentMulti == null) if (currentMulti == null)
throw new JedisDataException("DISCARD without MULTI"); throw new JedisDataException("DISCARD without MULTI");
client.discard(); client.discard();
currentMulti = null; currentMulti = null;
return getResponse(BuilderFactory.STRING); return getResponse(BuilderFactory.STRING);
} }
public Response<List<Object>> exec() { public Response<List<Object>> exec() {
if (currentMulti == null) if (currentMulti == null)
throw new JedisDataException("EXEC without MULTI"); throw new JedisDataException("EXEC without MULTI");
client.exec(); client.exec();
Response<List<Object>> response = super.getResponse(currentMulti); Response<List<Object>> response = super.getResponse(currentMulti);
currentMulti.setResponseDependency(response); currentMulti.setResponseDependency(response);
currentMulti = null; currentMulti = null;
return response; return response;
} }
public Response<String> multi() { public Response<String> multi() {
if (currentMulti != null) if (currentMulti != null)
throw new JedisDataException("MULTI calls can not be nested"); throw new JedisDataException("MULTI calls can not be nested");
client.multi(); client.multi();
Response<String> response = getResponse(BuilderFactory.STRING); // Expecting Response<String> response = getResponse(BuilderFactory.STRING); // Expecting
// OK // OK
currentMulti = new MultiResponseBuilder(); currentMulti = new MultiResponseBuilder();
return response; return response;
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -67,168 +67,168 @@ public final class Protocol {
public static final String PUBSUB_NUM_PAT = "numpat"; public static final String PUBSUB_NUM_PAT = "numpat";
private Protocol() { private Protocol() {
// this prevent the class from instantiation // this prevent the class from instantiation
} }
public static void sendCommand(final RedisOutputStream os, public static void sendCommand(final RedisOutputStream os,
final Command command, final byte[]... args) { final Command command, final byte[]... args) {
sendCommand(os, command.raw, args); sendCommand(os, command.raw, args);
} }
private static void sendCommand(final RedisOutputStream os, private static void sendCommand(final RedisOutputStream os,
final byte[] command, final byte[]... args) { final byte[] command, final byte[]... args) {
try { try {
os.write(ASTERISK_BYTE); os.write(ASTERISK_BYTE);
os.writeIntCrLf(args.length + 1); os.writeIntCrLf(args.length + 1);
os.write(DOLLAR_BYTE); os.write(DOLLAR_BYTE);
os.writeIntCrLf(command.length); os.writeIntCrLf(command.length);
os.write(command); os.write(command);
os.writeCrLf(); os.writeCrLf();
for (final byte[] arg : args) { for (final byte[] arg : args) {
os.write(DOLLAR_BYTE); os.write(DOLLAR_BYTE);
os.writeIntCrLf(arg.length); os.writeIntCrLf(arg.length);
os.write(arg); os.write(arg);
os.writeCrLf(); os.writeCrLf();
} }
} catch (IOException e) { } catch (IOException e) {
throw new JedisConnectionException(e); throw new JedisConnectionException(e);
} }
} }
private static void processError(final RedisInputStream is) { private static void processError(final RedisInputStream is) {
String message = is.readLine(); String message = is.readLine();
// TODO: I'm not sure if this is the best way to do this. // TODO: I'm not sure if this is the best way to do this.
// 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( throw new JedisMovedDataException(message, new HostAndPort(
movedInfo[1], Integer.valueOf(movedInfo[2])), movedInfo[1], Integer.valueOf(movedInfo[2])),
Integer.valueOf(movedInfo[0])); 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( throw new JedisAskDataException(message, new HostAndPort(
askInfo[1], Integer.valueOf(askInfo[2])), askInfo[1], Integer.valueOf(askInfo[2])),
Integer.valueOf(askInfo[0])); Integer.valueOf(askInfo[0]));
} else if (message.startsWith(CLUSTERDOWN_RESPONSE)) { } else if (message.startsWith(CLUSTERDOWN_RESPONSE)) {
throw new JedisClusterException(message); throw new JedisClusterException(message);
} }
throw new JedisDataException(message); throw new JedisDataException(message);
} }
private static String[] parseTargetHostAndSlot( private static String[] parseTargetHostAndSlot(
String clusterRedirectResponse) { 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(":");
response[0] = messageInfo[1]; response[0] = messageInfo[1];
response[1] = targetHostAndPort[0]; response[1] = targetHostAndPort[0];
response[2] = targetHostAndPort[1]; response[2] = targetHostAndPort[1];
return response; return response;
} }
private static Object process(final RedisInputStream is) { private static Object process(final RedisInputStream is) {
final byte b = is.readByte(); final byte b = is.readByte();
if (b == PLUS_BYTE) { if (b == PLUS_BYTE) {
return processStatusCodeReply(is); return processStatusCodeReply(is);
} else if (b == DOLLAR_BYTE) { } else if (b == DOLLAR_BYTE) {
return processBulkReply(is); return processBulkReply(is);
} else if (b == ASTERISK_BYTE) { } else if (b == ASTERISK_BYTE) {
return processMultiBulkReply(is); return processMultiBulkReply(is);
} else if (b == COLON_BYTE) { } else if (b == COLON_BYTE) {
return processInteger(is); return processInteger(is);
} else if (b == MINUS_BYTE) { } else if (b == MINUS_BYTE) {
processError(is); processError(is);
return null; return null;
} else { } else {
throw new JedisConnectionException("Unknown reply: " + (char) b); throw new JedisConnectionException("Unknown reply: " + (char) b);
} }
} }
private static byte[] processStatusCodeReply(final RedisInputStream is) { private static byte[] processStatusCodeReply(final RedisInputStream is) {
return is.readLineBytes(); return is.readLineBytes();
} }
private static byte[] processBulkReply(final RedisInputStream is) { private static byte[] processBulkReply(final RedisInputStream is) {
final int len = is.readIntCrLf(); final int len = is.readIntCrLf();
if (len == -1) { if (len == -1) {
return null; return null;
} }
final byte[] read = new byte[len]; final byte[] read = new byte[len];
int offset = 0; int offset = 0;
while (offset < len) { while (offset < len) {
final int size = is.read(read, offset, (len - offset)); final int size = is.read(read, offset, (len - offset));
if (size == -1) if (size == -1)
throw new JedisConnectionException( throw new JedisConnectionException(
"It seems like server has closed the connection."); "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
is.readByte(); is.readByte();
is.readByte(); is.readByte();
return read; return read;
} }
private static Long processInteger(final RedisInputStream is) { private static Long processInteger(final RedisInputStream is) {
return is.readLongCrLf(); return is.readLongCrLf();
} }
private static List<Object> processMultiBulkReply(final RedisInputStream is) { private static List<Object> processMultiBulkReply(final RedisInputStream is) {
final int num = is.readIntCrLf(); final int num = is.readIntCrLf();
if (num == -1) { if (num == -1) {
return null; return null;
} }
final List<Object> ret = new ArrayList<Object>(num); final List<Object> ret = new ArrayList<Object>(num);
for (int i = 0; i < num; i++) { for (int i = 0; i < num; i++) {
try { try {
ret.add(process(is)); ret.add(process(is));
} catch (JedisDataException e) { } catch (JedisDataException e) {
ret.add(e); ret.add(e);
} }
} }
return ret; return ret;
} }
public static Object read(final RedisInputStream is) { public static Object read(final RedisInputStream is) {
return process(is); return process(is);
} }
public static final byte[] toByteArray(final boolean value) { public static final byte[] toByteArray(final boolean value) {
return toByteArray(value ? 1 : 0); return toByteArray(value ? 1 : 0);
} }
public static final byte[] toByteArray(final int value) { public static final byte[] toByteArray(final int value) {
return SafeEncoder.encode(String.valueOf(value)); return SafeEncoder.encode(String.valueOf(value));
} }
public static final byte[] toByteArray(final long value) { public static final byte[] toByteArray(final long value) {
return SafeEncoder.encode(String.valueOf(value)); return SafeEncoder.encode(String.valueOf(value));
} }
public static final byte[] toByteArray(final double value) { public static final byte[] toByteArray(final double value) {
return SafeEncoder.encode(String.valueOf(value)); return SafeEncoder.encode(String.valueOf(value));
} }
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, PUBSUB, ZCOUNT, ZRANGEBYSCORE, ZREVRANGEBYSCORE, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZUNIONSTORE, ZINTERSTORE, ZLEXCOUNT, ZRANGEBYLEX, ZREVRANGEBYLEX, ZREMRANGEBYLEX, SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE, SHUTDOWN, INFO, MONITOR, SLAVEOF, CONFIG, STRLEN, SYNC, LPUSHX, PERSIST, RPUSHX, ECHO, LINSERT, DEBUG, BRPOPLPUSH, SETBIT, GETBIT, BITPOS, SETRANGE, GETRANGE, EVAL, EVALSHA, SCRIPT, SLOWLOG, OBJECT, BITCOUNT, BITOP, SENTINEL, DUMP, RESTORE, PEXPIRE, PEXPIREAT, PTTL, INCRBYFLOAT, PSETEX, CLIENT, TIME, MIGRATE, HINCRBYFLOAT, SCAN, HSCAN, SSCAN, ZSCAN, WAIT, CLUSTER, ASKING, PFADD, PFCOUNT, PFMERGE; 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, ZLEXCOUNT, ZRANGEBYLEX, ZREVRANGEBYLEX, ZREMRANGEBYLEX, SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE, SHUTDOWN, INFO, MONITOR, SLAVEOF, CONFIG, STRLEN, SYNC, LPUSHX, PERSIST, RPUSHX, ECHO, LINSERT, DEBUG, BRPOPLPUSH, SETBIT, GETBIT, BITPOS, SETRANGE, GETRANGE, EVAL, EVALSHA, SCRIPT, SLOWLOG, OBJECT, BITCOUNT, BITOP, SENTINEL, DUMP, RESTORE, PEXPIRE, PEXPIREAT, PTTL, INCRBYFLOAT, PSETEX, CLIENT, TIME, MIGRATE, HINCRBYFLOAT, SCAN, HSCAN, SSCAN, ZSCAN, WAIT, CLUSTER, ASKING, PFADD, PFCOUNT, PFMERGE;
public final byte[] raw; public final byte[] raw;
Command() { Command() {
raw = SafeEncoder.encode(this.name()); raw = SafeEncoder.encode(this.name());
} }
} }
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, GETNAME, SETNAME, LIST, MATCH, COUNT; AGGREGATE, ALPHA, ASC, BY, DESC, GET, LIMIT, MESSAGE, NO, NOSORT, PMESSAGE, PSUBSCRIBE, PUNSUBSCRIBE, OK, ONE, QUEUED, SET, STORE, SUBSCRIBE, UNSUBSCRIBE, WEIGHTS, WITHSCORES, RESETSTAT, RESET, FLUSH, EXISTS, LOAD, KILL, LEN, REFCOUNT, ENCODING, IDLETIME, AND, OR, XOR, NOT, GETNAME, SETNAME, LIST, MATCH, COUNT;
public final byte[] raw; public final byte[] raw;
Keyword() { Keyword() {
raw = SafeEncoder.encode(this.name().toLowerCase()); raw = SafeEncoder.encode(this.name().toLowerCase());
} }
} }
} }

View File

@@ -7,28 +7,28 @@ public class Queable {
private Queue<Response<?>> pipelinedResponses = new LinkedList<Response<?>>(); private Queue<Response<?>> pipelinedResponses = new LinkedList<Response<?>>();
protected void clean() { protected void clean() {
pipelinedResponses.clear(); pipelinedResponses.clear();
} }
protected Response<?> generateResponse(Object data) { protected Response<?> generateResponse(Object data) {
Response<?> response = pipelinedResponses.poll(); Response<?> response = pipelinedResponses.poll();
if (response != null) { if (response != null) {
response.set(data); response.set(data);
} }
return response; return response;
} }
protected <T> Response<T> getResponse(Builder<T> builder) { protected <T> Response<T> getResponse(Builder<T> builder) {
Response<T> lr = new Response<T>(builder); Response<T> lr = new Response<T>(builder);
pipelinedResponses.add(lr); pipelinedResponses.add(lr);
return lr; return lr;
} }
protected boolean hasPipelinedResponse() { protected boolean hasPipelinedResponse() {
return pipelinedResponses.size() > 0; return pipelinedResponses.size() > 0;
} }
protected int getPipelinedResponseLength() { protected int getPipelinedResponseLength() {
return pipelinedResponses.size(); return pipelinedResponses.size();
} }
} }

View File

@@ -67,7 +67,7 @@ public interface RedisPipeline {
Response<String> lindex(String key, long index); Response<String> lindex(String key, long index);
Response<Long> linsert(String key, BinaryClient.LIST_POSITION where, Response<Long> linsert(String key, BinaryClient.LIST_POSITION where,
String pivot, String value); String pivot, String value);
Response<Long> llen(String key); Response<Long> llen(String key);
@@ -146,26 +146,26 @@ public interface RedisPipeline {
Response<Set<String>> zrangeByScore(String key, String min, String max); Response<Set<String>> zrangeByScore(String key, String min, String max);
Response<Set<String>> zrangeByScore(String key, double min, double max, Response<Set<String>> zrangeByScore(String key, double min, 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);
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, double min); 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, String max, String min);
Response<Set<String>> zrevrangeByScore(String key, double max, double min, Response<Set<String>> zrevrangeByScore(String key, double max, double min,
int offset, int count); int offset, int count);
Response<Set<Tuple>> zrevrangeByScoreWithScores(String key, double max, Response<Set<Tuple>> zrevrangeByScoreWithScores(String key, double max,
double min); double min);
Response<Set<Tuple>> zrevrangeByScoreWithScores(String key, double max, Response<Set<Tuple>> zrevrangeByScoreWithScores(String key, double max,
double min, int offset, int count); 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);
@@ -186,22 +186,22 @@ public interface RedisPipeline {
Response<Double> zscore(String key, String member); Response<Double> zscore(String key, String member);
Response<Long> zlexcount(final String key, final String min, Response<Long> zlexcount(final String key, final String min,
final String max); final String max);
Response<Set<String>> zrangeByLex(final String key, final String min, Response<Set<String>> zrangeByLex(final String key, final String min,
final String max); final String max);
Response<Set<String>> zrangeByLex(final String key, final String min, Response<Set<String>> zrangeByLex(final String key, final String min,
final String max, final int offset, final int count); final String max, final int offset, final int count);
Response<Set<String>> zrevrangeByLex(final String key, final String max, Response<Set<String>> zrevrangeByLex(final String key, final String max,
final String min); final String min);
Response<Set<String>> zrevrangeByLex(final String key, final String max, Response<Set<String>> zrevrangeByLex(final String key, final String max,
final String min, final int offset, final int count); final String min, final int offset, final int count);
Response<Long> zremrangeByLex(final String key, final String start, Response<Long> zremrangeByLex(final String key, final String start,
final String end); final String end);
Response<Long> bitcount(String key); Response<Long> bitcount(String key);

View File

@@ -12,50 +12,50 @@ public class Response<T> {
private boolean requestDependencyBuild = false; private boolean requestDependencyBuild = false;
public Response(Builder<T> b) { public Response(Builder<T> b) {
this.builder = b; this.builder = b;
} }
public void set(Object data) { public void set(Object data) {
this.data = data; this.data = data;
set = true; set = true;
} }
public T get() { public T get() {
// if response has dependency response and dependency is not built, // if response has dependency response and dependency is not built,
// build it first and no more!! // build it first and no more!!
if (!requestDependencyBuild && dependency != null && dependency.set if (!requestDependencyBuild && dependency != null && dependency.set
&& !dependency.built) { && !dependency.built) {
requestDependencyBuild = true; requestDependencyBuild = true;
dependency.build(); dependency.build();
} }
if (!set) { if (!set) {
throw new JedisDataException( throw new JedisDataException(
"Please close pipeline or multi block before calling this method."); "Please close pipeline or multi block before calling this method.");
} }
if (!built) { if (!built) {
build(); build();
} }
return response; return response;
} }
public void setDependency(Response<?> dependency) { public void setDependency(Response<?> dependency) {
this.dependency = dependency; this.dependency = dependency;
this.requestDependencyBuild = false; this.requestDependencyBuild = false;
} }
private void build() { private void build() {
if (data != null) { if (data != null) {
if (data instanceof JedisDataException) { if (data instanceof JedisDataException) {
throw new JedisDataException((JedisDataException) data); throw new JedisDataException((JedisDataException) data);
} }
response = builder.build(data); response = builder.build(data);
} }
data = null; data = null;
built = true; built = true;
} }
public String toString() { public String toString() {
return "Response " + builder.toString(); return "Response " + builder.toString();
} }
} }

View File

@@ -14,27 +14,27 @@ public class ScanParams {
private List<byte[]> params = new ArrayList<byte[]>(); private List<byte[]> params = new ArrayList<byte[]>();
public final static String SCAN_POINTER_START = String.valueOf(0); public final static String SCAN_POINTER_START = String.valueOf(0);
public final static byte[] SCAN_POINTER_START_BINARY = SafeEncoder public final static byte[] SCAN_POINTER_START_BINARY = SafeEncoder
.encode(SCAN_POINTER_START); .encode(SCAN_POINTER_START);
public ScanParams match(final byte[] pattern) { public ScanParams match(final byte[] pattern) {
params.add(MATCH.raw); params.add(MATCH.raw);
params.add(pattern); params.add(pattern);
return this; return this;
} }
public ScanParams match(final String pattern) { public ScanParams match(final String pattern) {
params.add(MATCH.raw); params.add(MATCH.raw);
params.add(SafeEncoder.encode(pattern)); params.add(SafeEncoder.encode(pattern));
return this; return this;
} }
public ScanParams count(final int count) { public ScanParams count(final int count) {
params.add(COUNT.raw); params.add(COUNT.raw);
params.add(Protocol.toByteArray(count)); params.add(Protocol.toByteArray(count));
return this; return this;
} }
public Collection<byte[]> getParams() { public Collection<byte[]> getParams() {
return Collections.unmodifiableCollection(params); return Collections.unmodifiableCollection(params);
} }
} }

View File

@@ -9,23 +9,23 @@ public class ScanResult<T> {
private List<T> results; private List<T> results;
public ScanResult(String cursor, List<T> results) { public ScanResult(String cursor, List<T> results) {
this(SafeEncoder.encode(cursor), results); this(SafeEncoder.encode(cursor), results);
} }
public ScanResult(byte[] cursor, List<T> results) { public ScanResult(byte[] cursor, List<T> results) {
this.cursor = cursor; this.cursor = cursor;
this.results = results; this.results = results;
} }
public String getCursor() { public String getCursor() {
return SafeEncoder.encode(cursor); return SafeEncoder.encode(cursor);
} }
public byte[] getCursorAsBytes() { public byte[] getCursorAsBytes() {
return cursor; return cursor;
} }
public List<T> getResult() { public List<T> getResult() {
return results; return results;
} }
} }

View File

@@ -15,10 +15,10 @@ public interface SentinelCommands {
public String sentinelFailover(String masterName); public String sentinelFailover(String masterName);
public String sentinelMonitor(String masterName, String ip, int port, public String sentinelMonitor(String masterName, String ip, int port,
int quorum); int quorum);
public String sentinelRemove(String masterName); public String sentinelRemove(String masterName);
public String sentinelSet(String masterName, public String sentinelSet(String masterName,
Map<String, String> parameterMap); Map<String, String> parameterMap);
} }

View File

@@ -12,648 +12,648 @@ import redis.clients.util.Hashing;
import redis.clients.util.Pool; import redis.clients.util.Pool;
public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, public class ShardedJedis extends BinaryShardedJedis implements JedisCommands,
Closeable { Closeable {
protected Pool<ShardedJedis> dataSource = null; protected Pool<ShardedJedis> dataSource = null;
public ShardedJedis(List<JedisShardInfo> shards) { public ShardedJedis(List<JedisShardInfo> shards) {
super(shards); super(shards);
} }
public ShardedJedis(List<JedisShardInfo> shards, Hashing algo) { public ShardedJedis(List<JedisShardInfo> shards, Hashing algo) {
super(shards, algo); super(shards, algo);
} }
public ShardedJedis(List<JedisShardInfo> shards, Pattern keyTagPattern) { public ShardedJedis(List<JedisShardInfo> shards, Pattern keyTagPattern) {
super(shards, keyTagPattern); super(shards, keyTagPattern);
} }
public ShardedJedis(List<JedisShardInfo> shards, Hashing algo, public ShardedJedis(List<JedisShardInfo> shards, Hashing algo,
Pattern keyTagPattern) { Pattern keyTagPattern) {
super(shards, algo, keyTagPattern); super(shards, algo, keyTagPattern);
} }
public String set(String key, String value) { public String set(String key, String value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.set(key, value); return j.set(key, value);
} }
@Override @Override
public String set(String key, String value, String nxxx, String expx, public String set(String key, String value, String nxxx, String expx,
long time) { long time) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.set(key, value, nxxx, expx, time); return j.set(key, value, nxxx, expx, time);
} }
public String get(String key) { public String get(String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.get(key); return j.get(key);
} }
public String echo(String string) { public String echo(String string) {
Jedis j = getShard(string); Jedis j = getShard(string);
return j.echo(string); return j.echo(string);
} }
public Boolean exists(String key) { public Boolean exists(String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.exists(key); return j.exists(key);
} }
public String type(String key) { public String type(String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.type(key); return j.type(key);
} }
public Long expire(String key, int seconds) { public Long expire(String key, int seconds) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.expire(key, seconds); return j.expire(key, seconds);
} }
public Long expireAt(String key, long unixTime) { public Long expireAt(String key, long unixTime) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.expireAt(key, unixTime); return j.expireAt(key, unixTime);
} }
public Long ttl(String key) { public Long ttl(String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.ttl(key); return j.ttl(key);
} }
public Boolean setbit(String key, long offset, boolean value) { public Boolean setbit(String key, long offset, boolean value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.setbit(key, offset, value); return j.setbit(key, offset, value);
} }
public Boolean setbit(String key, long offset, String value) { public Boolean setbit(String key, long offset, String value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.setbit(key, offset, value); return j.setbit(key, offset, value);
} }
public Boolean getbit(String key, long offset) { public Boolean getbit(String key, long offset) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.getbit(key, offset); return j.getbit(key, offset);
} }
public Long setrange(String key, long offset, String value) { public Long setrange(String key, long offset, String value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.setrange(key, offset, value); return j.setrange(key, offset, value);
} }
public String getrange(String key, long startOffset, long endOffset) { public String getrange(String key, long startOffset, long endOffset) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.getrange(key, startOffset, endOffset); return j.getrange(key, startOffset, endOffset);
} }
public String getSet(String key, String value) { public String getSet(String key, String value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.getSet(key, value); return j.getSet(key, value);
} }
public Long setnx(String key, String value) { public Long setnx(String key, String value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.setnx(key, value); return j.setnx(key, value);
} }
public String setex(String key, int seconds, String value) { public String setex(String key, int seconds, String value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.setex(key, seconds, value); return j.setex(key, seconds, value);
} }
public List<String> blpop(String arg) { public List<String> blpop(String arg) {
Jedis j = getShard(arg); Jedis j = getShard(arg);
return j.blpop(arg); return j.blpop(arg);
} }
public List<String> blpop(int timeout, String key) { public List<String> blpop(int timeout, String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.blpop(timeout, key); return j.blpop(timeout, key);
} }
public List<String> brpop(String arg) { public List<String> brpop(String arg) {
Jedis j = getShard(arg); Jedis j = getShard(arg);
return j.brpop(arg); return j.brpop(arg);
} }
public List<String> brpop(int timeout, String key) { public List<String> brpop(int timeout, String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.brpop(timeout, key); return j.brpop(timeout, key);
} }
public Long decrBy(String key, long integer) { public Long decrBy(String key, long integer) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.decrBy(key, integer); return j.decrBy(key, integer);
} }
public Long decr(String key) { public Long decr(String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.decr(key); return j.decr(key);
} }
public Long incrBy(String key, long integer) { public Long incrBy(String key, long integer) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.incrBy(key, integer); return j.incrBy(key, integer);
} }
public Double incrByFloat(String key, double integer) { public Double incrByFloat(String key, double integer) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.incrByFloat(key, integer); return j.incrByFloat(key, integer);
} }
public Long incr(String key) { public Long incr(String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.incr(key); return j.incr(key);
} }
public Long append(String key, String value) { public Long append(String key, String value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.append(key, value); return j.append(key, value);
} }
public String substr(String key, int start, int end) { public String substr(String key, int start, int end) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.substr(key, start, end); return j.substr(key, start, end);
} }
public Long hset(String key, String field, String value) { public Long hset(String key, String field, String value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hset(key, field, value); return j.hset(key, field, value);
} }
public String hget(String key, String field) { public String hget(String key, String field) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hget(key, field); return j.hget(key, field);
} }
public Long hsetnx(String key, String field, String value) { public Long hsetnx(String key, String field, String value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hsetnx(key, field, value); return j.hsetnx(key, field, value);
} }
public String hmset(String key, Map<String, String> hash) { public String hmset(String key, Map<String, String> hash) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hmset(key, hash); return j.hmset(key, hash);
} }
public List<String> hmget(String key, String... fields) { public List<String> hmget(String key, String... fields) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hmget(key, fields); return j.hmget(key, fields);
} }
public Long hincrBy(String key, String field, long value) { public Long hincrBy(String key, String field, long value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hincrBy(key, field, value); return j.hincrBy(key, field, value);
} }
public Double hincrByFloat(String key, String field, double value) { public Double hincrByFloat(String key, String field, double value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hincrByFloat(key, field, value); return j.hincrByFloat(key, field, value);
} }
public Boolean hexists(String key, String field) { public Boolean hexists(String key, String field) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hexists(key, field); return j.hexists(key, field);
} }
public Long del(String key) { public Long del(String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.del(key); return j.del(key);
} }
public Long hdel(String key, String... fields) { public Long hdel(String key, String... fields) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hdel(key, fields); return j.hdel(key, fields);
} }
public Long hlen(String key) { public Long hlen(String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hlen(key); return j.hlen(key);
} }
public Set<String> hkeys(String key) { public Set<String> hkeys(String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hkeys(key); return j.hkeys(key);
} }
public List<String> hvals(String key) { public List<String> hvals(String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hvals(key); return j.hvals(key);
} }
public Map<String, String> hgetAll(String key) { public Map<String, String> hgetAll(String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hgetAll(key); return j.hgetAll(key);
} }
public Long rpush(String key, String... strings) { public Long rpush(String key, String... strings) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.rpush(key, strings); return j.rpush(key, strings);
} }
public Long lpush(String key, String... strings) { public Long lpush(String key, String... strings) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.lpush(key, strings); return j.lpush(key, strings);
} }
public Long lpushx(String key, String... string) { public Long lpushx(String key, String... string) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.lpushx(key, string); return j.lpushx(key, string);
} }
public Long strlen(final String key) { public Long strlen(final String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.strlen(key); return j.strlen(key);
} }
public Long move(String key, int dbIndex) { public Long move(String key, int dbIndex) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.move(key, dbIndex); return j.move(key, dbIndex);
} }
public Long rpushx(String key, String... string) { public Long rpushx(String key, String... string) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.rpushx(key, string); return j.rpushx(key, string);
} }
public Long persist(final String key) { public Long persist(final String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.persist(key); return j.persist(key);
} }
public Long llen(String key) { public Long llen(String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.llen(key); return j.llen(key);
} }
public List<String> lrange(String key, long start, long end) { public List<String> lrange(String key, long start, long end) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.lrange(key, start, end); return j.lrange(key, start, end);
} }
public String ltrim(String key, long start, long end) { public String ltrim(String key, long start, long end) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.ltrim(key, start, end); return j.ltrim(key, start, end);
} }
public String lindex(String key, long index) { public String lindex(String key, long index) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.lindex(key, index); return j.lindex(key, index);
} }
public String lset(String key, long index, String value) { public String lset(String key, long index, String value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.lset(key, index, value); return j.lset(key, index, value);
} }
public Long lrem(String key, long count, String value) { public Long lrem(String key, long count, String value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.lrem(key, count, value); return j.lrem(key, count, value);
} }
public String lpop(String key) { public String lpop(String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.lpop(key); return j.lpop(key);
} }
public String rpop(String key) { public String rpop(String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.rpop(key); return j.rpop(key);
} }
public Long sadd(String key, String... members) { public Long sadd(String key, String... members) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.sadd(key, members); return j.sadd(key, members);
} }
public Set<String> smembers(String key) { public Set<String> smembers(String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.smembers(key); return j.smembers(key);
} }
public Long srem(String key, String... members) { public Long srem(String key, String... members) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.srem(key, members); return j.srem(key, members);
} }
public String spop(String key) { public String spop(String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.spop(key); return j.spop(key);
} }
public Long scard(String key) { public Long scard(String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.scard(key); return j.scard(key);
} }
public Boolean sismember(String key, String member) { public Boolean sismember(String key, String member) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.sismember(key, member); return j.sismember(key, member);
} }
public String srandmember(String key) { public String srandmember(String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.srandmember(key); return j.srandmember(key);
} }
@Override @Override
public List<String> srandmember(String key, int count) { public List<String> srandmember(String key, int count) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.srandmember(key, count); return j.srandmember(key, count);
} }
public Long zadd(String key, double score, String member) { public Long zadd(String key, double score, String member) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zadd(key, score, member); return j.zadd(key, score, member);
} }
public Long zadd(String key, Map<String, Double> 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);
} }
public Set<String> zrange(String key, long start, long end) { public Set<String> zrange(String key, long start, long end) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrange(key, start, end); return j.zrange(key, start, end);
} }
public Long zrem(String key, String... members) { public Long zrem(String key, String... members) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrem(key, members); return j.zrem(key, members);
} }
public Double zincrby(String key, double score, String member) { public Double zincrby(String key, double score, String member) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zincrby(key, score, member); return j.zincrby(key, score, member);
} }
public Long zrank(String key, String member) { public Long zrank(String key, String member) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrank(key, member); return j.zrank(key, member);
} }
public Long zrevrank(String key, String member) { public Long zrevrank(String key, String member) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrank(key, member); return j.zrevrank(key, member);
} }
public Set<String> zrevrange(String key, long start, long end) { public Set<String> zrevrange(String key, long start, long end) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrange(key, start, end); return j.zrevrange(key, start, end);
} }
public Set<Tuple> zrangeWithScores(String key, long start, long end) { public Set<Tuple> zrangeWithScores(String key, long start, long end) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrangeWithScores(key, start, end); return j.zrangeWithScores(key, start, end);
} }
public Set<Tuple> zrevrangeWithScores(String key, long start, long end) { public Set<Tuple> zrevrangeWithScores(String key, long start, long end) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrangeWithScores(key, start, end); return j.zrevrangeWithScores(key, start, end);
} }
public Long zcard(String key) { public Long zcard(String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zcard(key); return j.zcard(key);
} }
public Double zscore(String key, String member) { public Double zscore(String key, String member) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zscore(key, member); return j.zscore(key, member);
} }
public List<String> sort(String key) { public List<String> sort(String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.sort(key); return j.sort(key);
} }
public List<String> sort(String key, SortingParams sortingParameters) { public List<String> sort(String key, SortingParams sortingParameters) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.sort(key, sortingParameters); return j.sort(key, sortingParameters);
} }
public Long zcount(String key, double min, double max) { public Long zcount(String key, double min, double max) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zcount(key, min, max); return j.zcount(key, min, max);
} }
public Long zcount(String key, String min, String max) { public Long zcount(String key, String min, String max) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zcount(key, min, max); return j.zcount(key, min, max);
} }
public Set<String> zrangeByScore(String key, double min, double max) { public Set<String> zrangeByScore(String key, double min, double max) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrangeByScore(key, min, max); return j.zrangeByScore(key, min, max);
} }
public Set<String> zrevrangeByScore(String key, double max, double min) { public Set<String> zrevrangeByScore(String key, double max, double min) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min); return j.zrevrangeByScore(key, max, min);
} }
public Set<String> zrangeByScore(String key, double min, double max, public Set<String> zrangeByScore(String key, double min, double max,
int offset, int count) { int offset, int count) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrangeByScore(key, min, max, offset, count); return j.zrangeByScore(key, min, max, offset, count);
} }
public Set<String> zrevrangeByScore(String key, double max, double min, public Set<String> zrevrangeByScore(String key, double max, double min,
int offset, int count) { int offset, int count) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min, offset, count); return j.zrevrangeByScore(key, max, min, offset, count);
} }
public Set<Tuple> zrangeByScoreWithScores(String key, double min, double max) { public Set<Tuple> zrangeByScoreWithScores(String key, double min, double max) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max); return j.zrangeByScoreWithScores(key, min, max);
} }
public Set<Tuple> zrevrangeByScoreWithScores(String key, double max, public Set<Tuple> zrevrangeByScoreWithScores(String key, double max,
double min) { double min) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min); return j.zrevrangeByScoreWithScores(key, max, min);
} }
public Set<Tuple> zrangeByScoreWithScores(String key, double min, public Set<Tuple> zrangeByScoreWithScores(String key, double min,
double max, int offset, int count) { double max, int offset, int count) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max, offset, count); return j.zrangeByScoreWithScores(key, min, max, offset, count);
} }
public Set<Tuple> zrevrangeByScoreWithScores(String key, double max, public Set<Tuple> zrevrangeByScoreWithScores(String key, double max,
double min, int offset, int count) { double min, int offset, int count) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min, offset, count); return j.zrevrangeByScoreWithScores(key, max, min, offset, count);
} }
public Set<String> zrangeByScore(String key, String min, String max) { public Set<String> zrangeByScore(String key, String min, String max) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrangeByScore(key, min, max); return j.zrangeByScore(key, min, max);
} }
public Set<String> zrevrangeByScore(String key, String max, String min) { public Set<String> zrevrangeByScore(String key, String max, String min) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min); return j.zrevrangeByScore(key, max, min);
} }
public Set<String> zrangeByScore(String key, String min, String max, public Set<String> zrangeByScore(String key, String min, String max,
int offset, int count) { int offset, int count) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrangeByScore(key, min, max, offset, count); return j.zrangeByScore(key, min, max, offset, count);
} }
public Set<String> zrevrangeByScore(String key, String max, String min, public Set<String> zrevrangeByScore(String key, String max, String min,
int offset, int count) { int offset, int count) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrangeByScore(key, max, min, offset, count); return j.zrevrangeByScore(key, max, min, offset, count);
} }
public Set<Tuple> zrangeByScoreWithScores(String key, String min, String max) { public Set<Tuple> zrangeByScoreWithScores(String key, String min, String max) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max); return j.zrangeByScoreWithScores(key, min, max);
} }
public Set<Tuple> zrevrangeByScoreWithScores(String key, String max, public Set<Tuple> zrevrangeByScoreWithScores(String key, String max,
String min) { String min) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min); return j.zrevrangeByScoreWithScores(key, max, min);
} }
public Set<Tuple> zrangeByScoreWithScores(String key, String min, public Set<Tuple> zrangeByScoreWithScores(String key, String min,
String max, int offset, int count) { String max, int offset, int count) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max, offset, count); return j.zrangeByScoreWithScores(key, min, max, offset, count);
} }
public Set<Tuple> zrevrangeByScoreWithScores(String key, String max, public Set<Tuple> zrevrangeByScoreWithScores(String key, String max,
String min, int offset, int count) { String min, int offset, int count) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min, offset, count); return j.zrevrangeByScoreWithScores(key, max, min, offset, count);
} }
public Long zremrangeByRank(String key, long start, long end) { public Long zremrangeByRank(String key, long start, long end) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zremrangeByRank(key, start, end); return j.zremrangeByRank(key, start, end);
} }
public Long zremrangeByScore(String key, double start, double end) { public Long zremrangeByScore(String key, double start, double end) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zremrangeByScore(key, start, end); return j.zremrangeByScore(key, start, end);
} }
public Long zremrangeByScore(String key, String start, String end) { public Long zremrangeByScore(String key, String start, String end) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zremrangeByScore(key, start, end); return j.zremrangeByScore(key, start, end);
} }
@Override @Override
public Long zlexcount(final String key, final String min, final String max) { public Long zlexcount(final String key, final String min, final String max) {
return getShard(key).zlexcount(key, min, max); return getShard(key).zlexcount(key, min, max);
} }
@Override @Override
public Set<String> zrangeByLex(final String key, final String min, public Set<String> zrangeByLex(final String key, final String min,
final String max) { final String max) {
return getShard(key).zrangeByLex(key, min, max); return getShard(key).zrangeByLex(key, min, max);
} }
@Override @Override
public Set<String> zrangeByLex(final String key, final String min, public Set<String> zrangeByLex(final String key, final String min,
final String max, final int offset, final int count) { final String max, final int offset, final int count) {
return getShard(key).zrangeByLex(key, min, max, offset, count); return getShard(key).zrangeByLex(key, min, max, offset, count);
} }
@Override @Override
public Set<String> zrevrangeByLex(String key, String max, String min) { public Set<String> zrevrangeByLex(String key, String max, String min) {
return getShard(key).zrevrangeByLex(key, max, min); return getShard(key).zrevrangeByLex(key, max, min);
} }
@Override @Override
public Set<String> zrevrangeByLex(String key, String max, String min, public Set<String> zrevrangeByLex(String key, String max, String min,
int offset, int count) { int offset, int count) {
return getShard(key).zrevrangeByLex(key, max, min, offset, count); return getShard(key).zrevrangeByLex(key, max, min, offset, count);
} }
@Override @Override
public Long zremrangeByLex(final String key, final String min, public Long zremrangeByLex(final String key, final String min,
final String max) { final String max) {
return getShard(key).zremrangeByLex(key, min, max); return getShard(key).zremrangeByLex(key, min, max);
} }
public Long linsert(String key, LIST_POSITION where, String pivot, public Long linsert(String key, LIST_POSITION where, String pivot,
String value) { String value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.linsert(key, where, pivot, value); return j.linsert(key, where, pivot, value);
} }
public Long bitcount(final String key) { public Long bitcount(final String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.bitcount(key); return j.bitcount(key);
} }
public Long bitcount(final String key, long start, long end) { public Long bitcount(final String key, long start, long end) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.bitcount(key, start, end); return j.bitcount(key, start, end);
} }
public ScanResult<Entry<String, String>> hscan(String key, public ScanResult<Entry<String, String>> hscan(String key,
final String cursor) { final String cursor) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.hscan(key, cursor); return j.hscan(key, cursor);
} }
public ScanResult<String> sscan(String key, final String cursor) { public ScanResult<String> sscan(String key, final String cursor) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.sscan(key, cursor); return j.sscan(key, cursor);
} }
public ScanResult<Tuple> zscan(String key, final String cursor) { public ScanResult<Tuple> zscan(String key, final String cursor) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zscan(key, cursor); return j.zscan(key, cursor);
} }
@Override @Override
public void close() { public void close() {
if (dataSource != null) { if (dataSource != null) {
boolean broken = false; boolean broken = false;
for (Jedis jedis : getAllShards()) { for (Jedis jedis : getAllShards()) {
if (jedis.getClient().isBroken()) { if (jedis.getClient().isBroken()) {
broken = true; broken = true;
} }
} }
if (broken) { if (broken) {
dataSource.returnBrokenResource(this); dataSource.returnBrokenResource(this);
} else { } else {
this.resetState(); this.resetState();
dataSource.returnResource(this); dataSource.returnResource(this);
} }
} else { } else {
disconnect(); disconnect();
} }
} }
public void setDataSource(Pool<ShardedJedis> shardedJedisPool) { public void setDataSource(Pool<ShardedJedis> shardedJedisPool) {
this.dataSource = shardedJedisPool; this.dataSource = shardedJedisPool;
} }
public void resetState() { public void resetState() {
for (Jedis jedis : getAllShards()) { for (Jedis jedis : getAllShards()) {
jedis.resetState(); jedis.resetState();
} }
} }
public Long pfadd(String key, String... elements) { public Long pfadd(String key, String... elements) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.pfadd(key, elements); return j.pfadd(key, elements);
} }
@Override @Override
public long pfcount(String key) { public long pfcount(String key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.pfcount(key); return j.pfcount(key);
} }
} }

View File

@@ -11,27 +11,27 @@ public class ShardedJedisPipeline extends PipelineBase {
private Queue<Client> clients = new LinkedList<Client>(); private Queue<Client> clients = new LinkedList<Client>();
private static class FutureResult { private static class FutureResult {
private Client client; private Client client;
public FutureResult(Client client) { public FutureResult(Client client) {
this.client = client; this.client = client;
} }
public Object get() { public Object get() {
return client.getOne(); return client.getOne();
} }
} }
public void setShardedJedis(BinaryShardedJedis jedis) { public void setShardedJedis(BinaryShardedJedis jedis) {
this.jedis = jedis; this.jedis = jedis;
} }
public List<Object> getResults() { public List<Object> getResults() {
List<Object> r = new ArrayList<Object>(); List<Object> r = new ArrayList<Object>();
for (FutureResult fr : results) { for (FutureResult fr : results) {
r.add(fr.get()); r.add(fr.get());
} }
return r; return r;
} }
/** /**
@@ -40,9 +40,9 @@ public class ShardedJedisPipeline extends PipelineBase {
* the different Response&lt;?&gt; of the commands you execute. * the different Response&lt;?&gt; of the commands you execute.
*/ */
public void sync() { public void sync() {
for (Client client : clients) { for (Client client : clients) {
generateResponse(client.getOne()); generateResponse(client.getOne());
} }
} }
/** /**
@@ -54,26 +54,26 @@ public class ShardedJedisPipeline extends PipelineBase {
* @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.
*/ */
public List<Object> syncAndReturnAll() { public List<Object> syncAndReturnAll() {
List<Object> formatted = new ArrayList<Object>(); List<Object> formatted = new ArrayList<Object>();
for (Client client : clients) { for (Client client : clients) {
formatted.add(generateResponse(client.getOne()).get()); formatted.add(generateResponse(client.getOne()).get());
} }
return formatted; return formatted;
} }
@Override @Override
protected Client getClient(String key) { protected Client getClient(String key) {
Client client = jedis.getShard(key).getClient(); Client client = jedis.getShard(key).getClient();
clients.add(client); clients.add(client);
results.add(new FutureResult(client)); results.add(new FutureResult(client));
return client; return client;
} }
@Override @Override
protected Client getClient(byte[] key) { protected Client getClient(byte[] key) {
Client client = jedis.getShard(key).getClient(); Client client = jedis.getShard(key).getClient();
clients.add(client); clients.add(client);
results.add(new FutureResult(client)); results.add(new FutureResult(client));
return client; return client;
} }
} }

View File

@@ -13,113 +13,113 @@ import redis.clients.util.Pool;
public class ShardedJedisPool extends Pool<ShardedJedis> { public class ShardedJedisPool extends Pool<ShardedJedis> {
public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, public ShardedJedisPool(final GenericObjectPoolConfig poolConfig,
List<JedisShardInfo> shards) { List<JedisShardInfo> shards) {
this(poolConfig, shards, Hashing.MURMUR_HASH); this(poolConfig, shards, Hashing.MURMUR_HASH);
} }
public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, public ShardedJedisPool(final GenericObjectPoolConfig poolConfig,
List<JedisShardInfo> shards, Hashing algo) { List<JedisShardInfo> shards, Hashing algo) {
this(poolConfig, shards, algo, null); this(poolConfig, shards, algo, null);
} }
public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, public ShardedJedisPool(final GenericObjectPoolConfig poolConfig,
List<JedisShardInfo> shards, Pattern keyTagPattern) { List<JedisShardInfo> shards, Pattern keyTagPattern) {
this(poolConfig, shards, Hashing.MURMUR_HASH, keyTagPattern); this(poolConfig, shards, Hashing.MURMUR_HASH, keyTagPattern);
} }
public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, public ShardedJedisPool(final GenericObjectPoolConfig poolConfig,
List<JedisShardInfo> shards, Hashing algo, Pattern keyTagPattern) { List<JedisShardInfo> shards, Hashing algo, Pattern keyTagPattern) {
super(poolConfig, new ShardedJedisFactory(shards, algo, keyTagPattern)); super(poolConfig, new ShardedJedisFactory(shards, algo, keyTagPattern));
} }
@Override @Override
public ShardedJedis getResource() { public ShardedJedis getResource() {
ShardedJedis jedis = super.getResource(); ShardedJedis jedis = super.getResource();
jedis.setDataSource(this); jedis.setDataSource(this);
return jedis; return jedis;
} }
@Override @Override
public void returnBrokenResource(final ShardedJedis resource) { public void returnBrokenResource(final ShardedJedis resource) {
if (resource != null) { if (resource != null) {
returnBrokenResourceObject(resource); returnBrokenResourceObject(resource);
} }
} }
@Override @Override
public void returnResource(final ShardedJedis resource) { public void returnResource(final ShardedJedis resource) {
if (resource != null) { if (resource != null) {
resource.resetState(); resource.resetState();
returnResourceObject(resource); returnResourceObject(resource);
} }
} }
/** /**
* PoolableObjectFactory custom impl. * PoolableObjectFactory custom impl.
*/ */
private static class ShardedJedisFactory implements private static class ShardedJedisFactory implements
PooledObjectFactory<ShardedJedis> { PooledObjectFactory<ShardedJedis> {
private List<JedisShardInfo> shards; private List<JedisShardInfo> shards;
private Hashing algo; private Hashing algo;
private Pattern keyTagPattern; private Pattern keyTagPattern;
public ShardedJedisFactory(List<JedisShardInfo> shards, Hashing algo, public ShardedJedisFactory(List<JedisShardInfo> shards, Hashing algo,
Pattern keyTagPattern) { Pattern keyTagPattern) {
this.shards = shards; this.shards = shards;
this.algo = algo; this.algo = algo;
this.keyTagPattern = keyTagPattern; this.keyTagPattern = keyTagPattern;
} }
@Override @Override
public PooledObject<ShardedJedis> makeObject() throws Exception { public PooledObject<ShardedJedis> makeObject() throws Exception {
ShardedJedis jedis = new ShardedJedis(shards, algo, keyTagPattern); ShardedJedis jedis = new ShardedJedis(shards, algo, keyTagPattern);
return new DefaultPooledObject<ShardedJedis>(jedis); return new DefaultPooledObject<ShardedJedis>(jedis);
} }
@Override @Override
public void destroyObject(PooledObject<ShardedJedis> pooledShardedJedis) public void destroyObject(PooledObject<ShardedJedis> pooledShardedJedis)
throws Exception { throws Exception {
final ShardedJedis shardedJedis = pooledShardedJedis.getObject(); final ShardedJedis shardedJedis = pooledShardedJedis.getObject();
for (Jedis jedis : shardedJedis.getAllShards()) { for (Jedis jedis : shardedJedis.getAllShards()) {
try { try {
try { try {
jedis.quit(); jedis.quit();
} catch (Exception e) { } catch (Exception e) {
} }
jedis.disconnect(); jedis.disconnect();
} catch (Exception e) { } catch (Exception e) {
} }
} }
} }
@Override @Override
public boolean validateObject( public boolean validateObject(
PooledObject<ShardedJedis> pooledShardedJedis) { PooledObject<ShardedJedis> pooledShardedJedis) {
try { try {
ShardedJedis jedis = pooledShardedJedis.getObject(); ShardedJedis jedis = pooledShardedJedis.getObject();
for (Jedis shard : jedis.getAllShards()) { for (Jedis shard : jedis.getAllShards()) {
if (!shard.ping().equals("PONG")) { if (!shard.ping().equals("PONG")) {
return false; return false;
} }
} }
return true; return true;
} catch (Exception ex) { } catch (Exception ex) {
return false; return false;
} }
} }
@Override @Override
public void activateObject(PooledObject<ShardedJedis> p) public void activateObject(PooledObject<ShardedJedis> p)
throws Exception { throws Exception {
} }
@Override @Override
public void passivateObject(PooledObject<ShardedJedis> p) public void passivateObject(PooledObject<ShardedJedis> p)
throws Exception { throws Exception {
} }
} }
} }

View File

@@ -36,7 +36,7 @@ public class SortingParams {
* @return the SortingParams Object * @return the SortingParams Object
*/ */
public SortingParams by(final String pattern) { public SortingParams by(final String pattern) {
return by(SafeEncoder.encode(pattern)); return by(SafeEncoder.encode(pattern));
} }
/** /**
@@ -53,9 +53,9 @@ public class SortingParams {
* @return the SortingParams Object * @return the SortingParams Object
*/ */
public SortingParams by(final byte[] pattern) { public SortingParams by(final byte[] pattern) {
params.add(BY.raw); params.add(BY.raw);
params.add(pattern); params.add(pattern);
return this; return this;
} }
/** /**
@@ -67,13 +67,13 @@ public class SortingParams {
* @return the SortingParams Object * @return the SortingParams Object
*/ */
public SortingParams nosort() { public SortingParams nosort() {
params.add(BY.raw); params.add(BY.raw);
params.add(NOSORT.raw); params.add(NOSORT.raw);
return this; return this;
} }
public Collection<byte[]> getParams() { public Collection<byte[]> getParams() {
return Collections.unmodifiableCollection(params); return Collections.unmodifiableCollection(params);
} }
/** /**
@@ -82,8 +82,8 @@ public class SortingParams {
* @return the sortingParams Object * @return the sortingParams Object
*/ */
public SortingParams desc() { public SortingParams desc() {
params.add(DESC.raw); params.add(DESC.raw);
return this; return this;
} }
/** /**
@@ -92,8 +92,8 @@ public class SortingParams {
* @return the SortingParams Object * @return the SortingParams Object
*/ */
public SortingParams asc() { public SortingParams asc() {
params.add(ASC.raw); params.add(ASC.raw);
return this; return this;
} }
/** /**
@@ -105,10 +105,10 @@ public class SortingParams {
* @return the SortingParams Object * @return the SortingParams Object
*/ */
public SortingParams limit(final int start, final int count) { public SortingParams limit(final int start, final int count) {
params.add(LIMIT.raw); params.add(LIMIT.raw);
params.add(Protocol.toByteArray(start)); params.add(Protocol.toByteArray(start));
params.add(Protocol.toByteArray(count)); params.add(Protocol.toByteArray(count));
return this; return this;
} }
/** /**
@@ -118,8 +118,8 @@ public class SortingParams {
* @return the SortingParams Object * @return the SortingParams Object
*/ */
public SortingParams alpha() { public SortingParams alpha() {
params.add(ALPHA.raw); params.add(ALPHA.raw);
return this; return this;
} }
/** /**
@@ -138,11 +138,11 @@ public class SortingParams {
* @return the SortingParams Object * @return the SortingParams Object
*/ */
public SortingParams get(String... patterns) { public SortingParams get(String... patterns) {
for (final String pattern : patterns) { for (final String pattern : patterns) {
params.add(GET.raw); params.add(GET.raw);
params.add(SafeEncoder.encode(pattern)); params.add(SafeEncoder.encode(pattern));
} }
return this; return this;
} }
/** /**
@@ -161,10 +161,10 @@ public class SortingParams {
* @return the SortingParams Object * @return the SortingParams Object
*/ */
public SortingParams get(byte[]... patterns) { public SortingParams get(byte[]... patterns) {
for (final byte[] pattern : patterns) { for (final byte[] pattern : patterns) {
params.add(GET.raw); params.add(GET.raw);
params.add(pattern); params.add(pattern);
} }
return this; return this;
} }
} }

View File

@@ -14,75 +14,75 @@ public class Transaction extends MultiKeyPipelineBase {
protected boolean inTransaction = true; protected boolean inTransaction = true;
protected Transaction() { protected Transaction() {
// client will be set later in transaction block // client will be set later in transaction block
} }
public Transaction(final Client client) { public Transaction(final Client client) {
this.client = client; this.client = client;
} }
@Override @Override
protected Client getClient(String key) { protected Client getClient(String key) {
return client; return client;
} }
@Override @Override
protected Client getClient(byte[] key) { protected Client getClient(byte[] key) {
return client; return client;
} }
public void clear() { public void clear() {
if (inTransaction) { if (inTransaction) {
discard(); discard();
} }
} }
public List<Object> exec() { public List<Object> exec() {
// Discard QUEUED or ERROR // Discard QUEUED or ERROR
client.getMany(getPipelinedResponseLength()); client.getMany(getPipelinedResponseLength());
client.exec(); client.exec();
List<Object> unformatted = client.getObjectMultiBulkReply(); List<Object> unformatted = client.getObjectMultiBulkReply();
if (unformatted == null) { if (unformatted == null) {
return null; return null;
} }
List<Object> formatted = new ArrayList<Object>(); List<Object> formatted = new ArrayList<Object>();
for (Object o : unformatted) { for (Object o : unformatted) {
try { try {
formatted.add(generateResponse(o).get()); formatted.add(generateResponse(o).get());
} catch (JedisDataException e) { } catch (JedisDataException e) {
formatted.add(e); formatted.add(e);
} }
} }
return formatted; return formatted;
} }
public List<Response<?>> execGetResponse() { public List<Response<?>> execGetResponse() {
// Discard QUEUED or ERROR // Discard QUEUED or ERROR
client.getMany(getPipelinedResponseLength()); client.getMany(getPipelinedResponseLength());
client.exec(); client.exec();
List<Object> unformatted = client.getObjectMultiBulkReply(); List<Object> unformatted = client.getObjectMultiBulkReply();
if (unformatted == null) { if (unformatted == null) {
return null; return null;
} }
List<Response<?>> response = new ArrayList<Response<?>>(); List<Response<?>> response = new ArrayList<Response<?>>();
for (Object o : unformatted) { for (Object o : unformatted) {
response.add(generateResponse(o)); response.add(generateResponse(o));
} }
return response; return response;
} }
public String discard() { public String discard() {
client.getMany(getPipelinedResponseLength()); client.getMany(getPipelinedResponseLength());
client.discard(); client.discard();
inTransaction = false; inTransaction = false;
clean(); clean();
return client.getStatusCodeReply(); return client.getStatusCodeReply();
} }
public void setClient(Client client) { public void setClient(Client client) {
this.client = client; this.client = client;
} }
} }

View File

@@ -9,72 +9,72 @@ public class Tuple implements Comparable<Tuple> {
private Double score; private Double score;
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result; result = prime * result;
if (null != element) { if (null != element) {
for (final byte b : element) { for (final byte b : element) {
result = prime * result + b; result = prime * result + b;
} }
} }
long temp; long temp;
temp = Double.doubleToLongBits(score); temp = Double.doubleToLongBits(score);
result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + (int) (temp ^ (temp >>> 32));
return result; return result;
} }
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) if (this == obj)
return true; return true;
if (obj == null) if (obj == null)
return false; return false;
if (getClass() != obj.getClass()) if (getClass() != obj.getClass())
return false; return false;
Tuple other = (Tuple) obj; Tuple other = (Tuple) obj;
if (element == null) { if (element == null) {
if (other.element != null) if (other.element != null)
return false; return false;
} else if (!Arrays.equals(element, other.element)) } else if (!Arrays.equals(element, other.element))
return false; return false;
return true; return true;
} }
public int compareTo(Tuple other) { public int compareTo(Tuple other) {
if (Arrays.equals(this.element, other.element)) if (Arrays.equals(this.element, other.element))
return 0; return 0;
else else
return this.score < other.getScore() ? -1 : 1; return this.score < other.getScore() ? -1 : 1;
} }
public Tuple(String element, Double score) { public Tuple(String element, Double score) {
super(); super();
this.element = SafeEncoder.encode(element); this.element = SafeEncoder.encode(element);
this.score = score; this.score = score;
} }
public Tuple(byte[] element, Double score) { public Tuple(byte[] element, Double score) {
super(); super();
this.element = element; this.element = element;
this.score = score; this.score = score;
} }
public String getElement() { public String getElement() {
if (null != element) { if (null != element) {
return SafeEncoder.encode(element); return SafeEncoder.encode(element);
} else { } else {
return null; return null;
} }
} }
public byte[] getBinaryElement() { public byte[] getBinaryElement() {
return element; return element;
} }
public double getScore() { public double getScore() {
return score; return score;
} }
public String toString() { public String toString() {
return '[' + Arrays.toString(element) + ',' + score + ']'; return '[' + Arrays.toString(element) + ',' + score + ']';
} }
} }

View File

@@ -12,13 +12,13 @@ import redis.clients.util.SafeEncoder;
public class ZParams { public class ZParams {
public enum Aggregate { public enum Aggregate {
SUM, MIN, MAX; SUM, MIN, MAX;
public final byte[] raw; public final byte[] raw;
Aggregate() { Aggregate() {
raw = SafeEncoder.encode(name()); raw = SafeEncoder.encode(name());
} }
} }
private List<byte[]> params = new ArrayList<byte[]>(); private List<byte[]> params = new ArrayList<byte[]>();
@@ -30,21 +30,21 @@ public class ZParams {
* weights. * weights.
*/ */
public ZParams weights(final double... weights) { public ZParams weights(final double... weights) {
params.add(WEIGHTS.raw); params.add(WEIGHTS.raw);
for (final double weight : weights) { for (final double weight : weights) {
params.add(Protocol.toByteArray(weight)); params.add(Protocol.toByteArray(weight));
} }
return this; return this;
} }
public Collection<byte[]> getParams() { public Collection<byte[]> getParams() {
return Collections.unmodifiableCollection(params); return Collections.unmodifiableCollection(params);
} }
public ZParams aggregate(final Aggregate aggregate) { public ZParams aggregate(final Aggregate aggregate) {
params.add(AGGREGATE.raw); params.add(AGGREGATE.raw);
params.add(aggregate.raw); params.add(aggregate.raw);
return this; return this;
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -6,17 +6,17 @@ 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, public JedisMovedDataException(Throwable cause, HostAndPort targetNode,
int slot) { int slot) {
super(cause, targetNode, slot); super(cause, targetNode, slot);
} }
public JedisMovedDataException(String message, Throwable cause, public JedisMovedDataException(String message, Throwable cause,
HostAndPort targetNode, int slot) { HostAndPort targetNode, int slot) {
super(message, cause, targetNode, slot); super(message, cause, targetNode, slot);
} }
} }

View File

@@ -9,31 +9,31 @@ public class JedisRedirectionException extends JedisDataException {
private int slot; private int slot;
public JedisRedirectionException(String message, HostAndPort targetNode, public JedisRedirectionException(String message, HostAndPort targetNode,
int slot) { int slot) {
super(message); super(message);
this.targetNode = targetNode; this.targetNode = targetNode;
this.slot = slot; this.slot = slot;
} }
public JedisRedirectionException(Throwable cause, HostAndPort targetNode, public JedisRedirectionException(Throwable cause, HostAndPort targetNode,
int slot) { int slot) {
super(cause); super(cause);
this.targetNode = targetNode; this.targetNode = targetNode;
this.slot = slot; this.slot = slot;
} }
public JedisRedirectionException(String message, Throwable cause, public JedisRedirectionException(String message, Throwable cause,
HostAndPort targetNode, int slot) { HostAndPort targetNode, int slot) {
super(message, cause); super(message, cause);
this.targetNode = targetNode; this.targetNode = targetNode;
this.slot = slot; this.slot = slot;
} }
public HostAndPort getTargetNode() { public HostAndPort getTargetNode() {
return targetNode; return targetNode;
} }
public int getSlot() { public int getSlot() {
return slot; return slot;
} }
} }

View File

@@ -12,37 +12,37 @@ public class ClusterNodeInformation {
private List<Integer> slotsBeingMigrated; private List<Integer> slotsBeingMigrated;
public ClusterNodeInformation(HostAndPort node) { public ClusterNodeInformation(HostAndPort node) {
this.node = node; this.node = node;
this.availableSlots = new ArrayList<Integer>(); this.availableSlots = new ArrayList<Integer>();
this.slotsBeingImported = new ArrayList<Integer>(); this.slotsBeingImported = new ArrayList<Integer>();
this.slotsBeingMigrated = new ArrayList<Integer>(); this.slotsBeingMigrated = new ArrayList<Integer>();
} }
public void addAvailableSlot(int slot) { public void addAvailableSlot(int slot) {
availableSlots.add(slot); availableSlots.add(slot);
} }
public void addSlotBeingImported(int slot) { public void addSlotBeingImported(int slot) {
slotsBeingImported.add(slot); slotsBeingImported.add(slot);
} }
public void addSlotBeingMigrated(int slot) { public void addSlotBeingMigrated(int slot) {
slotsBeingMigrated.add(slot); slotsBeingMigrated.add(slot);
} }
public HostAndPort getNode() { public HostAndPort getNode() {
return node; return node;
} }
public List<Integer> getAvailableSlots() { public List<Integer> getAvailableSlots() {
return availableSlots; return availableSlots;
} }
public List<Integer> getSlotsBeingImported() { public List<Integer> getSlotsBeingImported() {
return slotsBeingImported; return slotsBeingImported;
} }
public List<Integer> getSlotsBeingMigrated() { public List<Integer> getSlotsBeingMigrated() {
return slotsBeingMigrated; return slotsBeingMigrated;
} }
} }

View File

@@ -9,72 +9,72 @@ public class ClusterNodeInformationParser {
public static final int HOST_AND_PORT_INDEX = 1; public static final int HOST_AND_PORT_INDEX = 1;
public ClusterNodeInformation parse(String nodeInfo, HostAndPort current) { public ClusterNodeInformation parse(String nodeInfo, HostAndPort current) {
String[] nodeInfoPartArray = nodeInfo.split(" "); String[] nodeInfoPartArray = nodeInfo.split(" ");
HostAndPort node = getHostAndPortFromNodeLine(nodeInfoPartArray, HostAndPort node = getHostAndPortFromNodeLine(nodeInfoPartArray,
current); current);
ClusterNodeInformation info = new ClusterNodeInformation(node); ClusterNodeInformation info = new ClusterNodeInformation(node);
if (nodeInfoPartArray.length >= SLOT_INFORMATIONS_START_INDEX) { if (nodeInfoPartArray.length >= SLOT_INFORMATIONS_START_INDEX) {
String[] slotInfoPartArray = extractSlotParts(nodeInfoPartArray); String[] slotInfoPartArray = extractSlotParts(nodeInfoPartArray);
fillSlotInformation(slotInfoPartArray, info); fillSlotInformation(slotInfoPartArray, info);
} }
return info; return info;
} }
private String[] extractSlotParts(String[] nodeInfoPartArray) { private String[] extractSlotParts(String[] nodeInfoPartArray) {
String[] slotInfoPartArray = new String[nodeInfoPartArray.length String[] slotInfoPartArray = new String[nodeInfoPartArray.length
- SLOT_INFORMATIONS_START_INDEX]; - SLOT_INFORMATIONS_START_INDEX];
for (int i = SLOT_INFORMATIONS_START_INDEX; i < nodeInfoPartArray.length; i++) { for (int i = SLOT_INFORMATIONS_START_INDEX; i < nodeInfoPartArray.length; i++) {
slotInfoPartArray[i - SLOT_INFORMATIONS_START_INDEX] = nodeInfoPartArray[i]; slotInfoPartArray[i - SLOT_INFORMATIONS_START_INDEX] = nodeInfoPartArray[i];
} }
return slotInfoPartArray; return slotInfoPartArray;
} }
public HostAndPort getHostAndPortFromNodeLine(String[] nodeInfoPartArray, public HostAndPort getHostAndPortFromNodeLine(String[] nodeInfoPartArray,
HostAndPort current) { HostAndPort current) {
String stringHostAndPort = nodeInfoPartArray[HOST_AND_PORT_INDEX]; String stringHostAndPort = nodeInfoPartArray[HOST_AND_PORT_INDEX];
String[] arrayHostAndPort = stringHostAndPort.split(":"); String[] arrayHostAndPort = stringHostAndPort.split(":");
return new HostAndPort( return new HostAndPort(
arrayHostAndPort[0].isEmpty() ? current.getHost() arrayHostAndPort[0].isEmpty() ? current.getHost()
: arrayHostAndPort[0], : arrayHostAndPort[0],
arrayHostAndPort[1].isEmpty() ? current.getPort() : Integer arrayHostAndPort[1].isEmpty() ? current.getPort() : Integer
.valueOf(arrayHostAndPort[1])); .valueOf(arrayHostAndPort[1]));
} }
private void fillSlotInformation(String[] slotInfoPartArray, private void fillSlotInformation(String[] slotInfoPartArray,
ClusterNodeInformation info) { ClusterNodeInformation info) {
for (String slotRange : slotInfoPartArray) { for (String slotRange : slotInfoPartArray) {
fillSlotInformationFromSlotRange(slotRange, info); fillSlotInformationFromSlotRange(slotRange, info);
} }
} }
private void fillSlotInformationFromSlotRange(String slotRange, private void fillSlotInformationFromSlotRange(String slotRange,
ClusterNodeInformation info) { ClusterNodeInformation info) {
if (slotRange.startsWith(SLOT_IN_TRANSITION_IDENTIFIER)) { if (slotRange.startsWith(SLOT_IN_TRANSITION_IDENTIFIER)) {
// slot is in transition // slot is in transition
int slot = Integer.parseInt(slotRange.substring(1).split("-")[0]); int slot = Integer.parseInt(slotRange.substring(1).split("-")[0]);
if (slotRange.contains(SLOT_IMPORT_IDENTIFIER)) { if (slotRange.contains(SLOT_IMPORT_IDENTIFIER)) {
// import // import
info.addSlotBeingImported(slot); info.addSlotBeingImported(slot);
} else { } else {
// migrate (->-) // migrate (->-)
info.addSlotBeingMigrated(slot); info.addSlotBeingMigrated(slot);
} }
} else if (slotRange.contains("-")) { } else if (slotRange.contains("-")) {
// slot range // slot range
String[] slotRangePart = slotRange.split("-"); String[] slotRangePart = slotRange.split("-");
for (int slot = Integer.valueOf(slotRangePart[0]); slot <= Integer for (int slot = Integer.valueOf(slotRangePart[0]); slot <= Integer
.valueOf(slotRangePart[1]); slot++) { .valueOf(slotRangePart[1]); slot++) {
info.addAvailableSlot(slot); info.addAvailableSlot(slot);
} }
} else { } else {
// single slot // single slot
info.addAvailableSlot(Integer.valueOf(slotRange)); info.addAvailableSlot(Integer.valueOf(slotRange));
} }
} }
} }

View File

@@ -8,28 +8,28 @@ public interface Hashing {
public ThreadLocal<MessageDigest> md5Holder = new ThreadLocal<MessageDigest>(); public ThreadLocal<MessageDigest> md5Holder = new ThreadLocal<MessageDigest>();
public static final Hashing MD5 = new Hashing() { public static final Hashing MD5 = new Hashing() {
public long hash(String key) { public long hash(String key) {
return hash(SafeEncoder.encode(key)); return hash(SafeEncoder.encode(key));
} }
public long hash(byte[] key) { public long hash(byte[] key) {
try { try {
if (md5Holder.get() == null) { if (md5Holder.get() == null) {
md5Holder.set(MessageDigest.getInstance("MD5")); md5Holder.set(MessageDigest.getInstance("MD5"));
} }
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("++++ no md5 algorythm found"); throw new IllegalStateException("++++ no md5 algorythm found");
} }
MessageDigest md5 = md5Holder.get(); MessageDigest md5 = md5Holder.get();
md5.reset(); md5.reset();
md5.update(key); md5.update(key);
byte[] bKey = md5.digest(); byte[] bKey = md5.digest();
long res = ((long) (bKey[3] & 0xFF) << 24) long res = ((long) (bKey[3] & 0xFF) << 24)
| ((long) (bKey[2] & 0xFF) << 16) | ((long) (bKey[2] & 0xFF) << 16)
| ((long) (bKey[1] & 0xFF) << 8) | (long) (bKey[0] & 0xFF); | ((long) (bKey[1] & 0xFF) << 8) | (long) (bKey[0] & 0xFF);
return res; return res;
} }
}; };
public long hash(String key); public long hash(String key);

View File

@@ -10,127 +10,127 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
public class JedisByteHashMap implements Map<byte[], byte[]>, Cloneable, public class JedisByteHashMap implements Map<byte[], byte[]>, Cloneable,
Serializable { Serializable {
private static final long serialVersionUID = -6971431362627219416L; private static final long serialVersionUID = -6971431362627219416L;
private Map<ByteArrayWrapper, byte[]> internalMap = new HashMap<ByteArrayWrapper, byte[]>(); private Map<ByteArrayWrapper, byte[]> internalMap = new HashMap<ByteArrayWrapper, byte[]>();
public void clear() { public void clear() {
internalMap.clear(); internalMap.clear();
} }
public boolean containsKey(Object key) { public boolean containsKey(Object key) {
if (key instanceof byte[]) if (key instanceof byte[])
return internalMap.containsKey(new ByteArrayWrapper((byte[]) key)); return internalMap.containsKey(new ByteArrayWrapper((byte[]) key));
return internalMap.containsKey(key); return internalMap.containsKey(key);
} }
public boolean containsValue(Object value) { public boolean containsValue(Object value) {
return internalMap.containsValue(value); return internalMap.containsValue(value);
} }
public Set<java.util.Map.Entry<byte[], byte[]>> entrySet() { public Set<java.util.Map.Entry<byte[], byte[]>> entrySet() {
Iterator<java.util.Map.Entry<ByteArrayWrapper, byte[]>> iterator = internalMap Iterator<java.util.Map.Entry<ByteArrayWrapper, byte[]>> iterator = internalMap
.entrySet().iterator(); .entrySet().iterator();
HashSet<Entry<byte[], byte[]>> hashSet = new HashSet<java.util.Map.Entry<byte[], byte[]>>(); HashSet<Entry<byte[], byte[]>> hashSet = new HashSet<java.util.Map.Entry<byte[], byte[]>>();
while (iterator.hasNext()) { while (iterator.hasNext()) {
Entry<ByteArrayWrapper, byte[]> entry = iterator.next(); Entry<ByteArrayWrapper, byte[]> entry = iterator.next();
hashSet.add(new JedisByteEntry(entry.getKey().data, entry hashSet.add(new JedisByteEntry(entry.getKey().data, entry
.getValue())); .getValue()));
} }
return hashSet; return hashSet;
} }
public byte[] get(Object key) { public byte[] get(Object key) {
if (key instanceof byte[]) if (key instanceof byte[])
return internalMap.get(new ByteArrayWrapper((byte[]) key)); return internalMap.get(new ByteArrayWrapper((byte[]) key));
return internalMap.get(key); return internalMap.get(key);
} }
public boolean isEmpty() { public boolean isEmpty() {
return internalMap.isEmpty(); return internalMap.isEmpty();
} }
public Set<byte[]> keySet() { public Set<byte[]> keySet() {
Set<byte[]> keySet = new HashSet<byte[]>(); Set<byte[]> keySet = new HashSet<byte[]>();
Iterator<ByteArrayWrapper> iterator = internalMap.keySet().iterator(); Iterator<ByteArrayWrapper> iterator = internalMap.keySet().iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
keySet.add(iterator.next().data); keySet.add(iterator.next().data);
} }
return keySet; return keySet;
} }
public byte[] put(byte[] key, byte[] value) { public byte[] put(byte[] key, byte[] value) {
return internalMap.put(new ByteArrayWrapper(key), value); return internalMap.put(new ByteArrayWrapper(key), value);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void putAll(Map<? extends byte[], ? extends byte[]> m) { public void putAll(Map<? extends byte[], ? extends byte[]> m) {
Iterator<?> iterator = m.entrySet().iterator(); Iterator<?> iterator = m.entrySet().iterator();
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()), internalMap.put(new ByteArrayWrapper(next.getKey()),
next.getValue()); next.getValue());
} }
} }
public byte[] remove(Object key) { public byte[] remove(Object key) {
if (key instanceof byte[]) if (key instanceof byte[])
return internalMap.remove(new ByteArrayWrapper((byte[]) key)); return internalMap.remove(new ByteArrayWrapper((byte[]) key));
return internalMap.remove(key); return internalMap.remove(key);
} }
public int size() { public int size() {
return internalMap.size(); return internalMap.size();
} }
public Collection<byte[]> values() { public Collection<byte[]> values() {
return internalMap.values(); return internalMap.values();
} }
private static final class ByteArrayWrapper { private static final class ByteArrayWrapper {
private final byte[] data; private final byte[] data;
public ByteArrayWrapper(byte[] data) { public ByteArrayWrapper(byte[] data) {
if (data == null) { if (data == null) {
throw new NullPointerException(); throw new NullPointerException();
} }
this.data = data; this.data = data;
} }
public boolean equals(Object other) { public boolean equals(Object other) {
if (!(other instanceof ByteArrayWrapper)) { if (!(other instanceof ByteArrayWrapper)) {
return false; return false;
} }
return Arrays.equals(data, ((ByteArrayWrapper) other).data); return Arrays.equals(data, ((ByteArrayWrapper) other).data);
} }
public int hashCode() { public int hashCode() {
return Arrays.hashCode(data); return Arrays.hashCode(data);
} }
} }
private static final class JedisByteEntry implements Entry<byte[], byte[]> { private static final class JedisByteEntry implements Entry<byte[], byte[]> {
private byte[] value; private byte[] value;
private byte[] key; private byte[] key;
public JedisByteEntry(byte[] key, byte[] value) { public JedisByteEntry(byte[] key, byte[] value) {
this.key = key; this.key = key;
this.value = value; this.value = value;
} }
public byte[] getKey() { public byte[] getKey() {
return this.key; return this.key;
} }
public byte[] getValue() { public byte[] getValue() {
return this.value; return this.value;
} }
public byte[] setValue(byte[] value) { public byte[] setValue(byte[] value) {
this.value = value; this.value = value;
return value; return value;
} }
} }
} }

View File

@@ -9,50 +9,50 @@ package redis.clients.util;
*/ */
public class JedisClusterCRC16 { public class JedisClusterCRC16 {
private static final int LOOKUP_TABLE[] = { 0x0000, 0x1021, 0x2042, 0x3063, private static final int LOOKUP_TABLE[] = { 0x0000, 0x1021, 0x2042, 0x3063,
0x4084, 0x50A5, 0x60C6, 0x70E7, 0x8108, 0x9129, 0xA14A, 0xB16B, 0x4084, 0x50A5, 0x60C6, 0x70E7, 0x8108, 0x9129, 0xA14A, 0xB16B,
0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, 0x1231, 0x0210, 0x3273, 0x2252, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, 0x1231, 0x0210, 0x3273, 0x2252,
0x52B5, 0x4294, 0x72F7, 0x62D6, 0x9339, 0x8318, 0xB37B, 0xA35A, 0x52B5, 0x4294, 0x72F7, 0x62D6, 0x9339, 0x8318, 0xB37B, 0xA35A,
0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, 0x2462, 0x3443, 0x0420, 0x1401, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, 0x2462, 0x3443, 0x0420, 0x1401,
0x64E6, 0x74C7, 0x44A4, 0x5485, 0xA56A, 0xB54B, 0x8528, 0x9509, 0x64E6, 0x74C7, 0x44A4, 0x5485, 0xA56A, 0xB54B, 0x8528, 0x9509,
0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, 0x3653, 0x2672, 0x1611, 0x0630, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, 0x3653, 0x2672, 0x1611, 0x0630,
0x76D7, 0x66F6, 0x5695, 0x46B4, 0xB75B, 0xA77A, 0x9719, 0x8738, 0x76D7, 0x66F6, 0x5695, 0x46B4, 0xB75B, 0xA77A, 0x9719, 0x8738,
0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, 0x48C4, 0x58E5, 0x6886, 0x78A7, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, 0x48C4, 0x58E5, 0x6886, 0x78A7,
0x0840, 0x1861, 0x2802, 0x3823, 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x0840, 0x1861, 0x2802, 0x3823, 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF,
0x8948, 0x9969, 0xA90A, 0xB92B, 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x8948, 0x9969, 0xA90A, 0xB92B, 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96,
0x1A71, 0x0A50, 0x3A33, 0x2A12, 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x1A71, 0x0A50, 0x3A33, 0x2A12, 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E,
0x9B79, 0x8B58, 0xBB3B, 0xAB1A, 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A, 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5,
0x2C22, 0x3C03, 0x0C60, 0x1C41, 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0x2C22, 0x3C03, 0x0C60, 0x1C41, 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD,
0xAD2A, 0xBD0B, 0x8D68, 0x9D49, 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49, 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4,
0x3E13, 0x2E32, 0x1E51, 0x0E70, 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0x3E13, 0x2E32, 0x1E51, 0x0E70, 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC,
0xBF1B, 0xAF3A, 0x9F59, 0x8F78, 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, 0x9188, 0x81A9, 0xB1CA, 0xA1EB,
0xD10C, 0xC12D, 0xF14E, 0xE16F, 0x1080, 0x00A1, 0x30C2, 0x20E3, 0xD10C, 0xC12D, 0xF14E, 0xE16F, 0x1080, 0x00A1, 0x30C2, 0x20E3,
0x5004, 0x4025, 0x7046, 0x6067, 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0x5004, 0x4025, 0x7046, 0x6067, 0x83B9, 0x9398, 0xA3FB, 0xB3DA,
0xC33D, 0xD31C, 0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2, 0xC33D, 0xD31C, 0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2,
0x4235, 0x5214, 0x6277, 0x7256, 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0x4235, 0x5214, 0x6277, 0x7256, 0xB5EA, 0xA5CB, 0x95A8, 0x8589,
0xF56E, 0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, 0x0481, 0xF56E, 0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, 0x0481,
0x7466, 0x6447, 0x5424, 0x4405, 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0x7466, 0x6447, 0x5424, 0x4405, 0xA7DB, 0xB7FA, 0x8799, 0x97B8,
0xE75F, 0xF77E, 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691, 0x16B0, 0xE75F, 0xF77E, 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691, 0x16B0,
0x6657, 0x7676, 0x4615, 0x5634, 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x6657, 0x7676, 0x4615, 0x5634, 0xD94C, 0xC96D, 0xF90E, 0xE92F,
0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827,
0x18C0, 0x08E1, 0x3882, 0x28A3, 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x18C0, 0x08E1, 0x3882, 0x28A3, 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E,
0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16,
0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D,
0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07, 0x5C64, 0x4C45,
0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C,
0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, 0x6E17, 0x7E36, 0x4E55, 0x5E74,
0x2E93, 0x3EB2, 0x0ED1, 0x1EF0, }; 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0, };
public static int getSlot(String key) { public static int getSlot(String key) {
int s = key.indexOf("{"); int s = key.indexOf("{");
if (s > -1) { if (s > -1) {
int e = key.indexOf("}", s + 1); int e = key.indexOf("}", s + 1);
if (e > -1 && e != s + 1) { if (e > -1 && e != s + 1) {
key = key.substring(s + 1, e); key = key.substring(s + 1, e);
} }
} }
// optimization with modulo operator with power of 2 // optimization with modulo operator with power of 2
// equivalent to getCRC16(key) % 16384 // equivalent to getCRC16(key) % 16384
return getCRC16(key) & (16384 - 1); return getCRC16(key) & (16384 - 1);
} }
/** /**
@@ -64,16 +64,16 @@ public class JedisClusterCRC16 {
* @see https://github.com/xetorthio/jedis/pull/733#issuecomment-55840331 * @see https://github.com/xetorthio/jedis/pull/733#issuecomment-55840331
*/ */
public static int getCRC16(byte[] bytes) { public static int getCRC16(byte[] bytes) {
int crc = 0x0000; int crc = 0x0000;
for (byte b : bytes) { for (byte b : bytes) {
crc = ((crc << 8) ^ LOOKUP_TABLE[((crc >>> 8) ^ (b & 0xFF)) & 0xFF]); crc = ((crc << 8) ^ LOOKUP_TABLE[((crc >>> 8) ^ (b & 0xFF)) & 0xFF]);
} }
return crc & 0xFFFF; return crc & 0xFFFF;
} }
public static int getCRC16(String key) { public static int getCRC16(String key) {
return getCRC16(SafeEncoder.encode(key)); return getCRC16(SafeEncoder.encode(key));
} }
} }

View File

@@ -4,23 +4,23 @@ import java.net.URI;
public class JedisURIHelper { public class JedisURIHelper {
public static String getPassword(URI uri) { public static String getPassword(URI uri) {
String userInfo = uri.getUserInfo(); String userInfo = uri.getUserInfo();
if (userInfo != null) { if (userInfo != null) {
return userInfo.split(":", 2)[1]; return userInfo.split(":", 2)[1];
} }
return null; return null;
} }
public static Integer getDBIndex(URI uri) { public static Integer getDBIndex(URI uri) {
String[] pathSplit = uri.getPath().split("/", 2); String[] pathSplit = uri.getPath().split("/", 2);
if (pathSplit.length > 1) { if (pathSplit.length > 1) {
String dbIndexStr = pathSplit[1]; String dbIndexStr = pathSplit[1];
if (dbIndexStr.isEmpty()) { if (dbIndexStr.isEmpty()) {
return 0; return 0;
} }
return Integer.parseInt(dbIndexStr); return Integer.parseInt(dbIndexStr);
} else { } else {
return 0; return 0;
} }
} }
} }

View File

@@ -40,7 +40,7 @@ public class MurmurHash implements Hashing {
* @return The 32 bit hash of the bytes in question. * @return The 32 bit hash of the bytes in question.
*/ */
public static int hash(byte[] data, int seed) { public static int hash(byte[] data, int seed) {
return hash(ByteBuffer.wrap(data), seed); return hash(ByteBuffer.wrap(data), seed);
} }
/** /**
@@ -57,7 +57,7 @@ public class MurmurHash implements Hashing {
* @return The 32-bit hash of the data in question. * @return The 32-bit hash of the data in question.
*/ */
public static int hash(byte[] data, int offset, int length, int seed) { public static int hash(byte[] data, int offset, int length, int seed) {
return hash(ByteBuffer.wrap(data, offset, length), seed); return hash(ByteBuffer.wrap(data, offset, length), seed);
} }
/** /**
@@ -70,97 +70,97 @@ public class MurmurHash implements Hashing {
* @return The 32 bit murmur hash of the bytes in the buffer. * @return The 32 bit murmur hash of the bytes in the buffer.
*/ */
public static int hash(ByteBuffer buf, int seed) { public static int hash(ByteBuffer buf, int seed) {
// save byte order for later restoration // save byte order for later restoration
ByteOrder byteOrder = buf.order(); ByteOrder byteOrder = buf.order();
buf.order(ByteOrder.LITTLE_ENDIAN); buf.order(ByteOrder.LITTLE_ENDIAN);
int m = 0x5bd1e995; int m = 0x5bd1e995;
int r = 24; int r = 24;
int h = seed ^ buf.remaining(); int h = seed ^ buf.remaining();
int k; int k;
while (buf.remaining() >= 4) { while (buf.remaining() >= 4) {
k = buf.getInt(); k = buf.getInt();
k *= m; k *= m;
k ^= k >>> r; k ^= k >>> r;
k *= m; k *= m;
h *= m; h *= m;
h ^= k; h ^= k;
} }
if (buf.remaining() > 0) { if (buf.remaining() > 0) {
ByteBuffer finish = ByteBuffer.allocate(4).order( ByteBuffer finish = ByteBuffer.allocate(4).order(
ByteOrder.LITTLE_ENDIAN); ByteOrder.LITTLE_ENDIAN);
// for big-endian version, use this first: // for big-endian version, use this first:
// finish.position(4-buf.remaining()); // finish.position(4-buf.remaining());
finish.put(buf).rewind(); finish.put(buf).rewind();
h ^= finish.getInt(); h ^= finish.getInt();
h *= m; h *= m;
} }
h ^= h >>> 13; h ^= h >>> 13;
h *= m; h *= m;
h ^= h >>> 15; h ^= h >>> 15;
buf.order(byteOrder); buf.order(byteOrder);
return h; return h;
} }
public static long hash64A(byte[] data, int seed) { public static long hash64A(byte[] data, int seed) {
return hash64A(ByteBuffer.wrap(data), seed); return hash64A(ByteBuffer.wrap(data), seed);
} }
public static long hash64A(byte[] data, int offset, int length, int seed) { public static long hash64A(byte[] data, int offset, int length, int seed) {
return hash64A(ByteBuffer.wrap(data, offset, length), seed); return hash64A(ByteBuffer.wrap(data, offset, length), seed);
} }
public static long hash64A(ByteBuffer buf, int seed) { public static long hash64A(ByteBuffer buf, int seed) {
ByteOrder byteOrder = buf.order(); ByteOrder byteOrder = buf.order();
buf.order(ByteOrder.LITTLE_ENDIAN); buf.order(ByteOrder.LITTLE_ENDIAN);
long m = 0xc6a4a7935bd1e995L; long m = 0xc6a4a7935bd1e995L;
int r = 47; int r = 47;
long h = seed ^ (buf.remaining() * m); long h = seed ^ (buf.remaining() * m);
long k; long k;
while (buf.remaining() >= 8) { while (buf.remaining() >= 8) {
k = buf.getLong(); k = buf.getLong();
k *= m; k *= m;
k ^= k >>> r; k ^= k >>> r;
k *= m; k *= m;
h ^= k; h ^= k;
h *= m; h *= m;
} }
if (buf.remaining() > 0) { if (buf.remaining() > 0) {
ByteBuffer finish = ByteBuffer.allocate(8).order( ByteBuffer finish = ByteBuffer.allocate(8).order(
ByteOrder.LITTLE_ENDIAN); ByteOrder.LITTLE_ENDIAN);
// for big-endian version, do this first: // for big-endian version, do this first:
// finish.position(8-buf.remaining()); // finish.position(8-buf.remaining());
finish.put(buf).rewind(); finish.put(buf).rewind();
h ^= finish.getLong(); h ^= finish.getLong();
h *= m; h *= m;
} }
h ^= h >>> r; h ^= h >>> r;
h *= m; h *= m;
h ^= h >>> r; h ^= h >>> r;
buf.order(byteOrder); buf.order(byteOrder);
return h; return h;
} }
public long hash(byte[] key) { public long hash(byte[] key) {
return hash64A(key, 0x1234ABCD); return hash64A(key, 0x1234ABCD);
} }
public long hash(String key) { public long hash(String key) {
return hash(SafeEncoder.encode(key)); return hash(SafeEncoder.encode(key));
} }
} }

View File

@@ -21,82 +21,82 @@ public abstract class Pool<T> implements Closeable {
@Override @Override
public void close() { public void close() {
closeInternalPool(); closeInternalPool();
} }
public boolean isClosed() { public boolean isClosed() {
return this.internalPool.isClosed(); return this.internalPool.isClosed();
} }
public Pool(final GenericObjectPoolConfig poolConfig, public Pool(final GenericObjectPoolConfig poolConfig,
PooledObjectFactory<T> factory) { PooledObjectFactory<T> factory) {
initPool(poolConfig, factory); initPool(poolConfig, factory);
} }
public void initPool(final GenericObjectPoolConfig poolConfig, public void initPool(final GenericObjectPoolConfig poolConfig,
PooledObjectFactory<T> factory) { PooledObjectFactory<T> factory) {
if (this.internalPool != null) { if (this.internalPool != null) {
try { try {
closeInternalPool(); closeInternalPool();
} catch (Exception e) { } catch (Exception e) {
} }
} }
this.internalPool = new GenericObjectPool<T>(factory, poolConfig); this.internalPool = new GenericObjectPool<T>(factory, poolConfig);
} }
public T getResource() { public T getResource() {
try { try {
return internalPool.borrowObject(); return internalPool.borrowObject();
} catch (Exception e) { } catch (Exception e) {
throw new JedisConnectionException( throw new JedisConnectionException(
"Could not get a resource from the pool", e); "Could not get a resource from the pool", e);
} }
} }
public void returnResourceObject(final T resource) { public void returnResourceObject(final T resource) {
if (resource == null) { if (resource == null) {
return; return;
} }
try { try {
internalPool.returnObject(resource); internalPool.returnObject(resource);
} catch (Exception e) { } catch (Exception e) {
throw new JedisException( throw new JedisException(
"Could not return the resource to the pool", e); "Could not return the resource to the pool", e);
} }
} }
public void returnBrokenResource(final T resource) { public void returnBrokenResource(final T resource) {
if (resource != null) { if (resource != null) {
returnBrokenResourceObject(resource); returnBrokenResourceObject(resource);
} }
} }
public void returnResource(final T resource) { public void returnResource(final T resource) {
if (resource != null) { if (resource != null) {
returnResourceObject(resource); returnResourceObject(resource);
} }
} }
public void destroy() { public void destroy() {
closeInternalPool(); closeInternalPool();
} }
protected void returnBrokenResourceObject(final T resource) { protected void returnBrokenResourceObject(final T resource) {
try { try {
internalPool.invalidateObject(resource); internalPool.invalidateObject(resource);
} catch (Exception e) { } catch (Exception e) {
throw new JedisException( throw new JedisException(
"Could not return the resource to the pool", e); "Could not return the resource to the pool", e);
} }
} }
protected void closeInternalPool() { protected void closeInternalPool() {
try { try {
internalPool.close(); internalPool.close();
} catch (Exception e) { } catch (Exception e) {
throw new JedisException("Could not destroy the pool", e); throw new JedisException("Could not destroy the pool", e);
} }
} }
} }

View File

@@ -32,83 +32,83 @@ public class RedisInputStream extends FilterInputStream {
protected int count, limit; protected int count, limit;
public RedisInputStream(InputStream in, int size) { public RedisInputStream(InputStream in, int size) {
super(in); super(in);
if (size <= 0) { if (size <= 0) {
throw new IllegalArgumentException("Buffer size <= 0"); throw new IllegalArgumentException("Buffer size <= 0");
} }
buf = new byte[size]; buf = new byte[size];
} }
public RedisInputStream(InputStream in) { public RedisInputStream(InputStream in) {
this(in, 8192); this(in, 8192);
} }
public byte readByte() throws JedisConnectionException { public byte readByte() throws JedisConnectionException {
ensureFill(); ensureFill();
return buf[count++]; return buf[count++];
} }
public String readLine() { public String readLine() {
final StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
while (true) { while (true) {
ensureFill(); ensureFill();
byte b = buf[count++]; byte b = buf[count++];
if (b == '\r') { if (b == '\r') {
ensureFill(); // Must be one more byte ensureFill(); // Must be one more byte
byte c = buf[count++]; byte c = buf[count++];
if (c == '\n') { if (c == '\n') {
break; break;
} }
sb.append((char) b); sb.append((char) b);
sb.append((char) c); sb.append((char) c);
} else { } else {
sb.append((char) b); sb.append((char) b);
} }
} }
final String reply = sb.toString(); final String reply = sb.toString();
if (reply.length() == 0) { if (reply.length() == 0) {
throw new JedisConnectionException("It seems like server has closed the connection."); throw new JedisConnectionException("It seems like server has closed the connection.");
} }
return reply; return reply;
} }
public byte[] readLineBytes() { public byte[] readLineBytes() {
/* This operation should only require one fill. In that typical /* This operation should only require one fill. In that typical
case we optimize allocation and copy of the byte array. In the case we optimize allocation and copy of the byte array. In the
edge case where more than one fill is required then we take a edge case where more than one fill is required then we take a
slower path and expand a byte array output stream as is slower path and expand a byte array output stream as is
necessary. */ necessary. */
ensureFill(); ensureFill();
int pos = count; int pos = count;
final byte[] buf = this.buf; final byte[] buf = this.buf;
while (true) { while (true) {
if (pos == limit) { if (pos == limit) {
return readLineBytesSlowly(); return readLineBytesSlowly();
} }
if (buf[pos++] == '\r') { if (buf[pos++] == '\r') {
if (pos == limit) { if (pos == limit) {
return readLineBytesSlowly(); return readLineBytesSlowly();
} }
if (buf[pos++] == '\n') { if (buf[pos++] == '\n') {
break; break;
} }
} }
} }
final int N = (pos - count) - 2; final int N = (pos - count) - 2;
final byte[] line = new byte[N]; final byte[] line = new byte[N];
System.arraycopy(buf, count, line, 0, N); System.arraycopy(buf, count, line, 0, N);
count = pos; count = pos;
return line; return line;
} }
/** /**
@@ -117,80 +117,80 @@ public class RedisInputStream extends FilterInputStream {
* into a String. * into a String.
*/ */
private byte[] readLineBytesSlowly() { private byte[] readLineBytesSlowly() {
ByteArrayOutputStream bout = null; ByteArrayOutputStream bout = null;
while (true) { while (true) {
ensureFill(); ensureFill();
byte b = buf[count++]; byte b = buf[count++];
if (b == '\r') { if (b == '\r') {
ensureFill(); // Must be one more byte ensureFill(); // Must be one more byte
byte c = buf[count++]; byte c = buf[count++];
if (c == '\n') { if (c == '\n') {
break; break;
} }
if (bout == null) { if (bout == null) {
bout = new ByteArrayOutputStream(16); bout = new ByteArrayOutputStream(16);
} }
bout.write(b); bout.write(b);
bout.write(c); bout.write(c);
} else { } else {
if (bout == null) { if (bout == null) {
bout = new ByteArrayOutputStream(16); bout = new ByteArrayOutputStream(16);
} }
bout.write(b); bout.write(b);
} }
} }
return bout == null ? new byte[0] : bout.toByteArray(); return bout == null ? new byte[0] : bout.toByteArray();
} }
public int readIntCrLf() { public int readIntCrLf() {
return (int)readLongCrLf(); return (int)readLongCrLf();
} }
public long readLongCrLf() { public long readLongCrLf() {
final byte[] buf = this.buf; final byte[] buf = this.buf;
ensureFill(); ensureFill();
final boolean isNeg = buf[count] == '-'; final boolean isNeg = buf[count] == '-';
if (isNeg) { if (isNeg) {
++count; ++count;
} }
long value = 0; long value = 0;
while (true) { while (true) {
ensureFill(); ensureFill();
final int b = buf[count++]; final int b = buf[count++];
if (b == '\r') { if (b == '\r') {
ensureFill(); ensureFill();
if (buf[count++] != '\n') { if (buf[count++] != '\n') {
throw new JedisConnectionException("Unexpected character!"); throw new JedisConnectionException("Unexpected character!");
} }
break; break;
} }
else { else {
value = value * 10 + b - '0'; value = value * 10 + b - '0';
} }
} }
return (isNeg ? -value : value); return (isNeg ? -value : value);
} }
public int read(byte[] b, int off, int len) throws JedisConnectionException { public int read(byte[] b, int off, int len) throws JedisConnectionException {
ensureFill(); ensureFill();
final int length = Math.min(limit - count, len); final int length = Math.min(limit - count, len);
System.arraycopy(buf, count, b, off, length); System.arraycopy(buf, count, b, off, length);
count += length; count += length;
return length; return length;
} }
/** /**
@@ -199,16 +199,16 @@ public class RedisInputStream extends FilterInputStream {
* was smaller than expected. * was smaller than expected.
*/ */
private void ensureFill() throws JedisConnectionException { private void ensureFill() throws JedisConnectionException {
if (count >= limit) { if (count >= limit) {
try { try {
limit = in.read(buf); limit = in.read(buf);
count = 0; count = 0;
if (limit == -1) { if (limit == -1) {
throw new JedisConnectionException("Unexpected end of stream."); throw new JedisConnectionException("Unexpected end of stream.");
} }
} catch (IOException e) { } catch (IOException e) {
throw new JedisConnectionException(e); throw new JedisConnectionException(e);
} }
} }
} }
} }

View File

@@ -15,212 +15,212 @@ public final class RedisOutputStream extends FilterOutputStream {
protected int count; protected int count;
public RedisOutputStream(final OutputStream out) { public RedisOutputStream(final OutputStream out) {
this(out, 8192); this(out, 8192);
} }
public RedisOutputStream(final OutputStream out, final int size) { public RedisOutputStream(final OutputStream out, final int size) {
super(out); super(out);
if (size <= 0) { if (size <= 0) {
throw new IllegalArgumentException("Buffer size <= 0"); throw new IllegalArgumentException("Buffer size <= 0");
} }
buf = new byte[size]; buf = new byte[size];
} }
private void flushBuffer() throws IOException { private void flushBuffer() throws IOException {
if (count > 0) { if (count > 0) {
out.write(buf, 0, count); out.write(buf, 0, count);
count = 0; count = 0;
} }
} }
public void write(final byte b) throws IOException { public void write(final byte b) throws IOException {
if (count == buf.length) { if (count == buf.length) {
flushBuffer(); flushBuffer();
} }
buf[count++] = b; buf[count++] = b;
} }
public void write(final byte[] b) throws IOException { public void write(final byte[] b) throws IOException {
write(b, 0, b.length); write(b, 0, b.length);
} }
public void write(final byte b[], final int off, final int len) public void write(final byte b[], final int off, final int len)
throws IOException { throws IOException {
if (len >= buf.length) { if (len >= buf.length) {
flushBuffer(); flushBuffer();
out.write(b, off, len); out.write(b, off, len);
} else { } else {
if (len >= buf.length - count) { if (len >= buf.length - count) {
flushBuffer(); flushBuffer();
} }
System.arraycopy(b, off, buf, count, len); System.arraycopy(b, off, buf, count, len);
count += len; count += len;
} }
} }
public void writeAsciiCrLf(final String in) throws IOException { public void writeAsciiCrLf(final String in) throws IOException {
final int size = in.length(); final int size = in.length();
for (int i = 0; i != size; ++i) { for (int i = 0; i != size; ++i) {
if (count == buf.length) { if (count == buf.length) {
flushBuffer(); flushBuffer();
} }
buf[count++] = (byte) in.charAt(i); buf[count++] = (byte) in.charAt(i);
} }
writeCrLf(); writeCrLf();
} }
public static boolean isSurrogate(final char ch) { public static boolean isSurrogate(final char ch) {
return ch >= Character.MIN_SURROGATE && ch <= Character.MAX_SURROGATE; return ch >= Character.MIN_SURROGATE && ch <= Character.MAX_SURROGATE;
} }
public static int utf8Length(final String str) { public static int utf8Length(final String str) {
int strLen = str.length(), utfLen = 0; int strLen = str.length(), utfLen = 0;
for (int i = 0; i != strLen; ++i) { for (int i = 0; i != strLen; ++i) {
char c = str.charAt(i); char c = str.charAt(i);
if (c < 0x80) { if (c < 0x80) {
utfLen++; utfLen++;
} else if (c < 0x800) { } else if (c < 0x800) {
utfLen += 2; utfLen += 2;
} else if (isSurrogate(c)) { } else if (isSurrogate(c)) {
i++; i++;
utfLen += 4; utfLen += 4;
} else { } else {
utfLen += 3; utfLen += 3;
} }
} }
return utfLen; return utfLen;
} }
public void writeCrLf() throws IOException { public void writeCrLf() throws IOException {
if (2 >= buf.length - count) { if (2 >= buf.length - count) {
flushBuffer(); flushBuffer();
} }
buf[count++] = '\r'; buf[count++] = '\r';
buf[count++] = '\n'; buf[count++] = '\n';
} }
public void writeUtf8CrLf(final String str) throws IOException { public void writeUtf8CrLf(final String str) throws IOException {
int strLen = str.length(); int strLen = str.length();
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)) if (!(c < 0x80))
break; break;
if (count == buf.length) { if (count == buf.length) {
flushBuffer(); flushBuffer();
} }
buf[count++] = (byte) c; buf[count++] = (byte) c;
} }
for (; i < strLen; i++) { for (; i < strLen; i++) {
char c = str.charAt(i); char c = str.charAt(i);
if (c < 0x80) { if (c < 0x80) {
if (count == buf.length) { if (count == buf.length) {
flushBuffer(); flushBuffer();
} }
buf[count++] = (byte) c; buf[count++] = (byte) c;
} else if (c < 0x800) { } else if (c < 0x800) {
if (2 >= buf.length - count) { if (2 >= buf.length - count) {
flushBuffer(); flushBuffer();
} }
buf[count++] = (byte) (0xc0 | (c >> 6)); buf[count++] = (byte) (0xc0 | (c >> 6));
buf[count++] = (byte) (0x80 | (c & 0x3f)); buf[count++] = (byte) (0x80 | (c & 0x3f));
} else if (isSurrogate(c)) { } else if (isSurrogate(c)) {
if (4 >= buf.length - count) { if (4 >= buf.length - count) {
flushBuffer(); flushBuffer();
} }
int uc = Character.toCodePoint(c, str.charAt(i++)); int uc = Character.toCodePoint(c, str.charAt(i++));
buf[count++] = ((byte) (0xf0 | ((uc >> 18)))); buf[count++] = ((byte) (0xf0 | ((uc >> 18))));
buf[count++] = ((byte) (0x80 | ((uc >> 12) & 0x3f))); buf[count++] = ((byte) (0x80 | ((uc >> 12) & 0x3f)));
buf[count++] = ((byte) (0x80 | ((uc >> 6) & 0x3f))); buf[count++] = ((byte) (0x80 | ((uc >> 6) & 0x3f)));
buf[count++] = ((byte) (0x80 | (uc & 0x3f))); buf[count++] = ((byte) (0x80 | (uc & 0x3f)));
} else { } else {
if (3 >= buf.length - count) { if (3 >= buf.length - count) {
flushBuffer(); flushBuffer();
} }
buf[count++] = ((byte) (0xe0 | ((c >> 12)))); buf[count++] = ((byte) (0xe0 | ((c >> 12))));
buf[count++] = ((byte) (0x80 | ((c >> 6) & 0x3f))); buf[count++] = ((byte) (0x80 | ((c >> 6) & 0x3f)));
buf[count++] = ((byte) (0x80 | (c & 0x3f))); buf[count++] = ((byte) (0x80 | (c & 0x3f)));
} }
} }
writeCrLf(); writeCrLf();
} }
private final static int[] sizeTable = { 9, 99, 999, 9999, 99999, 999999, private final static int[] sizeTable = { 9, 99, 999, 9999, 99999, 999999,
9999999, 99999999, 999999999, Integer.MAX_VALUE }; 9999999, 99999999, 999999999, Integer.MAX_VALUE };
private final static byte[] DigitTens = { '0', '0', '0', '0', '0', '0', private final static byte[] DigitTens = { '0', '0', '0', '0', '0', '0',
'0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1',
'1', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '3', '3', '1', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '3', '3',
'3', '3', '3', '3', '3', '3', '3', '3', '4', '4', '4', '4', '4', '3', '3', '3', '3', '3', '3', '3', '3', '4', '4', '4', '4', '4',
'4', '4', '4', '4', '4', '5', '5', '5', '5', '5', '5', '5', '5', '4', '4', '4', '4', '4', '5', '5', '5', '5', '5', '5', '5', '5',
'5', '5', '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', '7', '5', '5', '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', '7',
'7', '7', '7', '7', '7', '7', '7', '7', '7', '8', '8', '8', '8', '7', '7', '7', '7', '7', '7', '7', '7', '7', '8', '8', '8', '8',
'8', '8', '8', '8', '8', '8', '9', '9', '9', '9', '9', '9', '9', '8', '8', '8', '8', '8', '8', '9', '9', '9', '9', '9', '9', '9',
'9', '9', '9', }; '9', '9', '9', };
private final static byte[] DigitOnes = { '0', '1', '2', '3', '4', '5', private final static byte[] DigitOnes = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1',
'2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4',
'5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', }; '7', '8', '9', };
private final static byte[] digits = { '0', '1', '2', '3', '4', '5', '6', private final static byte[] digits = { '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z' }; 'x', 'y', 'z' };
public void writeIntCrLf(int value) throws IOException { public void writeIntCrLf(int value) throws IOException {
if (value < 0) { if (value < 0) {
write((byte) '-'); write((byte) '-');
value = -value; value = -value;
} }
int size = 0; int size = 0;
while (value > sizeTable[size]) while (value > sizeTable[size])
size++; size++;
size++; size++;
if (size >= buf.length - count) { if (size >= buf.length - count) {
flushBuffer(); flushBuffer();
} }
int q, r; int q, r;
int charPos = count + size; int charPos = count + size;
while (value >= 65536) { while (value >= 65536) {
q = value / 100; q = value / 100;
r = value - ((q << 6) + (q << 5) + (q << 2)); r = value - ((q << 6) + (q << 5) + (q << 2));
value = q; value = q;
buf[--charPos] = DigitOnes[r]; buf[--charPos] = DigitOnes[r];
buf[--charPos] = DigitTens[r]; buf[--charPos] = DigitTens[r];
} }
for (;;) { for (;;) {
q = (value * 52429) >>> (16 + 3); q = (value * 52429) >>> (16 + 3);
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) if (value == 0)
break; break;
} }
count += size; count += size;
writeCrLf(); writeCrLf();
} }
public void flush() throws IOException { public void flush() throws IOException {
flushBuffer(); flushBuffer();
out.flush(); out.flush();
} }
} }

View File

@@ -12,30 +12,30 @@ import redis.clients.jedis.exceptions.JedisException;
*/ */
public class SafeEncoder { public class SafeEncoder {
public static byte[][] encodeMany(final String... strs) { public static byte[][] encodeMany(final String... strs) {
byte[][] many = new byte[strs.length][]; byte[][] many = new byte[strs.length][];
for (int i = 0; i < strs.length; i++) { for (int i = 0; i < strs.length; i++) {
many[i] = encode(strs[i]); many[i] = encode(strs[i]);
} }
return many; return many;
} }
public static byte[] encode(final String str) { public static byte[] encode(final String str) {
try { try {
if (str == null) { if (str == null) {
throw new JedisDataException( throw new JedisDataException(
"value sent to redis cannot be null"); "value sent to redis cannot be null");
} }
return str.getBytes(Protocol.CHARSET); return str.getBytes(Protocol.CHARSET);
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
throw new JedisException(e); throw new JedisException(e);
} }
} }
public static String encode(final byte[] data) { public static String encode(final byte[] data) {
try { try {
return new String(data, Protocol.CHARSET); return new String(data, Protocol.CHARSET);
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
throw new JedisException(e); throw new JedisException(e);
} }
} }
} }

View File

@@ -7,11 +7,11 @@ public abstract class ShardInfo<T> {
} }
public ShardInfo(int weight) { public ShardInfo(int weight) {
this.weight = weight; this.weight = weight;
} }
public int getWeight() { public int getWeight() {
return this.weight; return this.weight;
} }
protected abstract T createResource(); protected abstract T createResource();

View File

@@ -26,68 +26,68 @@ public class Sharded<R, S extends ShardInfo<R>> {
private Pattern tagPattern = null; private Pattern tagPattern = null;
// the tag is anything between {} // the tag is anything between {}
public static final Pattern DEFAULT_KEY_TAG_PATTERN = Pattern public static final Pattern DEFAULT_KEY_TAG_PATTERN = Pattern
.compile("\\{(.+?)\\}"); .compile("\\{(.+?)\\}");
public Sharded(List<S> shards) { public Sharded(List<S> shards) {
this(shards, Hashing.MURMUR_HASH); // MD5 is really not good as we works this(shards, Hashing.MURMUR_HASH); // MD5 is really not good as we works
// with 64-bits not 128 // with 64-bits not 128
} }
public Sharded(List<S> shards, Hashing algo) { public Sharded(List<S> shards, Hashing algo) {
this.algo = algo; this.algo = algo;
initialize(shards); initialize(shards);
} }
public Sharded(List<S> shards, Pattern tagPattern) { public Sharded(List<S> shards, Pattern tagPattern) {
this(shards, Hashing.MURMUR_HASH, tagPattern); // MD5 is really not good this(shards, Hashing.MURMUR_HASH, tagPattern); // MD5 is really not good
// as we works with // as we works with
// 64-bits not 128 // 64-bits not 128
} }
public Sharded(List<S> shards, Hashing algo, Pattern tagPattern) { public Sharded(List<S> shards, Hashing algo, Pattern tagPattern) {
this.algo = algo; this.algo = algo;
this.tagPattern = tagPattern; this.tagPattern = tagPattern;
initialize(shards); initialize(shards);
} }
private void initialize(List<S> shards) { private void initialize(List<S> shards) {
nodes = new TreeMap<Long, S>(); nodes = new TreeMap<Long, S>();
for (int i = 0; i != shards.size(); ++i) { for (int i = 0; i != shards.size(); ++i) {
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), nodes.put(this.algo.hash("SHARD-" + i + "-NODE-" + n),
shardInfo); shardInfo);
} }
else else
for (int n = 0; n < 160 * shardInfo.getWeight(); n++) { for (int n = 0; n < 160 * shardInfo.getWeight(); n++) {
nodes.put( nodes.put(
this.algo.hash(shardInfo.getName() + "*" this.algo.hash(shardInfo.getName() + "*"
+ shardInfo.getWeight() + n), shardInfo); + shardInfo.getWeight() + n), shardInfo);
} }
resources.put(shardInfo, shardInfo.createResource()); resources.put(shardInfo, shardInfo.createResource());
} }
} }
public R getShard(byte[] key) { public R getShard(byte[] key) {
return resources.get(getShardInfo(key)); return resources.get(getShardInfo(key));
} }
public R getShard(String key) { public R getShard(String key) {
return resources.get(getShardInfo(key)); return resources.get(getShardInfo(key));
} }
public S getShardInfo(byte[] key) { public S getShardInfo(byte[] key) {
SortedMap<Long, S> tail = nodes.tailMap(algo.hash(key)); SortedMap<Long, S> tail = nodes.tailMap(algo.hash(key));
if (tail.isEmpty()) { if (tail.isEmpty()) {
return nodes.get(nodes.firstKey()); return nodes.get(nodes.firstKey());
} }
return tail.get(tail.firstKey()); return tail.get(tail.firstKey());
} }
public S getShardInfo(String key) { public S getShardInfo(String key) {
return getShardInfo(SafeEncoder.encode(getKeyTag(key))); return getShardInfo(SafeEncoder.encode(getKeyTag(key)));
} }
/** /**
@@ -100,19 +100,19 @@ public class Sharded<R, S extends ShardInfo<R>> {
* @return The tag if it exists, or the original key * @return The tag if it exists, or the original key
*/ */
public String getKeyTag(String key) { public String getKeyTag(String key) {
if (tagPattern != null) { if (tagPattern != null) {
Matcher m = tagPattern.matcher(key); Matcher m = tagPattern.matcher(key);
if (m.find()) if (m.find())
return m.group(1); return m.group(1);
} }
return key; return key;
} }
public Collection<S> getAllShardInfo() { public Collection<S> getAllShardInfo() {
return Collections.unmodifiableCollection(nodes.values()); return Collections.unmodifiableCollection(nodes.values());
} }
public Collection<R> getAllShards() { public Collection<R> getAllShards() {
return Collections.unmodifiableCollection(resources.values()); return Collections.unmodifiableCollection(resources.values());
} }
} }

View File

@@ -11,43 +11,43 @@ public class Slowlog {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static List<Slowlog> from(List<Object> nestedMultiBulkReply) { public static List<Slowlog> from(List<Object> nestedMultiBulkReply) {
List<Slowlog> logs = new ArrayList<Slowlog>(nestedMultiBulkReply.size()); List<Slowlog> logs = new ArrayList<Slowlog>(nestedMultiBulkReply.size());
for (Object obj : nestedMultiBulkReply) { for (Object obj : nestedMultiBulkReply) {
List<Object> properties = (List<Object>) obj; List<Object> properties = (List<Object>) obj;
logs.add(new Slowlog(properties)); logs.add(new Slowlog(properties));
} }
return logs; return logs;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private Slowlog(List<Object> properties) { private Slowlog(List<Object> properties) {
super(); super();
this.id = (Long) properties.get(0); this.id = (Long) properties.get(0);
this.timeStamp = (Long) properties.get(1); this.timeStamp = (Long) properties.get(1);
this.executionTime = (Long) properties.get(2); this.executionTime = (Long) properties.get(2);
List<byte[]> bargs = (List<byte[]>) properties.get(3); List<byte[]> bargs = (List<byte[]>) properties.get(3);
this.args = new ArrayList<String>(bargs.size()); this.args = new ArrayList<String>(bargs.size());
for (byte[] barg : bargs) { for (byte[] barg : bargs) {
this.args.add(SafeEncoder.encode(barg)); this.args.add(SafeEncoder.encode(barg));
} }
} }
public long getId() { public long getId() {
return id; return id;
} }
public long getTimeStamp() { public long getTimeStamp() {
return timeStamp; return timeStamp;
} }
public long getExecutionTime() { public long getExecutionTime() {
return executionTime; return executionTime;
} }
public List<String> getArgs() { public List<String> getArgs() {
return args; return args;
} }
} }

View File

@@ -8,7 +8,7 @@ import redis.clients.jedis.BuilderFactory;
public class BuilderFactoryTest extends Assert { public class BuilderFactoryTest extends Assert {
@Test @Test
public void buildDouble() { public void buildDouble() {
Double build = BuilderFactory.DOUBLE.build("1.0".getBytes()); Double build = BuilderFactory.DOUBLE.build("1.0".getBytes());
assertEquals(new Double(1.0), build); assertEquals(new Double(1.0), build);
} }
} }

View File

@@ -14,31 +14,31 @@ public class ConnectionCloseTest extends Assert {
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
client = new Connection(); client = new Connection();
} }
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
client.close(); client.close();
} }
@Test(expected = JedisConnectionException.class) @Test(expected = JedisConnectionException.class)
public void checkUnkownHost() { public void checkUnkownHost() {
client.setHost("someunknownhost"); client.setHost("someunknownhost");
client.connect(); client.connect();
} }
@Test(expected = JedisConnectionException.class) @Test(expected = JedisConnectionException.class)
public void checkWrongPort() { public void checkWrongPort() {
client.setHost("localhost"); client.setHost("localhost");
client.setPort(55665); client.setPort(55665);
client.connect(); client.connect();
} }
@Test @Test
public void connectIfNotConnectedWhenSettingTimeoutInfinite() { public void connectIfNotConnectedWhenSettingTimeoutInfinite() {
client.setHost("localhost"); client.setHost("localhost");
client.setPort(6379); client.setPort(6379);
client.setTimeoutInfinite(); client.setTimeoutInfinite();
} }
} }

View File

@@ -13,39 +13,39 @@ public class ConnectionTest extends Assert {
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
client = new Connection(); client = new Connection();
} }
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
client.disconnect(); client.disconnect();
} }
@Test(expected = JedisConnectionException.class) @Test(expected = JedisConnectionException.class)
public void checkUnkownHost() { public void checkUnkownHost() {
client.setHost("someunknownhost"); client.setHost("someunknownhost");
client.connect(); client.connect();
} }
@Test(expected = JedisConnectionException.class) @Test(expected = JedisConnectionException.class)
public void checkWrongPort() { public void checkWrongPort() {
client.setHost("localhost"); client.setHost("localhost");
client.setPort(55665); client.setPort(55665);
client.connect(); client.connect();
} }
@Test @Test
public void connectIfNotConnectedWhenSettingTimeoutInfinite() { public void connectIfNotConnectedWhenSettingTimeoutInfinite() {
client.setHost("localhost"); client.setHost("localhost");
client.setPort(6379); client.setPort(6379);
client.setTimeoutInfinite(); client.setTimeoutInfinite();
} }
@Test @Test
public void checkCloseable() { public void checkCloseable() {
client.setHost("localhost"); client.setHost("localhost");
client.setPort(6379); client.setPort(6379);
client.connect(); client.connect();
client.close(); client.close();
} }
} }

View File

@@ -9,22 +9,22 @@ public class FragmentedByteArrayInputStream extends ByteArrayInputStream {
private int readMethodCallCount = 0; private int readMethodCallCount = 0;
public FragmentedByteArrayInputStream(final byte[] buf) { public FragmentedByteArrayInputStream(final byte[] buf) {
super(buf); super(buf);
} }
public synchronized int read(final byte[] b, final int off, final int len) { public synchronized int read(final byte[] b, final int off, final int len) {
readMethodCallCount++; readMethodCallCount++;
if (len <= 10) { if (len <= 10) {
// if the len <= 10, return as usual .. // if the len <= 10, return as usual ..
return super.read(b, off, len); return super.read(b, off, len);
} else { } else {
// else return the first half .. // else return the first half ..
return super.read(b, off, len / 2); return super.read(b, off, len / 2);
} }
} }
public int getReadMethodCallCount() { public int getReadMethodCallCount() {
return readMethodCallCount; return readMethodCallCount;
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -27,453 +27,453 @@ public class PipeliningTest extends Assert {
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
jedis = new Jedis(hnp.getHost(), hnp.getPort(), 500); jedis = new Jedis(hnp.getHost(), hnp.getPort(), 500);
jedis.connect(); jedis.connect();
jedis.auth("foobared"); jedis.auth("foobared");
jedis.flushAll(); jedis.flushAll();
} }
@Test @Test
public void pipeline() throws UnsupportedEncodingException { public void pipeline() throws UnsupportedEncodingException {
Pipeline p = jedis.pipelined(); Pipeline p = jedis.pipelined();
p.set("foo", "bar"); p.set("foo", "bar");
p.get("foo"); p.get("foo");
List<Object> results = p.syncAndReturnAll(); List<Object> results = p.syncAndReturnAll();
assertEquals(2, results.size()); assertEquals(2, results.size());
assertEquals("OK", results.get(0)); assertEquals("OK", results.get(0));
assertEquals("bar", results.get(1)); assertEquals("bar", results.get(1));
} }
@Test @Test
public void pipelineResponse() { public void pipelineResponse() {
jedis.set("string", "foo"); jedis.set("string", "foo");
jedis.lpush("list", "foo"); jedis.lpush("list", "foo");
jedis.hset("hash", "foo", "bar"); jedis.hset("hash", "foo", "bar");
jedis.zadd("zset", 1, "foo"); jedis.zadd("zset", 1, "foo");
jedis.sadd("set", "foo"); jedis.sadd("set", "foo");
jedis.setrange("setrange", 0, "0123456789"); jedis.setrange("setrange", 0, "0123456789");
byte[] bytesForSetRange = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; byte[] bytesForSetRange = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
jedis.setrange("setrangebytes".getBytes(), 0, bytesForSetRange); jedis.setrange("setrangebytes".getBytes(), 0, bytesForSetRange);
Pipeline p = jedis.pipelined(); Pipeline p = jedis.pipelined();
Response<String> string = p.get("string"); Response<String> string = p.get("string");
Response<String> list = p.lpop("list"); Response<String> list = p.lpop("list");
Response<String> hash = p.hget("hash", "foo"); Response<String> hash = p.hget("hash", "foo");
Response<Set<String>> zset = p.zrange("zset", 0, -1); Response<Set<String>> zset = p.zrange("zset", 0, -1);
Response<String> set = p.spop("set"); Response<String> set = p.spop("set");
Response<Boolean> blist = p.exists("list"); Response<Boolean> blist = p.exists("list");
Response<Double> zincrby = p.zincrby("zset", 1, "foo"); Response<Double> zincrby = p.zincrby("zset", 1, "foo");
Response<Long> zcard = p.zcard("zset"); Response<Long> zcard = p.zcard("zset");
p.lpush("list", "bar"); p.lpush("list", "bar");
Response<List<String>> lrange = p.lrange("list", 0, -1); Response<List<String>> lrange = p.lrange("list", 0, -1);
Response<Map<String, String>> hgetAll = p.hgetAll("hash"); Response<Map<String, String>> hgetAll = p.hgetAll("hash");
p.sadd("set", "foo"); p.sadd("set", "foo");
Response<Set<String>> smembers = p.smembers("set"); Response<Set<String>> smembers = p.smembers("set");
Response<Set<Tuple>> zrangeWithScores = p.zrangeWithScores("zset", 0, Response<Set<Tuple>> zrangeWithScores = p.zrangeWithScores("zset", 0,
-1); -1);
Response<String> getrange = p.getrange("setrange", 1, 3); Response<String> getrange = p.getrange("setrange", 1, 3);
Response<byte[]> getrangeBytes = p.getrange("setrangebytes".getBytes(), Response<byte[]> getrangeBytes = p.getrange("setrangebytes".getBytes(),
6, 8); 6, 8);
p.sync(); p.sync();
assertEquals("foo", string.get()); assertEquals("foo", string.get());
assertEquals("foo", list.get()); assertEquals("foo", list.get());
assertEquals("bar", hash.get()); assertEquals("bar", hash.get());
assertEquals("foo", zset.get().iterator().next()); assertEquals("foo", zset.get().iterator().next());
assertEquals("foo", set.get()); assertEquals("foo", set.get());
assertEquals(false, blist.get()); assertEquals(false, blist.get());
assertEquals(Double.valueOf(2), zincrby.get()); assertEquals(Double.valueOf(2), zincrby.get());
assertEquals(Long.valueOf(1), zcard.get()); assertEquals(Long.valueOf(1), zcard.get());
assertEquals(1, lrange.get().size()); assertEquals(1, lrange.get().size());
assertNotNull(hgetAll.get().get("foo")); assertNotNull(hgetAll.get().get("foo"));
assertEquals(1, smembers.get().size()); assertEquals(1, smembers.get().size());
assertEquals(1, zrangeWithScores.get().size()); assertEquals(1, zrangeWithScores.get().size());
assertEquals("123", getrange.get()); assertEquals("123", getrange.get());
byte[] expectedGetRangeBytes = { 6, 7, 8 }; byte[] expectedGetRangeBytes = { 6, 7, 8 };
assertArrayEquals(expectedGetRangeBytes, getrangeBytes.get()); assertArrayEquals(expectedGetRangeBytes, getrangeBytes.get());
} }
@Test @Test
public void pipelineResponseWithData() { public void pipelineResponseWithData() {
jedis.zadd("zset", 1, "foo"); jedis.zadd("zset", 1, "foo");
Pipeline p = jedis.pipelined(); Pipeline p = jedis.pipelined();
Response<Double> score = p.zscore("zset", "foo"); Response<Double> score = p.zscore("zset", "foo");
p.sync(); p.sync();
assertNotNull(score.get()); assertNotNull(score.get());
} }
@Test @Test
public void pipelineBinarySafeHashCommands() { public void pipelineBinarySafeHashCommands() {
jedis.hset("key".getBytes(), "f1".getBytes(), "v111".getBytes()); jedis.hset("key".getBytes(), "f1".getBytes(), "v111".getBytes());
jedis.hset("key".getBytes(), "f22".getBytes(), "v2222".getBytes()); jedis.hset("key".getBytes(), "f22".getBytes(), "v2222".getBytes());
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(), Response<List<byte[]>> fordered = p.hmget("key".getBytes(),
"f22".getBytes(), "f1".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 // we have to do these strange contortions because byte[] is not a very
// good key // good key
// for a java Map. It only works with equality (you need the exact key // for a java Map. It only works with equality (you need the exact key
// object to retrieve // object to retrieve
// the value) I recommend we switch to using ByteBuffer or something // the value) I recommend we switch to using ByteBuffer or something
// similar: // 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();
Iterator<byte[]> iterMap = mapKeys.iterator(); Iterator<byte[]> iterMap = mapKeys.iterator();
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(), verifyHasBothValues(firstMapKey, secondMapKey, "f1".getBytes(),
"f22".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(), verifyHasBothValues(firstMapValue, secondMapValue, "v111".getBytes(),
"v2222".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(), verifyHasBothValues(firstKey, secondKey, "f1".getBytes(),
"f22".getBytes()); "f22".getBytes());
assertNotNull(fordered.get()); assertNotNull(fordered.get());
assertArrayEquals("v2222".getBytes(), fordered.get().get(0)); assertArrayEquals("v2222".getBytes(), fordered.get().get(0));
assertArrayEquals("v111".getBytes(), fordered.get().get(1)); assertArrayEquals("v111".getBytes(), fordered.get().get(1));
assertNotNull(fvals.get()); assertNotNull(fvals.get());
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(), verifyHasBothValues(firstValue, secondValue, "v111".getBytes(),
"v2222".getBytes()); "v2222".getBytes());
} }
private void verifyHasBothValues(byte[] firstKey, byte[] secondKey, private void verifyHasBothValues(byte[] firstKey, byte[] secondKey,
byte[] value1, byte[] value2) { byte[] value1, byte[] value2) {
assertFalse(Arrays.equals(firstKey, secondKey)); assertFalse(Arrays.equals(firstKey, secondKey));
assertTrue(Arrays.equals(firstKey, value1) assertTrue(Arrays.equals(firstKey, value1)
|| Arrays.equals(firstKey, value2)); || Arrays.equals(firstKey, value2));
assertTrue(Arrays.equals(secondKey, value1) assertTrue(Arrays.equals(secondKey, value1)
|| Arrays.equals(secondKey, value2)); || Arrays.equals(secondKey, value2));
} }
@Test @Test
public void pipelineSelect() { public void pipelineSelect() {
Pipeline p = jedis.pipelined(); Pipeline p = jedis.pipelined();
p.select(1); p.select(1);
p.sync(); p.sync();
} }
@Test @Test
public void pipelineResponseWithoutData() { public void pipelineResponseWithoutData() {
jedis.zadd("zset", 1, "foo"); jedis.zadd("zset", 1, "foo");
Pipeline p = jedis.pipelined(); Pipeline p = jedis.pipelined();
Response<Double> score = p.zscore("zset", "bar"); Response<Double> score = p.zscore("zset", "bar");
p.sync(); p.sync();
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");
Pipeline p = jedis.pipelined(); Pipeline p = jedis.pipelined();
Response<String> string = p.get("string"); Response<String> string = p.get("string");
string.get(); string.get();
p.sync(); p.sync();
} }
@Test @Test
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(), Response<Long> p2 = pipelined.publish("foo".getBytes(),
"bar".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());
} }
@Test @Test
public void canRetrieveUnsetKey() { public void canRetrieveUnsetKey() {
Pipeline p = jedis.pipelined(); Pipeline p = jedis.pipelined();
Response<String> shouldNotExist = p.get(UUID.randomUUID().toString()); Response<String> shouldNotExist = p.get(UUID.randomUUID().toString());
p.sync(); p.sync();
assertNull(shouldNotExist.get()); assertNull(shouldNotExist.get());
} }
@Test @Test
public void piplineWithError() { public void piplineWithError() {
Pipeline p = jedis.pipelined(); Pipeline p = jedis.pipelined();
p.set("foo", "bar"); p.set("foo", "bar");
Response<Set<String>> error = p.smembers("foo"); Response<Set<String>> error = p.smembers("foo");
Response<String> r = p.get("foo"); Response<String> r = p.get("foo");
p.sync(); p.sync();
try { try {
error.get(); error.get();
fail(); fail();
} catch (JedisDataException e) { } catch (JedisDataException e) {
// that is fine we should be here // that is fine we should be here
} }
assertEquals(r.get(), "bar"); assertEquals(r.get(), "bar");
} }
@Test @Test
public void multi() { public void multi() {
Pipeline p = jedis.pipelined(); Pipeline p = jedis.pipelined();
p.multi(); p.multi();
Response<Long> r1 = p.hincrBy("a", "f1", -1); Response<Long> r1 = p.hincrBy("a", "f1", -1);
Response<Long> r2 = p.hincrBy("a", "f1", -2); Response<Long> r2 = p.hincrBy("a", "f1", -2);
Response<List<Object>> r3 = p.exec(); Response<List<Object>> r3 = p.exec();
List<Object> result = p.syncAndReturnAll(); List<Object> result = p.syncAndReturnAll();
assertEquals(new Long(-1), r1.get()); assertEquals(new Long(-1), r1.get());
assertEquals(new Long(-3), r2.get()); assertEquals(new Long(-3), r2.get());
assertEquals(4, result.size()); assertEquals(4, result.size());
assertEquals("OK", result.get(0)); assertEquals("OK", result.get(0));
assertEquals("QUEUED", result.get(1)); assertEquals("QUEUED", result.get(1));
assertEquals("QUEUED", result.get(2)); assertEquals("QUEUED", result.get(2));
// 4th result is a list with the results from the multi // 4th result is a list with the results from the multi
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
List<Object> multiResult = (List<Object>) result.get(3); List<Object> multiResult = (List<Object>) result.get(3);
assertEquals(new Long(-1), multiResult.get(0)); assertEquals(new Long(-1), multiResult.get(0));
assertEquals(new Long(-3), multiResult.get(1)); assertEquals(new Long(-3), multiResult.get(1));
assertEquals(new Long(-1), r3.get().get(0)); assertEquals(new Long(-1), r3.get().get(0));
assertEquals(new Long(-3), r3.get().get(1)); assertEquals(new Long(-3), r3.get().get(1));
} }
@Test @Test
public void multiWithSync() { public void multiWithSync() {
jedis.set("foo", "314"); jedis.set("foo", "314");
jedis.set("bar", "foo"); jedis.set("bar", "foo");
jedis.set("hello", "world"); jedis.set("hello", "world");
Pipeline p = jedis.pipelined(); Pipeline p = jedis.pipelined();
Response<String> r1 = p.get("bar"); Response<String> r1 = p.get("bar");
p.multi(); p.multi();
Response<String> r2 = p.get("foo"); Response<String> r2 = p.get("foo");
p.exec(); p.exec();
Response<String> r3 = p.get("hello"); Response<String> r3 = p.get("hello");
p.sync(); p.sync();
// before multi // before multi
assertEquals("foo", r1.get()); assertEquals("foo", r1.get());
// It should be readable whether exec's response was built or not // It should be readable whether exec's response was built or not
assertEquals("314", r2.get()); assertEquals("314", r2.get());
// after multi // after multi
assertEquals("world", r3.get()); assertEquals("world", r3.get());
} }
@Test(expected = JedisDataException.class) @Test(expected = JedisDataException.class)
public void pipelineExecShoudThrowJedisDataExceptionWhenNotInMulti() { public void pipelineExecShoudThrowJedisDataExceptionWhenNotInMulti() {
Pipeline pipeline = jedis.pipelined(); Pipeline pipeline = jedis.pipelined();
pipeline.exec(); pipeline.exec();
} }
@Test(expected = JedisDataException.class) @Test(expected = JedisDataException.class)
public void pipelineDiscardShoudThrowJedisDataExceptionWhenNotInMulti() { public void pipelineDiscardShoudThrowJedisDataExceptionWhenNotInMulti() {
Pipeline pipeline = jedis.pipelined(); Pipeline pipeline = jedis.pipelined();
pipeline.discard(); pipeline.discard();
} }
@Test(expected = JedisDataException.class) @Test(expected = JedisDataException.class)
public void pipelineMultiShoudThrowJedisDataExceptionWhenAlreadyInMulti() { public void pipelineMultiShoudThrowJedisDataExceptionWhenAlreadyInMulti() {
Pipeline pipeline = jedis.pipelined(); Pipeline pipeline = jedis.pipelined();
pipeline.multi(); pipeline.multi();
pipeline.set("foo", "3"); pipeline.set("foo", "3");
pipeline.multi(); pipeline.multi();
} }
@Test @Test
public void testDiscardInPipeline() { public void testDiscardInPipeline() {
Pipeline pipeline = jedis.pipelined(); Pipeline pipeline = jedis.pipelined();
pipeline.multi(); pipeline.multi();
pipeline.set("foo", "bar"); pipeline.set("foo", "bar");
Response<String> discard = pipeline.discard(); Response<String> discard = pipeline.discard();
Response<String> get = pipeline.get("foo"); Response<String> get = pipeline.get("foo");
pipeline.sync(); pipeline.sync();
discard.get(); discard.get();
get.get(); get.get();
} }
@Test @Test
public void testEval() { public void testEval() {
String script = "return 'success!'"; String script = "return 'success!'";
Pipeline p = jedis.pipelined(); Pipeline p = jedis.pipelined();
Response<String> result = p.eval(script); Response<String> result = p.eval(script);
p.sync(); p.sync();
assertEquals("success!", result.get()); assertEquals("success!", result.get());
} }
@Test @Test
public void testEvalKeyAndArg() { public void testEvalKeyAndArg() {
String key = "test"; String key = "test";
String arg = "3"; String arg = "3";
String script = "redis.call('INCRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[1], ARGV[1])"; String script = "redis.call('INCRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[1], ARGV[1])";
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), Response<String> result0 = p.eval(script, Arrays.asList(key),
Arrays.asList(arg)); Arrays.asList(arg));
p.incr(key); p.incr(key);
Response<String> result1 = p.eval(script, Arrays.asList(key), Response<String> result1 = p.eval(script, Arrays.asList(key),
Arrays.asList(arg)); Arrays.asList(arg));
Response<String> result2 = p.get(key); Response<String> result2 = p.get(key);
p.sync(); p.sync();
assertNull(result0.get()); assertNull(result0.get());
assertNull(result1.get()); assertNull(result1.get());
assertEquals("13", result2.get()); assertEquals("13", result2.get());
} }
@Test @Test
public void testEvalsha() { public void testEvalsha() {
String script = "return 'success!'"; String script = "return 'success!'";
String sha1 = jedis.scriptLoad(script); String sha1 = jedis.scriptLoad(script);
assertTrue(jedis.scriptExists(sha1)); assertTrue(jedis.scriptExists(sha1));
Pipeline p = jedis.pipelined(); Pipeline p = jedis.pipelined();
Response<String> result = p.evalsha(sha1); Response<String> result = p.evalsha(sha1);
p.sync(); p.sync();
assertEquals("success!", result.get()); assertEquals("success!", result.get());
} }
@Test @Test
public void testEvalshaKeyAndArg() { public void testEvalshaKeyAndArg() {
String key = "test"; String key = "test";
String arg = "3"; String arg = "3";
String script = "redis.call('INCRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[1], ARGV[1])"; String script = "redis.call('INCRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[1], ARGV[1])";
String sha1 = jedis.scriptLoad(script); String sha1 = jedis.scriptLoad(script);
assertTrue(jedis.scriptExists(sha1)); assertTrue(jedis.scriptExists(sha1));
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), Response<String> result0 = p.evalsha(sha1, Arrays.asList(key),
Arrays.asList(arg)); Arrays.asList(arg));
p.incr(key); p.incr(key);
Response<String> result1 = p.evalsha(sha1, Arrays.asList(key), Response<String> result1 = p.evalsha(sha1, Arrays.asList(key),
Arrays.asList(arg)); Arrays.asList(arg));
Response<String> result2 = p.get(key); Response<String> result2 = p.get(key);
p.sync(); p.sync();
assertNull(result0.get()); assertNull(result0.get());
assertNull(result1.get()); assertNull(result1.get());
assertEquals("13", result2.get()); assertEquals("13", result2.get());
} }
@Test @Test
public void testPipelinedTransactionResponse() { public void testPipelinedTransactionResponse() {
String key1 = "key1"; String key1 = "key1";
String val1 = "val1"; String val1 = "val1";
String key2 = "key2"; String key2 = "key2";
String val2 = "val2"; String val2 = "val2";
String key3 = "key3"; String key3 = "key3";
String field1 = "field1"; String field1 = "field1";
String field2 = "field2"; String field2 = "field2";
String field3 = "field3"; String field3 = "field3";
String field4 = "field4"; String field4 = "field4";
String value1 = "value1"; String value1 = "value1";
String value2 = "value2"; String value2 = "value2";
String value3 = "value3"; String value3 = "value3";
String value4 = "value4"; String value4 = "value4";
Map<String, String> hashMap = new HashMap<String, String>(); Map<String, String> hashMap = new HashMap<String, String>();
hashMap.put(field1, value1); hashMap.put(field1, value1);
hashMap.put(field2, value2); hashMap.put(field2, value2);
String key4 = "key4"; String key4 = "key4";
Map<String, String> hashMap1 = new HashMap<String, String>(); Map<String, String> hashMap1 = new HashMap<String, String>();
hashMap1.put(field3, value3); hashMap1.put(field3, value3);
hashMap1.put(field4, value4); hashMap1.put(field4, value4);
jedis.set(key1, val1); jedis.set(key1, val1);
jedis.set(key2, val2); jedis.set(key2, val2);
jedis.hmset(key3, hashMap); jedis.hmset(key3, hashMap);
jedis.hmset(key4, hashMap1); jedis.hmset(key4, hashMap1);
Pipeline pipeline = jedis.pipelined(); Pipeline pipeline = jedis.pipelined();
pipeline.multi(); pipeline.multi();
pipeline.get(key1); pipeline.get(key1);
pipeline.hgetAll(key2); pipeline.hgetAll(key2);
pipeline.hgetAll(key3); pipeline.hgetAll(key3);
pipeline.get(key4); pipeline.get(key4);
Response<List<Object>> response = pipeline.exec(); Response<List<Object>> response = pipeline.exec();
pipeline.sync(); pipeline.sync();
List<Object> result = response.get(); List<Object> result = response.get();
assertEquals(4, result.size()); assertEquals(4, result.size());
assertEquals("val1", result.get(0)); assertEquals("val1", result.get(0));
assertTrue(result.get(1) instanceof JedisDataException); assertTrue(result.get(1) instanceof JedisDataException);
Map<String, String> hashMapReceived = (Map<String, String>) result Map<String, String> hashMapReceived = (Map<String, String>) result
.get(2); .get(2);
Iterator<String> iterator = hashMapReceived.keySet().iterator(); Iterator<String> iterator = hashMapReceived.keySet().iterator();
String mapKey1 = iterator.next(); String mapKey1 = iterator.next();
String mapKey2 = iterator.next(); String mapKey2 = iterator.next();
assertFalse(iterator.hasNext()); assertFalse(iterator.hasNext());
verifyHasBothValues(mapKey1, mapKey2, field1, field2); verifyHasBothValues(mapKey1, mapKey2, field1, field2);
String mapValue1 = hashMapReceived.get(mapKey1); String mapValue1 = hashMapReceived.get(mapKey1);
String mapValue2 = hashMapReceived.get(mapKey2); String mapValue2 = hashMapReceived.get(mapKey2);
verifyHasBothValues(mapValue1, mapValue2, value1, value2); verifyHasBothValues(mapValue1, mapValue2, value1, value2);
assertTrue(result.get(3) instanceof JedisDataException); assertTrue(result.get(3) instanceof JedisDataException);
} }
@Test @Test
public void testSyncWithNoCommandQueued() { public void testSyncWithNoCommandQueued() {
// we need to test with fresh instance of Jedis // we need to test with fresh instance of Jedis
Jedis jedis2 = new Jedis(hnp.getHost(), hnp.getPort(), 500); Jedis jedis2 = new Jedis(hnp.getHost(), hnp.getPort(), 500);
Pipeline pipeline = jedis2.pipelined(); Pipeline pipeline = jedis2.pipelined();
pipeline.sync(); pipeline.sync();
jedis2.close(); jedis2.close();
jedis2 = new Jedis(hnp.getHost(), hnp.getPort(), 500); jedis2 = new Jedis(hnp.getHost(), hnp.getPort(), 500);
pipeline = jedis2.pipelined(); pipeline = jedis2.pipelined();
List<Object> resp = pipeline.syncAndReturnAll(); List<Object> resp = pipeline.syncAndReturnAll();
assertTrue(resp.isEmpty()); assertTrue(resp.isEmpty());
jedis2.close(); jedis2.close();
} }
private void verifyHasBothValues(String firstKey, String secondKey, private void verifyHasBothValues(String firstKey, String secondKey,
String value1, String value2) { String value1, String value2) {
assertFalse(firstKey.equals(secondKey)); assertFalse(firstKey.equals(secondKey));
assertTrue(firstKey.equals(value1) || firstKey.equals(value2)); assertTrue(firstKey.equals(value1) || firstKey.equals(value2));
assertTrue(secondKey.equals(value1) || secondKey.equals(value2)); assertTrue(secondKey.equals(value1) || secondKey.equals(value2));
} }
} }

View File

@@ -20,108 +20,108 @@ import redis.clients.util.SafeEncoder;
public class ProtocolTest extends JedisTestBase { public class ProtocolTest extends JedisTestBase {
@Test @Test
public void buildACommand() throws IOException { public void buildACommand() throws IOException {
PipedInputStream pis = new PipedInputStream(); PipedInputStream pis = new PipedInputStream();
BufferedInputStream bis = new BufferedInputStream(pis); BufferedInputStream bis = new BufferedInputStream(pis);
PipedOutputStream pos = new PipedOutputStream(pis); PipedOutputStream pos = new PipedOutputStream(pis);
RedisOutputStream ros = new RedisOutputStream(pos); RedisOutputStream ros = new RedisOutputStream(pos);
Protocol.sendCommand(ros, Protocol.Command.GET, Protocol.sendCommand(ros, Protocol.Command.GET,
"SOMEKEY".getBytes(Protocol.CHARSET)); "SOMEKEY".getBytes(Protocol.CHARSET));
ros.flush(); ros.flush();
pos.close(); pos.close();
String expectedCommand = "*2\r\n$3\r\nGET\r\n$7\r\nSOMEKEY\r\n"; String expectedCommand = "*2\r\n$3\r\nGET\r\n$7\r\nSOMEKEY\r\n";
int b; int b;
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
while ((b = bis.read()) != -1) { while ((b = bis.read()) != -1) {
sb.append((char) b); sb.append((char) b);
} }
assertEquals(expectedCommand, sb.toString()); assertEquals(expectedCommand, sb.toString());
} }
@Test(expected = IOException.class) @Test(expected = IOException.class)
public void writeOverflow() throws IOException { public void writeOverflow() throws IOException {
RedisOutputStream ros = new RedisOutputStream(new OutputStream() { RedisOutputStream ros = new RedisOutputStream(new OutputStream() {
@Override @Override
public void write(int b) throws IOException { public void write(int b) throws IOException {
throw new IOException("thrown exception"); throw new IOException("thrown exception");
} }
}); });
ros.write(new byte[8191]); ros.write(new byte[8191]);
try { try {
ros.write((byte) '*'); ros.write((byte) '*');
} catch (IOException ioe) { } catch (IOException ioe) {
} }
ros.write((byte) '*'); ros.write((byte) '*');
} }
@Test @Test
public void bulkReply() { public void bulkReply() {
InputStream is = new ByteArrayInputStream("$6\r\nfoobar\r\n".getBytes()); InputStream is = new ByteArrayInputStream("$6\r\nfoobar\r\n".getBytes());
byte[] response = (byte[]) Protocol.read(new RedisInputStream(is)); byte[] response = (byte[]) Protocol.read(new RedisInputStream(is));
assertArrayEquals(SafeEncoder.encode("foobar"), response); assertArrayEquals(SafeEncoder.encode("foobar"), response);
} }
@Test @Test
public void fragmentedBulkReply() { public void fragmentedBulkReply() {
FragmentedByteArrayInputStream fis = new FragmentedByteArrayInputStream( FragmentedByteArrayInputStream fis = new FragmentedByteArrayInputStream(
"$30\r\n012345678901234567890123456789\r\n".getBytes()); "$30\r\n012345678901234567890123456789\r\n".getBytes());
byte[] response = (byte[]) Protocol.read(new RedisInputStream(fis)); byte[] response = (byte[]) Protocol.read(new RedisInputStream(fis));
assertArrayEquals(SafeEncoder.encode("012345678901234567890123456789"), assertArrayEquals(SafeEncoder.encode("012345678901234567890123456789"),
response); response);
} }
@Test @Test
public void nullBulkReply() { public void nullBulkReply() {
InputStream is = new ByteArrayInputStream("$-1\r\n".getBytes()); InputStream is = new ByteArrayInputStream("$-1\r\n".getBytes());
String response = (String) Protocol.read(new RedisInputStream(is)); String response = (String) Protocol.read(new RedisInputStream(is));
assertEquals(null, response); assertEquals(null, response);
} }
@Test @Test
public void singleLineReply() { public void singleLineReply() {
InputStream is = new ByteArrayInputStream("+OK\r\n".getBytes()); InputStream is = new ByteArrayInputStream("+OK\r\n".getBytes());
byte[] response = (byte[]) Protocol.read(new RedisInputStream(is)); byte[] response = (byte[]) Protocol.read(new RedisInputStream(is));
assertArrayEquals(SafeEncoder.encode("OK"), response); assertArrayEquals(SafeEncoder.encode("OK"), response);
} }
@Test @Test
public void integerReply() { public void integerReply() {
InputStream is = new ByteArrayInputStream(":123\r\n".getBytes()); InputStream is = new ByteArrayInputStream(":123\r\n".getBytes());
long response = (Long) Protocol.read(new RedisInputStream(is)); long response = (Long) Protocol.read(new RedisInputStream(is));
assertEquals(123, response); assertEquals(123, response);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Test @Test
public void multiBulkReply() { public void multiBulkReply() {
InputStream is = new ByteArrayInputStream( InputStream is = new ByteArrayInputStream(
"*4\r\n$3\r\nfoo\r\n$3\r\nbar\r\n$5\r\nHello\r\n$5\r\nWorld\r\n" "*4\r\n$3\r\nfoo\r\n$3\r\nbar\r\n$5\r\nHello\r\n$5\r\nWorld\r\n"
.getBytes()); .getBytes());
List<byte[]> response = (List<byte[]>) Protocol List<byte[]> response = (List<byte[]>) Protocol
.read(new RedisInputStream(is)); .read(new RedisInputStream(is));
List<byte[]> expected = new ArrayList<byte[]>(); List<byte[]> expected = new ArrayList<byte[]>();
expected.add(SafeEncoder.encode("foo")); expected.add(SafeEncoder.encode("foo"));
expected.add(SafeEncoder.encode("bar")); expected.add(SafeEncoder.encode("bar"));
expected.add(SafeEncoder.encode("Hello")); expected.add(SafeEncoder.encode("Hello"));
expected.add(SafeEncoder.encode("World")); expected.add(SafeEncoder.encode("World"));
assertEquals(expected, response); assertEquals(expected, response);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Test @Test
public void nullMultiBulkReply() { public void nullMultiBulkReply() {
InputStream is = new ByteArrayInputStream("*-1\r\n".getBytes()); InputStream is = new ByteArrayInputStream("*-1\r\n".getBytes());
List<String> response = (List<String>) Protocol List<String> response = (List<String>) Protocol
.read(new RedisInputStream(is)); .read(new RedisInputStream(is));
assertNull(response); assertNull(response);
} }
} }

View File

@@ -29,135 +29,135 @@ import redis.clients.jedis.exceptions.JedisDataException;
public class ShardedJedisPipelineTest { public class ShardedJedisPipelineTest {
private static HostAndPort redis1 = HostAndPortUtil.getRedisServers() private static HostAndPort redis1 = HostAndPortUtil.getRedisServers()
.get(0); .get(0);
private static HostAndPort redis2 = HostAndPortUtil.getRedisServers() private static HostAndPort redis2 = HostAndPortUtil.getRedisServers()
.get(1); .get(1);
private ShardedJedis jedis; private ShardedJedis jedis;
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
Jedis jedis = new Jedis(redis1.getHost(), redis1.getPort()); Jedis jedis = new Jedis(redis1.getHost(), redis1.getPort());
jedis.auth("foobared"); jedis.auth("foobared");
jedis.flushAll(); jedis.flushAll();
jedis.disconnect(); jedis.disconnect();
jedis = new Jedis(redis2.getHost(), redis2.getPort()); jedis = new Jedis(redis2.getHost(), redis2.getPort());
jedis.auth("foobared"); jedis.auth("foobared");
jedis.flushAll(); jedis.flushAll();
jedis.disconnect(); jedis.disconnect();
JedisShardInfo shardInfo1 = new JedisShardInfo(redis1.getHost(), JedisShardInfo shardInfo1 = new JedisShardInfo(redis1.getHost(),
redis1.getPort()); redis1.getPort());
JedisShardInfo shardInfo2 = new JedisShardInfo(redis2.getHost(), JedisShardInfo shardInfo2 = new JedisShardInfo(redis2.getHost(),
redis2.getPort()); redis2.getPort());
shardInfo1.setPassword("foobared"); shardInfo1.setPassword("foobared");
shardInfo2.setPassword("foobared"); shardInfo2.setPassword("foobared");
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(); List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(shardInfo1); shards.add(shardInfo1);
shards.add(shardInfo2); shards.add(shardInfo2);
this.jedis = new ShardedJedis(shards); this.jedis = new ShardedJedis(shards);
} }
@Test @Test
public void pipeline() throws UnsupportedEncodingException { public void pipeline() throws UnsupportedEncodingException {
ShardedJedisPipeline p = jedis.pipelined(); ShardedJedisPipeline p = jedis.pipelined();
p.set("foo", "bar"); p.set("foo", "bar");
p.get("foo"); p.get("foo");
List<Object> results = p.syncAndReturnAll(); List<Object> results = p.syncAndReturnAll();
assertEquals(2, results.size()); assertEquals(2, results.size());
assertEquals("OK", results.get(0)); assertEquals("OK", results.get(0));
assertEquals("bar", results.get(1)); assertEquals("bar", results.get(1));
} }
@Test @Test
public void pipelineResponse() { public void pipelineResponse() {
jedis.set("string", "foo"); jedis.set("string", "foo");
jedis.lpush("list", "foo"); jedis.lpush("list", "foo");
jedis.hset("hash", "foo", "bar"); jedis.hset("hash", "foo", "bar");
jedis.zadd("zset", 1, "foo"); jedis.zadd("zset", 1, "foo");
jedis.sadd("set", "foo"); jedis.sadd("set", "foo");
ShardedJedisPipeline p = jedis.pipelined(); ShardedJedisPipeline p = jedis.pipelined();
Response<String> string = p.get("string"); Response<String> string = p.get("string");
Response<Long> del = p.del("string"); Response<Long> del = p.del("string");
Response<String> emptyString = p.get("string"); Response<String> emptyString = p.get("string");
Response<String> list = p.lpop("list"); Response<String> list = p.lpop("list");
Response<String> hash = p.hget("hash", "foo"); Response<String> hash = p.hget("hash", "foo");
Response<Set<String>> zset = p.zrange("zset", 0, -1); Response<Set<String>> zset = p.zrange("zset", 0, -1);
Response<String> set = p.spop("set"); Response<String> set = p.spop("set");
Response<Boolean> blist = p.exists("list"); Response<Boolean> blist = p.exists("list");
Response<Double> zincrby = p.zincrby("zset", 1, "foo"); Response<Double> zincrby = p.zincrby("zset", 1, "foo");
Response<Long> zcard = p.zcard("zset"); Response<Long> zcard = p.zcard("zset");
p.lpush("list", "bar"); p.lpush("list", "bar");
Response<List<String>> lrange = p.lrange("list", 0, -1); Response<List<String>> lrange = p.lrange("list", 0, -1);
Response<Map<String, String>> hgetAll = p.hgetAll("hash"); Response<Map<String, String>> hgetAll = p.hgetAll("hash");
p.sadd("set", "foo"); p.sadd("set", "foo");
Response<Set<String>> smembers = p.smembers("set"); Response<Set<String>> smembers = p.smembers("set");
Response<Set<Tuple>> zrangeWithScores = p.zrangeWithScores("zset", 0, Response<Set<Tuple>> zrangeWithScores = p.zrangeWithScores("zset", 0,
-1); -1);
p.sync(); p.sync();
assertEquals("foo", string.get()); assertEquals("foo", string.get());
assertEquals(Long.valueOf(1), del.get()); assertEquals(Long.valueOf(1), del.get());
assertNull(emptyString.get()); assertNull(emptyString.get());
assertEquals("foo", list.get()); assertEquals("foo", list.get());
assertEquals("bar", hash.get()); assertEquals("bar", hash.get());
assertEquals("foo", zset.get().iterator().next()); assertEquals("foo", zset.get().iterator().next());
assertEquals("foo", set.get()); assertEquals("foo", set.get());
assertFalse(blist.get()); assertFalse(blist.get());
assertEquals(Double.valueOf(2), zincrby.get()); assertEquals(Double.valueOf(2), zincrby.get());
assertEquals(Long.valueOf(1), zcard.get()); assertEquals(Long.valueOf(1), zcard.get());
assertEquals(1, lrange.get().size()); assertEquals(1, lrange.get().size());
assertNotNull(hgetAll.get().get("foo")); assertNotNull(hgetAll.get().get("foo"));
assertEquals(1, smembers.get().size()); assertEquals(1, smembers.get().size());
assertEquals(1, zrangeWithScores.get().size()); assertEquals(1, zrangeWithScores.get().size());
} }
@Test(expected = JedisDataException.class) @Test(expected = JedisDataException.class)
public void pipelineResponseWithinPipeline() { public void pipelineResponseWithinPipeline() {
jedis.set("string", "foo"); jedis.set("string", "foo");
ShardedJedisPipeline p = jedis.pipelined(); ShardedJedisPipeline p = jedis.pipelined();
Response<String> string = p.get("string"); Response<String> string = p.get("string");
string.get(); string.get();
p.sync(); p.sync();
} }
@Test @Test
public void canRetrieveUnsetKey() { public void canRetrieveUnsetKey() {
ShardedJedisPipeline p = jedis.pipelined(); ShardedJedisPipeline p = jedis.pipelined();
Response<String> shouldNotExist = p.get(UUID.randomUUID().toString()); Response<String> shouldNotExist = p.get(UUID.randomUUID().toString());
p.sync(); p.sync();
assertNull(shouldNotExist.get()); assertNull(shouldNotExist.get());
} }
@Test @Test
public void testSyncWithNoCommandQueued() { public void testSyncWithNoCommandQueued() {
JedisShardInfo shardInfo1 = new JedisShardInfo(redis1.getHost(), JedisShardInfo shardInfo1 = new JedisShardInfo(redis1.getHost(),
redis1.getPort()); redis1.getPort());
JedisShardInfo shardInfo2 = new JedisShardInfo(redis2.getHost(), JedisShardInfo shardInfo2 = new JedisShardInfo(redis2.getHost(),
redis2.getPort()); redis2.getPort());
shardInfo1.setPassword("foobared"); shardInfo1.setPassword("foobared");
shardInfo2.setPassword("foobared"); shardInfo2.setPassword("foobared");
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(); List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(shardInfo1); shards.add(shardInfo1);
shards.add(shardInfo2); shards.add(shardInfo2);
ShardedJedis jedis2 = new ShardedJedis(shards); ShardedJedis jedis2 = new ShardedJedis(shards);
ShardedJedisPipeline pipeline = jedis2.pipelined(); ShardedJedisPipeline pipeline = jedis2.pipelined();
pipeline.sync(); pipeline.sync();
jedis2.close(); jedis2.close();
jedis2 = new ShardedJedis(shards); jedis2 = new ShardedJedis(shards);
pipeline = jedis2.pipelined(); pipeline = jedis2.pipelined();
List<Object> resp = pipeline.syncAndReturnAll(); List<Object> resp = pipeline.syncAndReturnAll();
assertTrue(resp.isEmpty()); assertTrue(resp.isEmpty());
jedis2.close(); jedis2.close();
} }
} }

View File

@@ -20,295 +20,295 @@ import redis.clients.jedis.exceptions.JedisConnectionException;
public class ShardedJedisPoolTest extends Assert { public class ShardedJedisPoolTest extends Assert {
private static HostAndPort redis1 = HostAndPortUtil.getRedisServers() private static HostAndPort redis1 = HostAndPortUtil.getRedisServers()
.get(0); .get(0);
private static HostAndPort redis2 = HostAndPortUtil.getRedisServers() private static HostAndPort redis2 = HostAndPortUtil.getRedisServers()
.get(1); .get(1);
private List<JedisShardInfo> shards; private List<JedisShardInfo> shards;
@Before @Before
public void startUp() { public void startUp() {
shards = new ArrayList<JedisShardInfo>(); shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(redis1.getHost(), redis1.getPort())); shards.add(new JedisShardInfo(redis1.getHost(), redis1.getPort()));
shards.add(new JedisShardInfo(redis2.getHost(), redis2.getPort())); shards.add(new JedisShardInfo(redis2.getHost(), redis2.getPort()));
shards.get(0).setPassword("foobared"); shards.get(0).setPassword("foobared");
shards.get(1).setPassword("foobared"); shards.get(1).setPassword("foobared");
Jedis j = new Jedis(shards.get(0)); Jedis j = new Jedis(shards.get(0));
j.connect(); j.connect();
j.flushAll(); j.flushAll();
j.disconnect(); j.disconnect();
j = new Jedis(shards.get(1)); j = new Jedis(shards.get(1));
j.connect(); j.connect();
j.flushAll(); j.flushAll();
j.disconnect(); j.disconnect();
} }
@Test @Test
public void checkConnections() { public void checkConnections() {
ShardedJedisPool pool = new ShardedJedisPool( ShardedJedisPool pool = new ShardedJedisPool(
new GenericObjectPoolConfig(), shards); new GenericObjectPoolConfig(), shards);
ShardedJedis jedis = pool.getResource(); ShardedJedis jedis = pool.getResource();
jedis.set("foo", "bar"); jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo")); assertEquals("bar", jedis.get("foo"));
pool.returnResource(jedis); pool.returnResource(jedis);
pool.destroy(); pool.destroy();
} }
@Test @Test
public void checkCloseableConnections() throws Exception { public void checkCloseableConnections() throws Exception {
ShardedJedisPool pool = new ShardedJedisPool( ShardedJedisPool pool = new ShardedJedisPool(
new GenericObjectPoolConfig(), shards); new GenericObjectPoolConfig(), shards);
ShardedJedis jedis = pool.getResource(); ShardedJedis jedis = pool.getResource();
jedis.set("foo", "bar"); jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo")); assertEquals("bar", jedis.get("foo"));
pool.returnResource(jedis); pool.returnResource(jedis);
pool.close(); pool.close();
assertTrue(pool.isClosed()); assertTrue(pool.isClosed());
} }
@Test @Test
public void checkConnectionWithDefaultPort() { public void checkConnectionWithDefaultPort() {
ShardedJedisPool pool = new ShardedJedisPool( ShardedJedisPool pool = new ShardedJedisPool(
new GenericObjectPoolConfig(), shards); new GenericObjectPoolConfig(), shards);
ShardedJedis jedis = pool.getResource(); ShardedJedis jedis = pool.getResource();
jedis.set("foo", "bar"); jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo")); assertEquals("bar", jedis.get("foo"));
pool.returnResource(jedis); pool.returnResource(jedis);
pool.destroy(); pool.destroy();
} }
@Test @Test
public void checkJedisIsReusedWhenReturned() { public void checkJedisIsReusedWhenReturned() {
ShardedJedisPool pool = new ShardedJedisPool( ShardedJedisPool pool = new ShardedJedisPool(
new GenericObjectPoolConfig(), shards); new GenericObjectPoolConfig(), shards);
ShardedJedis jedis = pool.getResource(); ShardedJedis jedis = pool.getResource();
jedis.set("foo", "0"); jedis.set("foo", "0");
pool.returnResource(jedis); pool.returnResource(jedis);
jedis = pool.getResource(); jedis = pool.getResource();
jedis.incr("foo"); jedis.incr("foo");
pool.returnResource(jedis); pool.returnResource(jedis);
pool.destroy(); pool.destroy();
} }
@Test @Test
public void checkPoolRepairedWhenJedisIsBroken() { public void checkPoolRepairedWhenJedisIsBroken() {
ShardedJedisPool pool = new ShardedJedisPool( ShardedJedisPool pool = new ShardedJedisPool(
new GenericObjectPoolConfig(), shards); new GenericObjectPoolConfig(), shards);
ShardedJedis jedis = pool.getResource(); ShardedJedis jedis = pool.getResource();
jedis.disconnect(); jedis.disconnect();
pool.returnBrokenResource(jedis); pool.returnBrokenResource(jedis);
jedis = pool.getResource(); jedis = pool.getResource();
jedis.incr("foo"); jedis.incr("foo");
pool.returnResource(jedis); pool.returnResource(jedis);
pool.destroy(); pool.destroy();
} }
@Test(expected = JedisConnectionException.class) @Test(expected = JedisConnectionException.class)
public void checkPoolOverflow() { public void checkPoolOverflow() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig(); GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1); config.setMaxTotal(1);
config.setBlockWhenExhausted(false); config.setBlockWhenExhausted(false);
ShardedJedisPool pool = new ShardedJedisPool(config, shards); ShardedJedisPool pool = new ShardedJedisPool(config, shards);
ShardedJedis jedis = pool.getResource(); ShardedJedis jedis = pool.getResource();
jedis.set("foo", "0"); jedis.set("foo", "0");
ShardedJedis newJedis = pool.getResource(); ShardedJedis newJedis = pool.getResource();
newJedis.incr("foo"); newJedis.incr("foo");
} }
@Test @Test
public void shouldNotShareInstances() { public void shouldNotShareInstances() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig(); GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(2); config.setMaxTotal(2);
ShardedJedisPool pool = new ShardedJedisPool(config, shards); ShardedJedisPool pool = new ShardedJedisPool(config, shards);
ShardedJedis j1 = pool.getResource(); ShardedJedis j1 = pool.getResource();
ShardedJedis j2 = pool.getResource(); ShardedJedis j2 = pool.getResource();
assertNotSame(j1.getShard("foo"), j2.getShard("foo")); assertNotSame(j1.getShard("foo"), j2.getShard("foo"));
} }
@Test @Test
public void checkFailedJedisServer() { public void checkFailedJedisServer() {
ShardedJedisPool pool = new ShardedJedisPool( ShardedJedisPool pool = new ShardedJedisPool(
new GenericObjectPoolConfig(), shards); new GenericObjectPoolConfig(), shards);
ShardedJedis jedis = pool.getResource(); ShardedJedis jedis = pool.getResource();
jedis.incr("foo"); jedis.incr("foo");
pool.returnResource(jedis); pool.returnResource(jedis);
pool.destroy(); pool.destroy();
} }
@Test @Test
public void shouldReturnActiveShardsWhenOneGoesOffline() { public void shouldReturnActiveShardsWhenOneGoesOffline() {
GenericObjectPoolConfig redisConfig = new GenericObjectPoolConfig(); GenericObjectPoolConfig redisConfig = new GenericObjectPoolConfig();
redisConfig.setTestOnBorrow(false); redisConfig.setTestOnBorrow(false);
ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards); ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards);
ShardedJedis jedis = pool.getResource(); ShardedJedis jedis = pool.getResource();
// fill the shards // fill the shards
for (int i = 0; i < 1000; i++) { for (int i = 0; i < 1000; i++) {
jedis.set("a-test-" + i, "0"); jedis.set("a-test-" + i, "0");
} }
pool.returnResource(jedis); pool.returnResource(jedis);
// check quantity for each shard // check quantity for each shard
Jedis j = new Jedis(shards.get(0)); Jedis j = new Jedis(shards.get(0));
j.connect(); j.connect();
Long c1 = j.dbSize(); Long c1 = j.dbSize();
j.disconnect(); j.disconnect();
j = new Jedis(shards.get(1)); j = new Jedis(shards.get(1));
j.connect(); j.connect();
Long c2 = j.dbSize(); Long c2 = j.dbSize();
j.disconnect(); j.disconnect();
// shutdown shard 2 and check thay the pool returns an instance with c1 // shutdown shard 2 and check thay the pool returns an instance with c1
// items on one shard // items on one shard
// alter shard 1 and recreate pool // alter shard 1 and recreate pool
pool.destroy(); pool.destroy();
shards.set(1, new JedisShardInfo("localhost", 1234)); shards.set(1, new JedisShardInfo("localhost", 1234));
pool = new ShardedJedisPool(redisConfig, shards); pool = new ShardedJedisPool(redisConfig, shards);
jedis = pool.getResource(); jedis = pool.getResource();
Long actual = Long.valueOf(0); Long actual = Long.valueOf(0);
Long fails = Long.valueOf(0); Long fails = Long.valueOf(0);
for (int i = 0; i < 1000; i++) { for (int i = 0; i < 1000; i++) {
try { try {
jedis.get("a-test-" + i); jedis.get("a-test-" + i);
actual++; actual++;
} catch (RuntimeException e) { } catch (RuntimeException e) {
fails++; fails++;
} }
} }
pool.returnResource(jedis); pool.returnResource(jedis);
pool.destroy(); pool.destroy();
assertEquals(actual, c1); assertEquals(actual, c1);
assertEquals(fails, c2); assertEquals(fails, c2);
} }
@Test @Test
public void startWithUrlString() { public void startWithUrlString() {
Jedis j = new Jedis("localhost", 6380); Jedis j = new Jedis("localhost", 6380);
j.auth("foobared"); j.auth("foobared");
j.set("foo", "bar"); j.set("foo", "bar");
j = new Jedis("localhost", 6379); j = new Jedis("localhost", 6379);
j.auth("foobared"); j.auth("foobared");
j.set("foo", "bar"); j.set("foo", "bar");
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(); List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo("redis://:foobared@localhost:6380")); shards.add(new JedisShardInfo("redis://:foobared@localhost:6380"));
shards.add(new JedisShardInfo("redis://:foobared@localhost:6379")); shards.add(new JedisShardInfo("redis://:foobared@localhost:6379"));
GenericObjectPoolConfig redisConfig = new GenericObjectPoolConfig(); GenericObjectPoolConfig redisConfig = new GenericObjectPoolConfig();
ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards); ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards);
Jedis[] jedises = pool.getResource().getAllShards() Jedis[] jedises = pool.getResource().getAllShards()
.toArray(new Jedis[2]); .toArray(new Jedis[2]);
Jedis jedis = jedises[0]; Jedis jedis = jedises[0];
assertEquals("PONG", jedis.ping()); assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo")); assertEquals("bar", jedis.get("foo"));
jedis = jedises[1]; jedis = jedises[1];
assertEquals("PONG", jedis.ping()); assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo")); assertEquals("bar", jedis.get("foo"));
} }
@Test @Test
public void startWithUrl() throws URISyntaxException { public void startWithUrl() throws URISyntaxException {
Jedis j = new Jedis("localhost", 6380); Jedis j = new Jedis("localhost", 6380);
j.auth("foobared"); j.auth("foobared");
j.set("foo", "bar"); j.set("foo", "bar");
j = new Jedis("localhost", 6379); j = new Jedis("localhost", 6379);
j.auth("foobared"); j.auth("foobared");
j.set("foo", "bar"); j.set("foo", "bar");
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(); List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(new URI( shards.add(new JedisShardInfo(new URI(
"redis://:foobared@localhost:6380"))); "redis://:foobared@localhost:6380")));
shards.add(new JedisShardInfo(new URI( shards.add(new JedisShardInfo(new URI(
"redis://:foobared@localhost:6379"))); "redis://:foobared@localhost:6379")));
GenericObjectPoolConfig redisConfig = new GenericObjectPoolConfig(); GenericObjectPoolConfig redisConfig = new GenericObjectPoolConfig();
ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards); ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards);
Jedis[] jedises = pool.getResource().getAllShards() Jedis[] jedises = pool.getResource().getAllShards()
.toArray(new Jedis[2]); .toArray(new Jedis[2]);
Jedis jedis = jedises[0]; Jedis jedis = jedises[0];
assertEquals("PONG", jedis.ping()); assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo")); assertEquals("bar", jedis.get("foo"));
jedis = jedises[1]; jedis = jedises[1];
assertEquals("PONG", jedis.ping()); assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo")); assertEquals("bar", jedis.get("foo"));
} }
@Test @Test
public void returnResourceShouldResetState() throws URISyntaxException { public void returnResourceShouldResetState() throws URISyntaxException {
GenericObjectPoolConfig config = new GenericObjectPoolConfig(); GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1); config.setMaxTotal(1);
config.setBlockWhenExhausted(false); config.setBlockWhenExhausted(false);
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(); List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(new URI( shards.add(new JedisShardInfo(new URI(
"redis://:foobared@localhost:6380"))); "redis://:foobared@localhost:6380")));
shards.add(new JedisShardInfo(new URI( shards.add(new JedisShardInfo(new URI(
"redis://:foobared@localhost:6379"))); "redis://:foobared@localhost:6379")));
ShardedJedisPool pool = new ShardedJedisPool(config, shards); ShardedJedisPool pool = new ShardedJedisPool(config, shards);
ShardedJedis jedis = pool.getResource(); ShardedJedis jedis = pool.getResource();
jedis.set("pipelined", String.valueOf(0)); jedis.set("pipelined", String.valueOf(0));
jedis.set("pipelined2", String.valueOf(0)); jedis.set("pipelined2", String.valueOf(0));
ShardedJedisPipeline pipeline = jedis.pipelined(); ShardedJedisPipeline pipeline = jedis.pipelined();
pipeline.incr("pipelined"); pipeline.incr("pipelined");
pipeline.incr("pipelined2"); pipeline.incr("pipelined2");
jedis.resetState(); jedis.resetState();
pipeline = jedis.pipelined(); pipeline = jedis.pipelined();
pipeline.incr("pipelined"); pipeline.incr("pipelined");
pipeline.incr("pipelined2"); pipeline.incr("pipelined2");
List<Object> results = pipeline.syncAndReturnAll(); List<Object> results = pipeline.syncAndReturnAll();
assertEquals(2, results.size()); assertEquals(2, results.size());
pool.returnResource(jedis); pool.returnResource(jedis);
pool.destroy(); pool.destroy();
} }
@Test @Test
public void checkResourceIsCloseable() throws URISyntaxException { public void checkResourceIsCloseable() throws URISyntaxException {
GenericObjectPoolConfig config = new GenericObjectPoolConfig(); GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(1); config.setMaxTotal(1);
config.setBlockWhenExhausted(false); config.setBlockWhenExhausted(false);
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(); List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(new URI( shards.add(new JedisShardInfo(new URI(
"redis://:foobared@localhost:6380"))); "redis://:foobared@localhost:6380")));
shards.add(new JedisShardInfo(new URI( shards.add(new JedisShardInfo(new URI(
"redis://:foobared@localhost:6379"))); "redis://:foobared@localhost:6379")));
ShardedJedisPool pool = new ShardedJedisPool(config, shards); ShardedJedisPool pool = new ShardedJedisPool(config, shards);
ShardedJedis jedis = pool.getResource(); ShardedJedis jedis = pool.getResource();
try { try {
jedis.set("hello", "jedis"); jedis.set("hello", "jedis");
} finally { } finally {
jedis.close(); jedis.close();
} }
ShardedJedis jedis2 = pool.getResource(); ShardedJedis jedis2 = pool.getResource();
try { try {
assertEquals(jedis, jedis2); assertEquals(jedis, jedis2);
} finally { } finally {
jedis2.close(); jedis2.close();
} }
} }
} }

View File

@@ -18,278 +18,278 @@ import redis.clients.util.Sharded;
public class ShardedJedisTest extends Assert { public class ShardedJedisTest extends Assert {
private static HostAndPort redis1 = HostAndPortUtil.getRedisServers() private static HostAndPort redis1 = HostAndPortUtil.getRedisServers()
.get(0); .get(0);
private static HostAndPort redis2 = HostAndPortUtil.getRedisServers() private static HostAndPort redis2 = HostAndPortUtil.getRedisServers()
.get(1); .get(1);
private List<String> getKeysDifferentShard(ShardedJedis jedis) { private List<String> getKeysDifferentShard(ShardedJedis jedis) {
List<String> ret = new ArrayList<String>(); List<String> ret = new ArrayList<String>();
JedisShardInfo first = jedis.getShardInfo("a0"); JedisShardInfo first = jedis.getShardInfo("a0");
ret.add("a0"); ret.add("a0");
for (int i = 1; i < 100; ++i) { for (int i = 1; i < 100; ++i) {
JedisShardInfo actual = jedis.getShardInfo("a" + i); JedisShardInfo actual = jedis.getShardInfo("a" + i);
if (actual != first) { if (actual != first) {
ret.add("a" + i); ret.add("a" + i);
break; break;
} }
} }
return ret; return ret;
} }
@Test @Test
public void checkSharding() { public void checkSharding() {
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(); List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(redis1.getHost(), redis1.getPort())); shards.add(new JedisShardInfo(redis1.getHost(), redis1.getPort()));
shards.add(new JedisShardInfo(redis2.getHost(), redis2.getPort())); shards.add(new JedisShardInfo(redis2.getHost(), redis2.getPort()));
ShardedJedis jedis = new ShardedJedis(shards); ShardedJedis jedis = new ShardedJedis(shards);
List<String> keys = getKeysDifferentShard(jedis); List<String> keys = getKeysDifferentShard(jedis);
JedisShardInfo s1 = jedis.getShardInfo(keys.get(0)); JedisShardInfo s1 = jedis.getShardInfo(keys.get(0));
JedisShardInfo s2 = jedis.getShardInfo(keys.get(1)); JedisShardInfo s2 = jedis.getShardInfo(keys.get(1));
assertNotSame(s1, s2); assertNotSame(s1, s2);
} }
@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(), JedisShardInfo si = new JedisShardInfo(redis1.getHost(),
redis1.getPort()); 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());
si.setPassword("foobared"); si.setPassword("foobared");
shards.add(si); shards.add(si);
ShardedJedis jedis = new ShardedJedis(shards); ShardedJedis jedis = new ShardedJedis(shards);
jedis.set("a", "bar"); jedis.set("a", "bar");
JedisShardInfo s1 = jedis.getShardInfo("a"); JedisShardInfo s1 = jedis.getShardInfo("a");
jedis.set("b", "bar1"); jedis.set("b", "bar1");
JedisShardInfo s2 = jedis.getShardInfo("b"); JedisShardInfo s2 = jedis.getShardInfo("b");
jedis.disconnect(); jedis.disconnect();
Jedis j = new Jedis(s1.getHost(), s1.getPort()); Jedis j = new Jedis(s1.getHost(), s1.getPort());
j.auth("foobared"); j.auth("foobared");
assertEquals("bar", j.get("a")); assertEquals("bar", j.get("a"));
j.disconnect(); j.disconnect();
j = new Jedis(s2.getHost(), s2.getPort()); j = new Jedis(s2.getHost(), s2.getPort());
j.auth("foobared"); j.auth("foobared");
assertEquals("bar1", j.get("b")); assertEquals("bar1", j.get("b"));
j.disconnect(); j.disconnect();
} }
@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(), JedisShardInfo si = new JedisShardInfo(redis1.getHost(),
redis1.getPort()); 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());
si.setPassword("foobared"); si.setPassword("foobared");
shards.add(si); shards.add(si);
ShardedJedis jedis = new ShardedJedis(shards, Hashing.MURMUR_HASH); ShardedJedis jedis = new ShardedJedis(shards, Hashing.MURMUR_HASH);
jedis.set("a", "bar"); jedis.set("a", "bar");
JedisShardInfo s1 = jedis.getShardInfo("a"); JedisShardInfo s1 = jedis.getShardInfo("a");
jedis.set("b", "bar1"); jedis.set("b", "bar1");
JedisShardInfo s2 = jedis.getShardInfo("b"); JedisShardInfo s2 = jedis.getShardInfo("b");
jedis.disconnect(); jedis.disconnect();
Jedis j = new Jedis(s1.getHost(), s1.getPort()); Jedis j = new Jedis(s1.getHost(), s1.getPort());
j.auth("foobared"); j.auth("foobared");
assertEquals("bar", j.get("a")); assertEquals("bar", j.get("a"));
j.disconnect(); j.disconnect();
j = new Jedis(s2.getHost(), s2.getPort()); j = new Jedis(s2.getHost(), s2.getPort());
j.auth("foobared"); j.auth("foobared");
assertEquals("bar1", j.get("b")); assertEquals("bar1", j.get("b"));
j.disconnect(); j.disconnect();
} }
@Test @Test
public void checkKeyTags() { public void checkKeyTags() {
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(); List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(redis1.getHost(), redis1.getPort())); shards.add(new JedisShardInfo(redis1.getHost(), redis1.getPort()));
shards.add(new JedisShardInfo(redis2.getHost(), redis2.getPort())); shards.add(new JedisShardInfo(redis2.getHost(), redis2.getPort()));
ShardedJedis jedis = new ShardedJedis(shards, ShardedJedis jedis = new ShardedJedis(shards,
ShardedJedis.DEFAULT_KEY_TAG_PATTERN); ShardedJedis.DEFAULT_KEY_TAG_PATTERN);
assertEquals(jedis.getKeyTag("foo"), "foo"); assertEquals(jedis.getKeyTag("foo"), "foo");
assertEquals(jedis.getKeyTag("foo{bar}"), "bar"); assertEquals(jedis.getKeyTag("foo{bar}"), "bar");
assertEquals(jedis.getKeyTag("foo{bar}}"), "bar"); // default pattern is assertEquals(jedis.getKeyTag("foo{bar}}"), "bar"); // default pattern is
// non greedy // non greedy
assertEquals(jedis.getKeyTag("{bar}foo"), "bar"); // Key tag may appear assertEquals(jedis.getKeyTag("{bar}foo"), "bar"); // Key tag may appear
// anywhere // anywhere
assertEquals(jedis.getKeyTag("f{bar}oo"), "bar"); // Key tag may appear assertEquals(jedis.getKeyTag("f{bar}oo"), "bar"); // Key tag may appear
// anywhere // anywhere
JedisShardInfo s1 = jedis.getShardInfo("abc{bar}"); JedisShardInfo s1 = jedis.getShardInfo("abc{bar}");
JedisShardInfo s2 = jedis.getShardInfo("foo{bar}"); JedisShardInfo s2 = jedis.getShardInfo("foo{bar}");
assertSame(s1, s2); assertSame(s1, s2);
List<String> keys = getKeysDifferentShard(jedis); List<String> keys = getKeysDifferentShard(jedis);
JedisShardInfo s3 = jedis.getShardInfo(keys.get(0)); JedisShardInfo s3 = jedis.getShardInfo(keys.get(0));
JedisShardInfo s4 = jedis.getShardInfo(keys.get(1)); JedisShardInfo s4 = jedis.getShardInfo(keys.get(1));
assertNotSame(s3, s4); assertNotSame(s3, s4);
ShardedJedis jedis2 = new ShardedJedis(shards); ShardedJedis jedis2 = new ShardedJedis(shards);
assertEquals(jedis2.getKeyTag("foo"), "foo"); assertEquals(jedis2.getKeyTag("foo"), "foo");
assertNotSame(jedis2.getKeyTag("foo{bar}"), "bar"); assertNotSame(jedis2.getKeyTag("foo{bar}"), "bar");
JedisShardInfo s5 = jedis2.getShardInfo(keys.get(0) + "{bar}"); JedisShardInfo s5 = jedis2.getShardInfo(keys.get(0) + "{bar}");
JedisShardInfo s6 = jedis2.getShardInfo(keys.get(1) + "{bar}"); JedisShardInfo s6 = jedis2.getShardInfo(keys.get(1) + "{bar}");
assertNotSame(s5, s6); assertNotSame(s5, s6);
} }
@Test @Test
public void testMD5Sharding() { public void testMD5Sharding() {
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(3); List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(3);
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT)); shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT));
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1)); shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1));
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2)); shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2));
Sharded<Jedis, JedisShardInfo> sharded = new Sharded<Jedis, JedisShardInfo>( Sharded<Jedis, JedisShardInfo> sharded = new Sharded<Jedis, JedisShardInfo>(
shards, Hashing.MD5); shards, Hashing.MD5);
int shard_6379 = 0; int shard_6379 = 0;
int shard_6380 = 0; int shard_6380 = 0;
int shard_6381 = 0; int shard_6381 = 0;
for (int i = 0; i < 1000; i++) { for (int i = 0; i < 1000; i++) {
JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer
.toString(i)); .toString(i));
switch (jedisShardInfo.getPort()) { switch (jedisShardInfo.getPort()) {
case 6379: case 6379:
shard_6379++; shard_6379++;
break; break;
case 6380: case 6380:
shard_6380++; shard_6380++;
break; break;
case 6381: case 6381:
shard_6381++; shard_6381++;
break; break;
default: default:
fail("Attempting to use a non-defined shard!!:" fail("Attempting to use a non-defined shard!!:"
+ jedisShardInfo); + jedisShardInfo);
break; break;
} }
} }
assertTrue(shard_6379 > 300 && shard_6379 < 400); assertTrue(shard_6379 > 300 && shard_6379 < 400);
assertTrue(shard_6380 > 300 && shard_6380 < 400); assertTrue(shard_6380 > 300 && shard_6380 < 400);
assertTrue(shard_6381 > 300 && shard_6381 < 400); assertTrue(shard_6381 > 300 && shard_6381 < 400);
} }
@Test @Test
public void testMurmurSharding() { public void testMurmurSharding() {
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(3); List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(3);
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT)); shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT));
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1)); shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1));
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2)); shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2));
Sharded<Jedis, JedisShardInfo> sharded = new Sharded<Jedis, JedisShardInfo>( Sharded<Jedis, JedisShardInfo> sharded = new Sharded<Jedis, JedisShardInfo>(
shards, Hashing.MURMUR_HASH); shards, Hashing.MURMUR_HASH);
int shard_6379 = 0; int shard_6379 = 0;
int shard_6380 = 0; int shard_6380 = 0;
int shard_6381 = 0; int shard_6381 = 0;
for (int i = 0; i < 1000; i++) { for (int i = 0; i < 1000; i++) {
JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer
.toString(i)); .toString(i));
switch (jedisShardInfo.getPort()) { switch (jedisShardInfo.getPort()) {
case 6379: case 6379:
shard_6379++; shard_6379++;
break; break;
case 6380: case 6380:
shard_6380++; shard_6380++;
break; break;
case 6381: case 6381:
shard_6381++; shard_6381++;
break; break;
default: default:
fail("Attempting to use a non-defined shard!!:" fail("Attempting to use a non-defined shard!!:"
+ jedisShardInfo); + jedisShardInfo);
break; break;
} }
} }
assertTrue(shard_6379 > 300 && shard_6379 < 400); assertTrue(shard_6379 > 300 && shard_6379 < 400);
assertTrue(shard_6380 > 300 && shard_6380 < 400); assertTrue(shard_6380 > 300 && shard_6380 < 400);
assertTrue(shard_6381 > 300 && shard_6381 < 400); assertTrue(shard_6381 > 300 && shard_6381 < 400);
} }
@Test @Test
public void testMasterSlaveShardingConsistency() { public void testMasterSlaveShardingConsistency() {
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(3); List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(3);
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT)); shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT));
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1)); shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1));
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2)); shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2));
Sharded<Jedis, JedisShardInfo> sharded = new Sharded<Jedis, JedisShardInfo>( Sharded<Jedis, JedisShardInfo> sharded = new Sharded<Jedis, JedisShardInfo>(
shards, Hashing.MURMUR_HASH); shards, Hashing.MURMUR_HASH);
List<JedisShardInfo> otherShards = new ArrayList<JedisShardInfo>(3); List<JedisShardInfo> otherShards = new ArrayList<JedisShardInfo>(3);
otherShards.add(new JedisShardInfo("otherhost", Protocol.DEFAULT_PORT)); otherShards.add(new JedisShardInfo("otherhost", Protocol.DEFAULT_PORT));
otherShards.add(new JedisShardInfo("otherhost", otherShards.add(new JedisShardInfo("otherhost",
Protocol.DEFAULT_PORT + 1)); Protocol.DEFAULT_PORT + 1));
otherShards.add(new JedisShardInfo("otherhost", otherShards.add(new JedisShardInfo("otherhost",
Protocol.DEFAULT_PORT + 2)); Protocol.DEFAULT_PORT + 2));
Sharded<Jedis, JedisShardInfo> sharded2 = new Sharded<Jedis, JedisShardInfo>( Sharded<Jedis, JedisShardInfo> sharded2 = new Sharded<Jedis, JedisShardInfo>(
otherShards, Hashing.MURMUR_HASH); otherShards, Hashing.MURMUR_HASH);
for (int i = 0; i < 1000; i++) { for (int i = 0; i < 1000; i++) {
JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer
.toString(i)); .toString(i));
JedisShardInfo jedisShardInfo2 = sharded2.getShardInfo(Integer JedisShardInfo jedisShardInfo2 = sharded2.getShardInfo(Integer
.toString(i)); .toString(i));
assertEquals(shards.indexOf(jedisShardInfo), assertEquals(shards.indexOf(jedisShardInfo),
otherShards.indexOf(jedisShardInfo2)); otherShards.indexOf(jedisShardInfo2));
} }
} }
@Test @Test
public void testMasterSlaveShardingConsistencyWithShardNaming() { public void testMasterSlaveShardingConsistencyWithShardNaming() {
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(3); List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(3);
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT, shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT,
"HOST1:1234")); "HOST1:1234"));
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1, shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1,
"HOST2:1234")); "HOST2:1234"));
shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2, shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2,
"HOST3:1234")); "HOST3:1234"));
Sharded<Jedis, JedisShardInfo> sharded = new Sharded<Jedis, JedisShardInfo>( Sharded<Jedis, JedisShardInfo> sharded = new Sharded<Jedis, JedisShardInfo>(
shards, Hashing.MURMUR_HASH); shards, Hashing.MURMUR_HASH);
List<JedisShardInfo> otherShards = new ArrayList<JedisShardInfo>(3); List<JedisShardInfo> otherShards = new ArrayList<JedisShardInfo>(3);
otherShards.add(new JedisShardInfo("otherhost", Protocol.DEFAULT_PORT, otherShards.add(new JedisShardInfo("otherhost", Protocol.DEFAULT_PORT,
"HOST2:1234")); "HOST2:1234"));
otherShards.add(new JedisShardInfo("otherhost", otherShards.add(new JedisShardInfo("otherhost",
Protocol.DEFAULT_PORT + 1, "HOST3:1234")); Protocol.DEFAULT_PORT + 1, "HOST3:1234"));
otherShards.add(new JedisShardInfo("otherhost", otherShards.add(new JedisShardInfo("otherhost",
Protocol.DEFAULT_PORT + 2, "HOST1:1234")); Protocol.DEFAULT_PORT + 2, "HOST1:1234"));
Sharded<Jedis, JedisShardInfo> sharded2 = new Sharded<Jedis, JedisShardInfo>( Sharded<Jedis, JedisShardInfo> sharded2 = new Sharded<Jedis, JedisShardInfo>(
otherShards, Hashing.MURMUR_HASH); otherShards, Hashing.MURMUR_HASH);
for (int i = 0; i < 1000; i++) { for (int i = 0; i < 1000; i++) {
JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer
.toString(i)); .toString(i));
JedisShardInfo jedisShardInfo2 = sharded2.getShardInfo(Integer JedisShardInfo jedisShardInfo2 = sharded2.getShardInfo(Integer
.toString(i)); .toString(i));
assertEquals(jedisShardInfo.getName(), jedisShardInfo2.getName()); assertEquals(jedisShardInfo.getName(), jedisShardInfo2.getName());
} }
} }
@Test @Test
public void checkCloseable() { public void checkCloseable() {
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(); List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(redis1.getHost(), redis1.getPort())); shards.add(new JedisShardInfo(redis1.getHost(), redis1.getPort()));
shards.add(new JedisShardInfo(redis2.getHost(), redis2.getPort())); shards.add(new JedisShardInfo(redis2.getHost(), redis2.getPort()));
shards.get(0).setPassword("foobared"); shards.get(0).setPassword("foobared");
shards.get(1).setPassword("foobared"); shards.get(1).setPassword("foobared");
ShardedJedis jedisShard = new ShardedJedis(shards); ShardedJedis jedisShard = new ShardedJedis(shards);
try { try {
jedisShard.set("shard_closeable", "true"); jedisShard.set("shard_closeable", "true");
} finally { } finally {
jedisShard.close(); jedisShard.close();
} }
for (Jedis jedis : jedisShard.getAllShards()) { for (Jedis jedis : jedisShard.getAllShards()) {
assertTrue(!jedis.isConnected()); assertTrue(!jedis.isConnected());
} }
} }
} }

View File

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

View File

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

View File

@@ -19,33 +19,33 @@ public class HashingBenchmark {
private static final int TOTAL_OPERATIONS = 100000; private static final int TOTAL_OPERATIONS = 100000;
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(), JedisShardInfo shard = new JedisShardInfo(hnp1.getHost(),
hnp1.getPort()); 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());
shard.setPassword("foobared"); shard.setPassword("foobared");
shards.add(shard); shards.add(shard);
ShardedJedis jedis = new ShardedJedis(shards); ShardedJedis jedis = new ShardedJedis(shards);
Collection<Jedis> allShards = jedis.getAllShards(); Collection<Jedis> allShards = jedis.getAllShards();
for (Jedis j : allShards) { for (Jedis j : allShards) {
j.flushAll(); j.flushAll();
} }
long begin = Calendar.getInstance().getTimeInMillis(); long begin = Calendar.getInstance().getTimeInMillis();
for (int n = 0; n <= TOTAL_OPERATIONS; n++) { for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
String key = "foo" + n; String key = "foo" + n;
jedis.set(key, "bar" + n); jedis.set(key, "bar" + n);
jedis.get(key); jedis.get(key);
} }
long elapsed = Calendar.getInstance().getTimeInMillis() - begin; long elapsed = Calendar.getInstance().getTimeInMillis() - begin;
jedis.disconnect(); jedis.disconnect();
System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops"); System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops");
} }
} }

View File

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

View File

@@ -16,49 +16,49 @@ public class PoolBenchmark {
private static final int TOTAL_OPERATIONS = 100000; private static final int TOTAL_OPERATIONS = 100000;
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
Jedis j = new Jedis(hnp.getHost(), hnp.getPort()); Jedis j = new Jedis(hnp.getHost(), hnp.getPort());
j.connect(); j.connect();
j.auth("foobared"); j.auth("foobared");
j.flushAll(); j.flushAll();
j.quit(); j.quit();
j.disconnect(); j.disconnect();
long t = System.currentTimeMillis(); long t = System.currentTimeMillis();
// withoutPool(); // withoutPool();
withPool(); withPool();
long elapsed = System.currentTimeMillis() - t; long elapsed = System.currentTimeMillis() - t;
System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops"); System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops");
} }
private static void withPool() throws Exception { private static void withPool() throws Exception {
final JedisPool pool = new JedisPool(new GenericObjectPoolConfig(), final JedisPool pool = new JedisPool(new GenericObjectPoolConfig(),
hnp.getHost(), hnp.getPort(), 2000, "foobared"); hnp.getHost(), hnp.getPort(), 2000, "foobared");
List<Thread> tds = new ArrayList<Thread>(); List<Thread> tds = new ArrayList<Thread>();
final AtomicInteger ind = new AtomicInteger(); final AtomicInteger ind = new AtomicInteger();
for (int i = 0; i < 50; i++) { for (int i = 0; i < 50; i++) {
Thread hj = new Thread(new Runnable() { Thread hj = new Thread(new Runnable() {
public void run() { public void run() {
for (int i = 0; (i = ind.getAndIncrement()) < TOTAL_OPERATIONS;) { for (int i = 0; (i = ind.getAndIncrement()) < TOTAL_OPERATIONS;) {
try { try {
Jedis j = pool.getResource(); Jedis j = pool.getResource();
final String key = "foo" + i; final String key = "foo" + i;
j.set(key, key); j.set(key, key);
j.get(key); j.get(key);
pool.returnResource(j); pool.returnResource(j);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
}); });
tds.add(hj); tds.add(hj);
hj.start(); hj.start();
} }
for (Thread t : tds) for (Thread t : tds)
t.join(); t.join();
pool.destroy(); pool.destroy();
} }
} }

View File

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

View File

@@ -10,29 +10,29 @@ public class SafeEncoderBenchmark {
private static final int TOTAL_OPERATIONS = 10000000; private static final int TOTAL_OPERATIONS = 10000000;
public static void main(String[] args) throws UnknownHostException, public static void main(String[] args) throws UnknownHostException,
IOException { IOException {
long begin = Calendar.getInstance().getTimeInMillis(); long begin = Calendar.getInstance().getTimeInMillis();
for (int n = 0; n <= TOTAL_OPERATIONS; n++) { for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
SafeEncoder.encode("foo bar!"); SafeEncoder.encode("foo bar!");
} }
long elapsed = Calendar.getInstance().getTimeInMillis() - begin; long elapsed = Calendar.getInstance().getTimeInMillis() - begin;
System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed) System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed)
+ " ops to build byte[]"); + " ops to build byte[]");
begin = Calendar.getInstance().getTimeInMillis(); begin = Calendar.getInstance().getTimeInMillis();
byte[] bytes = "foo bar!".getBytes(); byte[] bytes = "foo bar!".getBytes();
for (int n = 0; n <= TOTAL_OPERATIONS; n++) { for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
SafeEncoder.encode(bytes); SafeEncoder.encode(bytes);
} }
elapsed = Calendar.getInstance().getTimeInMillis() - begin; elapsed = Calendar.getInstance().getTimeInMillis() - begin;
System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed) System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed)
+ " ops to build Strings"); + " ops to build Strings");
} }
} }

View File

@@ -10,30 +10,30 @@ public class ShardedBenchmark {
private static final int TOTAL_OPERATIONS = 10000000; private static final int TOTAL_OPERATIONS = 10000000;
public static void main(String[] args) throws UnknownHostException, public static void main(String[] args) throws UnknownHostException,
IOException { IOException {
long begin = Calendar.getInstance().getTimeInMillis(); long begin = Calendar.getInstance().getTimeInMillis();
for (int n = 0; n <= TOTAL_OPERATIONS; n++) { for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
String key = "foo" + n; String key = "foo" + n;
Hashing.MD5.hash(key); Hashing.MD5.hash(key);
} }
long elapsed = Calendar.getInstance().getTimeInMillis() - begin; long elapsed = Calendar.getInstance().getTimeInMillis() - begin;
System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed) + " MD5 ops"); System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed) + " MD5 ops");
begin = Calendar.getInstance().getTimeInMillis(); begin = Calendar.getInstance().getTimeInMillis();
for (int n = 0; n <= TOTAL_OPERATIONS; n++) { for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
String key = "foo" + n; String key = "foo" + n;
Hashing.MURMUR_HASH.hash(key); Hashing.MURMUR_HASH.hash(key);
} }
elapsed = Calendar.getInstance().getTimeInMillis() - begin; elapsed = Calendar.getInstance().getTimeInMillis() - begin;
System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed) System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed)
+ " Murmur ops"); + " Murmur ops");
} }
} }

View File

@@ -30,560 +30,560 @@ public class AllKindOfValuesCommandsTest extends JedisCommandTestBase {
@Test @Test
public void ping() { public void ping() {
String status = jedis.ping(); String status = jedis.ping();
assertEquals("PONG", status); assertEquals("PONG", status);
} }
@Test @Test
public void exists() { public void exists() {
String status = jedis.set("foo", "bar"); String status = jedis.set("foo", "bar");
assertEquals("OK", status); assertEquals("OK", status);
status = jedis.set(bfoo, bbar); status = jedis.set(bfoo, bbar);
assertEquals("OK", status); assertEquals("OK", status);
boolean reply = jedis.exists("foo"); boolean reply = jedis.exists("foo");
assertTrue(reply); assertTrue(reply);
reply = jedis.exists(bfoo); reply = jedis.exists(bfoo);
assertTrue(reply); assertTrue(reply);
long lreply = jedis.del("foo"); long lreply = jedis.del("foo");
assertEquals(1, lreply); assertEquals(1, lreply);
lreply = jedis.del(bfoo); lreply = jedis.del(bfoo);
assertEquals(1, lreply); assertEquals(1, lreply);
reply = jedis.exists("foo"); reply = jedis.exists("foo");
assertFalse(reply); assertFalse(reply);
reply = jedis.exists(bfoo); reply = jedis.exists(bfoo);
assertFalse(reply); assertFalse(reply);
} }
@Test @Test
public void del() { public void del() {
jedis.set("foo1", "bar1"); jedis.set("foo1", "bar1");
jedis.set("foo2", "bar2"); jedis.set("foo2", "bar2");
jedis.set("foo3", "bar3"); jedis.set("foo3", "bar3");
long reply = jedis.del("foo1", "foo2", "foo3"); long reply = jedis.del("foo1", "foo2", "foo3");
assertEquals(3, reply); assertEquals(3, reply);
Boolean breply = jedis.exists("foo1"); Boolean breply = jedis.exists("foo1");
assertFalse(breply); assertFalse(breply);
breply = jedis.exists("foo2"); breply = jedis.exists("foo2");
assertFalse(breply); assertFalse(breply);
breply = jedis.exists("foo3"); breply = jedis.exists("foo3");
assertFalse(breply); assertFalse(breply);
jedis.set("foo1", "bar1"); jedis.set("foo1", "bar1");
reply = jedis.del("foo1", "foo2"); reply = jedis.del("foo1", "foo2");
assertEquals(1, reply); assertEquals(1, reply);
reply = jedis.del("foo1", "foo2"); reply = jedis.del("foo1", "foo2");
assertEquals(0, reply); assertEquals(0, reply);
// Binary ... // Binary ...
jedis.set(bfoo1, bbar1); jedis.set(bfoo1, bbar1);
jedis.set(bfoo2, bbar2); jedis.set(bfoo2, bbar2);
jedis.set(bfoo3, bbar3); jedis.set(bfoo3, bbar3);
reply = jedis.del(bfoo1, bfoo2, bfoo3); reply = jedis.del(bfoo1, bfoo2, bfoo3);
assertEquals(3, reply); assertEquals(3, reply);
breply = jedis.exists(bfoo1); breply = jedis.exists(bfoo1);
assertFalse(breply); assertFalse(breply);
breply = jedis.exists(bfoo2); breply = jedis.exists(bfoo2);
assertFalse(breply); assertFalse(breply);
breply = jedis.exists(bfoo3); breply = jedis.exists(bfoo3);
assertFalse(breply); assertFalse(breply);
jedis.set(bfoo1, bbar1); jedis.set(bfoo1, bbar1);
reply = jedis.del(bfoo1, bfoo2); reply = jedis.del(bfoo1, bfoo2);
assertEquals(1, reply); assertEquals(1, reply);
reply = jedis.del(bfoo1, bfoo2); reply = jedis.del(bfoo1, bfoo2);
assertEquals(0, reply); assertEquals(0, reply);
} }
@Test @Test
public void type() { public void type() {
jedis.set("foo", "bar"); jedis.set("foo", "bar");
String status = jedis.type("foo"); String status = jedis.type("foo");
assertEquals("string", status); assertEquals("string", status);
// Binary // Binary
jedis.set(bfoo, bbar); jedis.set(bfoo, bbar);
status = jedis.type(bfoo); status = jedis.type(bfoo);
assertEquals("string", status); assertEquals("string", status);
} }
@Test @Test
public void keys() { public void keys() {
jedis.set("foo", "bar"); jedis.set("foo", "bar");
jedis.set("foobar", "bar"); jedis.set("foobar", "bar");
Set<String> keys = jedis.keys("foo*"); Set<String> keys = jedis.keys("foo*");
Set<String> expected = new HashSet<String>(); Set<String> expected = new HashSet<String>();
expected.add("foo"); expected.add("foo");
expected.add("foobar"); expected.add("foobar");
assertEquals(expected, keys); assertEquals(expected, keys);
expected = new HashSet<String>(); expected = new HashSet<String>();
keys = jedis.keys("bar*"); keys = jedis.keys("bar*");
assertEquals(expected, keys); assertEquals(expected, keys);
// Binary // Binary
jedis.set(bfoo, bbar); jedis.set(bfoo, bbar);
jedis.set(bfoobar, bbar); jedis.set(bfoobar, bbar);
Set<byte[]> bkeys = jedis.keys(bfoostar); Set<byte[]> bkeys = jedis.keys(bfoostar);
assertEquals(2, bkeys.size()); assertEquals(2, bkeys.size());
assertTrue(setContains(bkeys, bfoo)); assertTrue(setContains(bkeys, bfoo));
assertTrue(setContains(bkeys, bfoobar)); assertTrue(setContains(bkeys, bfoobar));
bkeys = jedis.keys(bbarstar); bkeys = jedis.keys(bbarstar);
assertEquals(0, bkeys.size()); assertEquals(0, bkeys.size());
} }
@Test @Test
public void randomKey() { public void randomKey() {
assertEquals(null, jedis.randomKey()); assertEquals(null, jedis.randomKey());
jedis.set("foo", "bar"); jedis.set("foo", "bar");
assertEquals("foo", jedis.randomKey()); assertEquals("foo", jedis.randomKey());
jedis.set("bar", "foo"); jedis.set("bar", "foo");
String randomkey = jedis.randomKey(); String randomkey = jedis.randomKey();
assertTrue(randomkey.equals("foo") || randomkey.equals("bar")); assertTrue(randomkey.equals("foo") || randomkey.equals("bar"));
// Binary // Binary
jedis.del("foo"); jedis.del("foo");
jedis.del("bar"); jedis.del("bar");
assertEquals(null, jedis.randomKey()); assertEquals(null, jedis.randomKey());
jedis.set(bfoo, bbar); jedis.set(bfoo, bbar);
assertArrayEquals(bfoo, jedis.randomBinaryKey()); assertArrayEquals(bfoo, jedis.randomBinaryKey());
jedis.set(bbar, bfoo); jedis.set(bbar, bfoo);
byte[] randomBkey = jedis.randomBinaryKey(); byte[] randomBkey = jedis.randomBinaryKey();
assertTrue(Arrays.equals(randomBkey, bfoo) assertTrue(Arrays.equals(randomBkey, bfoo)
|| Arrays.equals(randomBkey, bbar)); || Arrays.equals(randomBkey, bbar));
} }
@Test @Test
public void rename() { public void rename() {
jedis.set("foo", "bar"); jedis.set("foo", "bar");
String status = jedis.rename("foo", "bar"); String status = jedis.rename("foo", "bar");
assertEquals("OK", status); assertEquals("OK", status);
String value = jedis.get("foo"); String value = jedis.get("foo");
assertEquals(null, value); assertEquals(null, value);
value = jedis.get("bar"); value = jedis.get("bar");
assertEquals("bar", value); assertEquals("bar", value);
// Binary // Binary
jedis.set(bfoo, bbar); jedis.set(bfoo, bbar);
String bstatus = jedis.rename(bfoo, bbar); String bstatus = jedis.rename(bfoo, bbar);
assertEquals("OK", bstatus); assertEquals("OK", bstatus);
byte[] bvalue = jedis.get(bfoo); byte[] bvalue = jedis.get(bfoo);
assertEquals(null, bvalue); assertEquals(null, bvalue);
bvalue = jedis.get(bbar); bvalue = jedis.get(bbar);
assertArrayEquals(bbar, bvalue); assertArrayEquals(bbar, bvalue);
} }
@Test @Test
public void renameOldAndNewAreTheSame() { public void renameOldAndNewAreTheSame() {
try { try {
jedis.set("foo", "bar"); jedis.set("foo", "bar");
jedis.rename("foo", "foo"); jedis.rename("foo", "foo");
fail("JedisDataException expected"); fail("JedisDataException expected");
} catch (final JedisDataException e) { } catch (final JedisDataException e) {
} }
// Binary // Binary
try { try {
jedis.set(bfoo, bbar); jedis.set(bfoo, bbar);
jedis.rename(bfoo, bfoo); jedis.rename(bfoo, bfoo);
fail("JedisDataException expected"); fail("JedisDataException expected");
} catch (final JedisDataException e) { } catch (final JedisDataException e) {
} }
} }
@Test @Test
public void renamenx() { public void renamenx() {
jedis.set("foo", "bar"); jedis.set("foo", "bar");
long status = jedis.renamenx("foo", "bar"); long status = jedis.renamenx("foo", "bar");
assertEquals(1, status); assertEquals(1, status);
jedis.set("foo", "bar"); jedis.set("foo", "bar");
status = jedis.renamenx("foo", "bar"); status = jedis.renamenx("foo", "bar");
assertEquals(0, status); assertEquals(0, status);
// Binary // Binary
jedis.set(bfoo, bbar); jedis.set(bfoo, bbar);
long bstatus = jedis.renamenx(bfoo, bbar); long bstatus = jedis.renamenx(bfoo, bbar);
assertEquals(1, bstatus); assertEquals(1, bstatus);
jedis.set(bfoo, bbar); jedis.set(bfoo, bbar);
bstatus = jedis.renamenx(bfoo, bbar); bstatus = jedis.renamenx(bfoo, bbar);
assertEquals(0, bstatus); assertEquals(0, bstatus);
} }
@Test @Test
public void dbSize() { public void dbSize() {
long size = jedis.dbSize(); long size = jedis.dbSize();
assertEquals(0, size); assertEquals(0, size);
jedis.set("foo", "bar"); jedis.set("foo", "bar");
size = jedis.dbSize(); size = jedis.dbSize();
assertEquals(1, size); assertEquals(1, size);
// Binary // Binary
jedis.set(bfoo, bbar); jedis.set(bfoo, bbar);
size = jedis.dbSize(); size = jedis.dbSize();
assertEquals(2, size); assertEquals(2, size);
} }
@Test @Test
public void expire() { public void expire() {
long status = jedis.expire("foo", 20); long status = jedis.expire("foo", 20);
assertEquals(0, status); assertEquals(0, status);
jedis.set("foo", "bar"); jedis.set("foo", "bar");
status = jedis.expire("foo", 20); status = jedis.expire("foo", 20);
assertEquals(1, status); assertEquals(1, status);
// Binary // Binary
long bstatus = jedis.expire(bfoo, 20); long bstatus = jedis.expire(bfoo, 20);
assertEquals(0, bstatus); assertEquals(0, bstatus);
jedis.set(bfoo, bbar); jedis.set(bfoo, bbar);
bstatus = jedis.expire(bfoo, 20); bstatus = jedis.expire(bfoo, 20);
assertEquals(1, bstatus); assertEquals(1, bstatus);
} }
@Test @Test
public void expireAt() { public void expireAt() {
long unixTime = (System.currentTimeMillis() / 1000L) + 20; long unixTime = (System.currentTimeMillis() / 1000L) + 20;
long status = jedis.expireAt("foo", unixTime); long status = jedis.expireAt("foo", unixTime);
assertEquals(0, status); assertEquals(0, status);
jedis.set("foo", "bar"); jedis.set("foo", "bar");
unixTime = (System.currentTimeMillis() / 1000L) + 20; unixTime = (System.currentTimeMillis() / 1000L) + 20;
status = jedis.expireAt("foo", unixTime); status = jedis.expireAt("foo", unixTime);
assertEquals(1, status); assertEquals(1, status);
// Binary // Binary
long bstatus = jedis.expireAt(bfoo, unixTime); long bstatus = jedis.expireAt(bfoo, unixTime);
assertEquals(0, bstatus); assertEquals(0, bstatus);
jedis.set(bfoo, bbar); jedis.set(bfoo, bbar);
unixTime = (System.currentTimeMillis() / 1000L) + 20; unixTime = (System.currentTimeMillis() / 1000L) + 20;
bstatus = jedis.expireAt(bfoo, unixTime); bstatus = jedis.expireAt(bfoo, unixTime);
assertEquals(1, bstatus); assertEquals(1, bstatus);
} }
@Test @Test
public void ttl() { public void ttl() {
long ttl = jedis.ttl("foo"); long ttl = jedis.ttl("foo");
assertEquals(-2, ttl); assertEquals(-2, ttl);
jedis.set("foo", "bar"); jedis.set("foo", "bar");
ttl = jedis.ttl("foo"); ttl = jedis.ttl("foo");
assertEquals(-1, ttl); assertEquals(-1, ttl);
jedis.expire("foo", 20); jedis.expire("foo", 20);
ttl = jedis.ttl("foo"); ttl = jedis.ttl("foo");
assertTrue(ttl >= 0 && ttl <= 20); assertTrue(ttl >= 0 && ttl <= 20);
// Binary // Binary
long bttl = jedis.ttl(bfoo); long bttl = jedis.ttl(bfoo);
assertEquals(-2, bttl); assertEquals(-2, bttl);
jedis.set(bfoo, bbar); jedis.set(bfoo, bbar);
bttl = jedis.ttl(bfoo); bttl = jedis.ttl(bfoo);
assertEquals(-1, bttl); assertEquals(-1, bttl);
jedis.expire(bfoo, 20); jedis.expire(bfoo, 20);
bttl = jedis.ttl(bfoo); bttl = jedis.ttl(bfoo);
assertTrue(bttl >= 0 && bttl <= 20); assertTrue(bttl >= 0 && bttl <= 20);
} }
@Test @Test
public void select() { public void select() {
jedis.set("foo", "bar"); jedis.set("foo", "bar");
String status = jedis.select(1); String status = jedis.select(1);
assertEquals("OK", status); assertEquals("OK", status);
assertEquals(null, jedis.get("foo")); assertEquals(null, jedis.get("foo"));
status = jedis.select(0); status = jedis.select(0);
assertEquals("OK", status); assertEquals("OK", status);
assertEquals("bar", jedis.get("foo")); assertEquals("bar", jedis.get("foo"));
// Binary // Binary
jedis.set(bfoo, bbar); jedis.set(bfoo, bbar);
String bstatus = jedis.select(1); String bstatus = jedis.select(1);
assertEquals("OK", bstatus); assertEquals("OK", bstatus);
assertEquals(null, jedis.get(bfoo)); assertEquals(null, jedis.get(bfoo));
bstatus = jedis.select(0); bstatus = jedis.select(0);
assertEquals("OK", bstatus); assertEquals("OK", bstatus);
assertArrayEquals(bbar, jedis.get(bfoo)); assertArrayEquals(bbar, jedis.get(bfoo));
} }
@Test @Test
public void getDB() { public void getDB() {
assertEquals(0, jedis.getDB().longValue()); assertEquals(0, jedis.getDB().longValue());
jedis.select(1); jedis.select(1);
assertEquals(1, jedis.getDB().longValue()); assertEquals(1, jedis.getDB().longValue());
} }
@Test @Test
public void move() { public void move() {
long status = jedis.move("foo", 1); long status = jedis.move("foo", 1);
assertEquals(0, status); assertEquals(0, status);
jedis.set("foo", "bar"); jedis.set("foo", "bar");
status = jedis.move("foo", 1); status = jedis.move("foo", 1);
assertEquals(1, status); assertEquals(1, status);
assertEquals(null, jedis.get("foo")); assertEquals(null, jedis.get("foo"));
jedis.select(1); jedis.select(1);
assertEquals("bar", jedis.get("foo")); assertEquals("bar", jedis.get("foo"));
// Binary // Binary
jedis.select(0); jedis.select(0);
long bstatus = jedis.move(bfoo, 1); long bstatus = jedis.move(bfoo, 1);
assertEquals(0, bstatus); assertEquals(0, bstatus);
jedis.set(bfoo, bbar); jedis.set(bfoo, bbar);
bstatus = jedis.move(bfoo, 1); bstatus = jedis.move(bfoo, 1);
assertEquals(1, bstatus); assertEquals(1, bstatus);
assertEquals(null, jedis.get(bfoo)); assertEquals(null, jedis.get(bfoo));
jedis.select(1); jedis.select(1);
assertArrayEquals(bbar, jedis.get(bfoo)); assertArrayEquals(bbar, jedis.get(bfoo));
} }
@Test @Test
public void flushDB() { public void flushDB() {
jedis.set("foo", "bar"); jedis.set("foo", "bar");
assertEquals(1, jedis.dbSize().intValue()); assertEquals(1, jedis.dbSize().intValue());
jedis.set("bar", "foo"); jedis.set("bar", "foo");
jedis.move("bar", 1); jedis.move("bar", 1);
String status = jedis.flushDB(); String status = jedis.flushDB();
assertEquals("OK", status); assertEquals("OK", status);
assertEquals(0, jedis.dbSize().intValue()); assertEquals(0, jedis.dbSize().intValue());
jedis.select(1); jedis.select(1);
assertEquals(1, jedis.dbSize().intValue()); assertEquals(1, jedis.dbSize().intValue());
jedis.del("bar"); jedis.del("bar");
// Binary // Binary
jedis.select(0); jedis.select(0);
jedis.set(bfoo, bbar); jedis.set(bfoo, bbar);
assertEquals(1, jedis.dbSize().intValue()); assertEquals(1, jedis.dbSize().intValue());
jedis.set(bbar, bfoo); jedis.set(bbar, bfoo);
jedis.move(bbar, 1); jedis.move(bbar, 1);
String bstatus = jedis.flushDB(); String bstatus = jedis.flushDB();
assertEquals("OK", bstatus); assertEquals("OK", bstatus);
assertEquals(0, jedis.dbSize().intValue()); assertEquals(0, jedis.dbSize().intValue());
jedis.select(1); jedis.select(1);
assertEquals(1, jedis.dbSize().intValue()); assertEquals(1, jedis.dbSize().intValue());
} }
@Test @Test
public void flushAll() { public void flushAll() {
jedis.set("foo", "bar"); jedis.set("foo", "bar");
assertEquals(1, jedis.dbSize().intValue()); assertEquals(1, jedis.dbSize().intValue());
jedis.set("bar", "foo"); jedis.set("bar", "foo");
jedis.move("bar", 1); jedis.move("bar", 1);
String status = jedis.flushAll(); String status = jedis.flushAll();
assertEquals("OK", status); assertEquals("OK", status);
assertEquals(0, jedis.dbSize().intValue()); assertEquals(0, jedis.dbSize().intValue());
jedis.select(1); jedis.select(1);
assertEquals(0, jedis.dbSize().intValue()); assertEquals(0, jedis.dbSize().intValue());
// Binary // Binary
jedis.select(0); jedis.select(0);
jedis.set(bfoo, bbar); jedis.set(bfoo, bbar);
assertEquals(1, jedis.dbSize().intValue()); assertEquals(1, jedis.dbSize().intValue());
jedis.set(bbar, bfoo); jedis.set(bbar, bfoo);
jedis.move(bbar, 1); jedis.move(bbar, 1);
String bstatus = jedis.flushAll(); String bstatus = jedis.flushAll();
assertEquals("OK", bstatus); assertEquals("OK", bstatus);
assertEquals(0, jedis.dbSize().intValue()); assertEquals(0, jedis.dbSize().intValue());
jedis.select(1); jedis.select(1);
assertEquals(0, jedis.dbSize().intValue()); assertEquals(0, jedis.dbSize().intValue());
} }
@Test @Test
public void persist() { public void persist() {
jedis.setex("foo", 60 * 60, "bar"); jedis.setex("foo", 60 * 60, "bar");
assertTrue(jedis.ttl("foo") > 0); assertTrue(jedis.ttl("foo") > 0);
long status = jedis.persist("foo"); long status = jedis.persist("foo");
assertEquals(1, status); assertEquals(1, status);
assertEquals(-1, jedis.ttl("foo").intValue()); assertEquals(-1, jedis.ttl("foo").intValue());
// Binary // Binary
jedis.setex(bfoo, 60 * 60, bbar); jedis.setex(bfoo, 60 * 60, bbar);
assertTrue(jedis.ttl(bfoo) > 0); assertTrue(jedis.ttl(bfoo) > 0);
long bstatus = jedis.persist(bfoo); long bstatus = jedis.persist(bfoo);
assertEquals(1, bstatus); assertEquals(1, bstatus);
assertEquals(-1, jedis.ttl(bfoo).intValue()); assertEquals(-1, jedis.ttl(bfoo).intValue());
} }
@Test @Test
public void echo() { public void echo() {
String result = jedis.echo("hello world"); String result = jedis.echo("hello world");
assertEquals("hello world", result); assertEquals("hello world", result);
// Binary // Binary
byte[] bresult = jedis.echo(SafeEncoder.encode("hello world")); byte[] bresult = jedis.echo(SafeEncoder.encode("hello world"));
assertArrayEquals(SafeEncoder.encode("hello world"), bresult); assertArrayEquals(SafeEncoder.encode("hello world"), bresult);
} }
@Test @Test
public void dumpAndRestore() { public void dumpAndRestore() {
jedis.set("foo1", "bar1"); jedis.set("foo1", "bar1");
byte[] sv = jedis.dump("foo1"); byte[] sv = jedis.dump("foo1");
jedis.restore("foo2", 0, sv); jedis.restore("foo2", 0, sv);
assertTrue(jedis.exists("foo2")); assertTrue(jedis.exists("foo2"));
} }
@Test @Test
public void pexpire() { public void pexpire() {
long status = jedis.pexpire("foo", 10000); long status = jedis.pexpire("foo", 10000);
assertEquals(0, status); assertEquals(0, status);
jedis.set("foo1", "bar1"); jedis.set("foo1", "bar1");
status = jedis.pexpire("foo1", 10000); status = jedis.pexpire("foo1", 10000);
assertEquals(1, status); assertEquals(1, status);
jedis.set("foo2", "bar2"); jedis.set("foo2", "bar2");
status = jedis.pexpire("foo2", 200000000000L); status = jedis.pexpire("foo2", 200000000000L);
assertEquals(1, status); assertEquals(1, status);
long pttl = jedis.pttl("foo2"); long pttl = jedis.pttl("foo2");
assertTrue(pttl > 100000000000L); assertTrue(pttl > 100000000000L);
} }
@Test @Test
public void pexpireAt() { public void pexpireAt() {
long unixTime = (System.currentTimeMillis()) + 10000; long unixTime = (System.currentTimeMillis()) + 10000;
long status = jedis.pexpireAt("foo", unixTime); long status = jedis.pexpireAt("foo", unixTime);
assertEquals(0, status); assertEquals(0, status);
jedis.set("foo", "bar"); jedis.set("foo", "bar");
unixTime = (System.currentTimeMillis()) + 10000; unixTime = (System.currentTimeMillis()) + 10000;
status = jedis.pexpireAt("foo", unixTime); status = jedis.pexpireAt("foo", unixTime);
assertEquals(1, status); assertEquals(1, status);
} }
@Test @Test
public void pttl() { public void pttl() {
long pttl = jedis.pttl("foo"); long pttl = jedis.pttl("foo");
assertEquals(-2, pttl); assertEquals(-2, pttl);
jedis.set("foo", "bar"); jedis.set("foo", "bar");
pttl = jedis.pttl("foo"); pttl = jedis.pttl("foo");
assertEquals(-1, pttl); assertEquals(-1, pttl);
jedis.pexpire("foo", 20000); jedis.pexpire("foo", 20000);
pttl = jedis.pttl("foo"); pttl = jedis.pttl("foo");
assertTrue(pttl >= 0 && pttl <= 20000); assertTrue(pttl >= 0 && pttl <= 20000);
} }
@Test @Test
public void scan() { public void scan() {
jedis.set("b", "b"); jedis.set("b", "b");
jedis.set("a", "a"); jedis.set("a", "a");
ScanResult<String> result = jedis.scan(SCAN_POINTER_START); ScanResult<String> result = jedis.scan(SCAN_POINTER_START);
assertEquals(SCAN_POINTER_START, result.getCursor()); assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty()); assertFalse(result.getResult().isEmpty());
// binary // binary
ScanResult<byte[]> bResult = jedis.scan(SCAN_POINTER_START_BINARY); ScanResult<byte[]> bResult = jedis.scan(SCAN_POINTER_START_BINARY);
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty()); assertFalse(bResult.getResult().isEmpty());
} }
@Test @Test
public void scanMatch() { public void scanMatch() {
ScanParams params = new ScanParams(); ScanParams params = new ScanParams();
params.match("a*"); params.match("a*");
jedis.set("b", "b"); jedis.set("b", "b");
jedis.set("a", "a"); jedis.set("a", "a");
jedis.set("aa", "aa"); jedis.set("aa", "aa");
ScanResult<String> result = jedis.scan(SCAN_POINTER_START, params); ScanResult<String> result = jedis.scan(SCAN_POINTER_START, params);
assertEquals(SCAN_POINTER_START, result.getCursor()); assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty()); assertFalse(result.getResult().isEmpty());
// binary // binary
params = new ScanParams(); params = new ScanParams();
params.match(bfoostar); params.match(bfoostar);
jedis.set(bfoo1, bbar); jedis.set(bfoo1, bbar);
jedis.set(bfoo2, bbar); jedis.set(bfoo2, bbar);
jedis.set(bfoo3, bbar); jedis.set(bfoo3, bbar);
ScanResult<byte[]> bResult = jedis.scan(SCAN_POINTER_START_BINARY, ScanResult<byte[]> bResult = jedis.scan(SCAN_POINTER_START_BINARY,
params); params);
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty()); assertFalse(bResult.getResult().isEmpty());
} }
@Test @Test
public void scanCount() { public void scanCount() {
ScanParams params = new ScanParams(); ScanParams params = new ScanParams();
params.count(2); params.count(2);
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
jedis.set("a" + i, "a" + i); jedis.set("a" + i, "a" + i);
} }
ScanResult<String> result = jedis.scan(SCAN_POINTER_START, params); ScanResult<String> result = jedis.scan(SCAN_POINTER_START, params);
assertFalse(result.getResult().isEmpty()); assertFalse(result.getResult().isEmpty());
// binary // binary
params = new ScanParams(); params = new ScanParams();
params.count(2); params.count(2);
jedis.set(bfoo1, bbar); jedis.set(bfoo1, bbar);
jedis.set(bfoo2, bbar); jedis.set(bfoo2, bbar);
jedis.set(bfoo3, bbar); jedis.set(bfoo3, bbar);
ScanResult<byte[]> bResult = jedis.scan(SCAN_POINTER_START_BINARY, ScanResult<byte[]> bResult = jedis.scan(SCAN_POINTER_START_BINARY,
params); params);
assertFalse(bResult.getResult().isEmpty()); assertFalse(bResult.getResult().isEmpty());
} }
} }

View File

@@ -23,260 +23,260 @@ public class BinaryValuesCommandsTest extends JedisCommandTestBase {
@Before @Before
public void startUp() { public void startUp() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (int n = 0; n < 1000; n++) { for (int n = 0; n < 1000; n++) {
sb.append("A"); sb.append("A");
} }
binaryValue = sb.toString().getBytes(); binaryValue = sb.toString().getBytes();
} }
@Test @Test
public void setAndGet() { public void setAndGet() {
String status = jedis.set(bfoo, binaryValue); String status = jedis.set(bfoo, binaryValue);
assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); assertTrue(Keyword.OK.name().equalsIgnoreCase(status));
byte[] value = jedis.get(bfoo); byte[] value = jedis.get(bfoo);
assertTrue(Arrays.equals(binaryValue, value)); assertTrue(Arrays.equals(binaryValue, value));
assertNull(jedis.get(bbar)); assertNull(jedis.get(bbar));
} }
@Test @Test
public void setNxExAndGet() { public void setNxExAndGet() {
String status = jedis.set(bfoo, binaryValue, bnx, bex, expireSeconds); String status = jedis.set(bfoo, binaryValue, bnx, bex, expireSeconds);
assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); assertTrue(Keyword.OK.name().equalsIgnoreCase(status));
byte[] value = jedis.get(bfoo); byte[] value = jedis.get(bfoo);
assertTrue(Arrays.equals(binaryValue, value)); assertTrue(Arrays.equals(binaryValue, value));
assertNull(jedis.get(bbar)); assertNull(jedis.get(bbar));
} }
@Test @Test
public void setIfNotExistAndGet() { public void setIfNotExistAndGet() {
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, String statusFail = jedis.set(bfoo, binaryValue, bnx, bex,
expireSeconds); expireSeconds);
assertNull(statusFail); assertNull(statusFail);
byte[] value = jedis.get(bfoo); byte[] value = jedis.get(bfoo);
assertTrue(Arrays.equals(binaryValue, value)); assertTrue(Arrays.equals(binaryValue, value));
assertNull(jedis.get(bbar)); assertNull(jedis.get(bbar));
} }
@Test @Test
public void setIfExistAndGet() { public void setIfExistAndGet() {
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, String statusSuccess = jedis.set(bfoo, binaryValue, bxx, bex,
expireSeconds); expireSeconds);
assertTrue(Keyword.OK.name().equalsIgnoreCase(statusSuccess)); assertTrue(Keyword.OK.name().equalsIgnoreCase(statusSuccess));
byte[] value = jedis.get(bfoo); byte[] value = jedis.get(bfoo);
assertTrue(Arrays.equals(binaryValue, value)); assertTrue(Arrays.equals(binaryValue, value));
assertNull(jedis.get(bbar)); assertNull(jedis.get(bbar));
} }
@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, String statusFail = jedis.set(bfoo, binaryValue, bxx, bex,
expireSeconds); expireSeconds);
assertNull(statusFail); assertNull(statusFail);
} }
@Test @Test
public void setAndExpireMillis() { public void setAndExpireMillis() {
String status = jedis.set(bfoo, binaryValue, bnx, bpx, expireMillis); String status = jedis.set(bfoo, binaryValue, bnx, bpx, expireMillis);
assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); assertTrue(Keyword.OK.name().equalsIgnoreCase(status));
long ttl = jedis.ttl(bfoo); long ttl = jedis.ttl(bfoo);
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);
assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); assertTrue(Keyword.OK.name().equalsIgnoreCase(status));
long ttl = jedis.ttl(bfoo); long ttl = jedis.ttl(bfoo);
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);
assertNull(value); assertNull(value);
value = jedis.get(bfoo); value = jedis.get(bfoo);
assertTrue(Arrays.equals(binaryValue, value)); assertTrue(Arrays.equals(binaryValue, value));
} }
@Test @Test
public void mget() { public void mget() {
List<byte[]> values = jedis.mget(bfoo, bbar); List<byte[]> values = jedis.mget(bfoo, bbar);
List<byte[]> expected = new ArrayList<byte[]>(); List<byte[]> expected = new ArrayList<byte[]>();
expected.add(null); expected.add(null);
expected.add(null); expected.add(null);
assertEquals(expected, values); assertEquals(expected, values);
jedis.set(bfoo, binaryValue); jedis.set(bfoo, binaryValue);
expected = new ArrayList<byte[]>(); expected = new ArrayList<byte[]>();
expected.add(binaryValue); expected.add(binaryValue);
expected.add(null); expected.add(null);
values = jedis.mget(bfoo, bbar); values = jedis.mget(bfoo, bbar);
assertEquals(expected, values); assertEquals(expected, values);
jedis.set(bbar, bfoo); jedis.set(bbar, bfoo);
expected = new ArrayList<byte[]>(); expected = new ArrayList<byte[]>();
expected.add(binaryValue); expected.add(binaryValue);
expected.add(bfoo); expected.add(bfoo);
values = jedis.mget(bfoo, bbar); values = jedis.mget(bfoo, bbar);
assertEquals(expected, values); assertEquals(expected, values);
} }
@Test @Test
public void setnx() { public void setnx() {
long status = jedis.setnx(bfoo, binaryValue); long status = jedis.setnx(bfoo, binaryValue);
assertEquals(1, status); assertEquals(1, status);
assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo))); assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo)));
status = jedis.setnx(bfoo, bbar); status = jedis.setnx(bfoo, bbar);
assertEquals(0, status); assertEquals(0, status);
assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo))); assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo)));
} }
@Test @Test
public void setex() { public void setex() {
String status = jedis.setex(bfoo, 20, binaryValue); String status = jedis.setex(bfoo, 20, binaryValue);
assertEquals(Keyword.OK.name(), status); assertEquals(Keyword.OK.name(), status);
long ttl = jedis.ttl(bfoo); long ttl = jedis.ttl(bfoo);
assertTrue(ttl > 0 && ttl <= 20); assertTrue(ttl > 0 && ttl <= 20);
} }
@Test @Test
public void mset() { public void mset() {
String status = jedis.mset(bfoo, binaryValue, bbar, bfoo); String status = jedis.mset(bfoo, binaryValue, bbar, bfoo);
assertEquals(Keyword.OK.name(), status); assertEquals(Keyword.OK.name(), status);
assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo))); assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo)));
assertTrue(Arrays.equals(bfoo, jedis.get(bbar))); assertTrue(Arrays.equals(bfoo, jedis.get(bbar)));
} }
@Test @Test
public void msetnx() { public void msetnx() {
long status = jedis.msetnx(bfoo, binaryValue, bbar, bfoo); long status = jedis.msetnx(bfoo, binaryValue, bbar, bfoo);
assertEquals(1, status); assertEquals(1, status);
assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo))); assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo)));
assertTrue(Arrays.equals(bfoo, jedis.get(bbar))); assertTrue(Arrays.equals(bfoo, jedis.get(bbar)));
status = jedis.msetnx(bfoo, bbar, "bar2".getBytes(), "foo2".getBytes()); status = jedis.msetnx(bfoo, bbar, "bar2".getBytes(), "foo2".getBytes());
assertEquals(0, status); assertEquals(0, status);
assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo))); assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo)));
assertTrue(Arrays.equals(bfoo, jedis.get(bbar))); assertTrue(Arrays.equals(bfoo, jedis.get(bbar)));
} }
@Test(expected = JedisDataException.class) @Test(expected = JedisDataException.class)
public void incrWrongValue() { public void incrWrongValue() {
jedis.set(bfoo, binaryValue); jedis.set(bfoo, binaryValue);
jedis.incr(bfoo); jedis.incr(bfoo);
} }
@Test @Test
public void incr() { public void incr() {
long value = jedis.incr(bfoo); long value = jedis.incr(bfoo);
assertEquals(1, value); assertEquals(1, value);
value = jedis.incr(bfoo); value = jedis.incr(bfoo);
assertEquals(2, value); assertEquals(2, value);
} }
@Test(expected = JedisDataException.class) @Test(expected = JedisDataException.class)
public void incrByWrongValue() { public void incrByWrongValue() {
jedis.set(bfoo, binaryValue); jedis.set(bfoo, binaryValue);
jedis.incrBy(bfoo, 2); jedis.incrBy(bfoo, 2);
} }
@Test @Test
public void incrBy() { public void incrBy() {
long value = jedis.incrBy(bfoo, 2); long value = jedis.incrBy(bfoo, 2);
assertEquals(2, value); assertEquals(2, value);
value = jedis.incrBy(bfoo, 2); value = jedis.incrBy(bfoo, 2);
assertEquals(4, value); assertEquals(4, value);
} }
@Test(expected = JedisDataException.class) @Test(expected = JedisDataException.class)
public void decrWrongValue() { public void decrWrongValue() {
jedis.set(bfoo, binaryValue); jedis.set(bfoo, binaryValue);
jedis.decr(bfoo); jedis.decr(bfoo);
} }
@Test @Test
public void decr() { public void decr() {
long value = jedis.decr(bfoo); long value = jedis.decr(bfoo);
assertEquals(-1, value); assertEquals(-1, value);
value = jedis.decr(bfoo); value = jedis.decr(bfoo);
assertEquals(-2, value); assertEquals(-2, value);
} }
@Test(expected = JedisDataException.class) @Test(expected = JedisDataException.class)
public void decrByWrongValue() { public void decrByWrongValue() {
jedis.set(bfoo, binaryValue); jedis.set(bfoo, binaryValue);
jedis.decrBy(bfoo, 2); jedis.decrBy(bfoo, 2);
} }
@Test @Test
public void decrBy() { public void decrBy() {
long value = jedis.decrBy(bfoo, 2); long value = jedis.decrBy(bfoo, 2);
assertEquals(-2, value); assertEquals(-2, value);
value = jedis.decrBy(bfoo, 2); value = jedis.decrBy(bfoo, 2);
assertEquals(-4, value); assertEquals(-4, value);
} }
@Test @Test
public void append() { public void append() {
byte[] first512 = new byte[512]; byte[] first512 = new byte[512];
System.arraycopy(binaryValue, 0, first512, 0, 512); System.arraycopy(binaryValue, 0, first512, 0, 512);
long value = jedis.append(bfoo, first512); long value = jedis.append(bfoo, first512);
assertEquals(512, value); assertEquals(512, value);
assertTrue(Arrays.equals(first512, jedis.get(bfoo))); assertTrue(Arrays.equals(first512, jedis.get(bfoo)));
byte[] rest = new byte[binaryValue.length - 512]; byte[] rest = new byte[binaryValue.length - 512];
System.arraycopy(binaryValue, 512, rest, 0, binaryValue.length - 512); System.arraycopy(binaryValue, 512, rest, 0, binaryValue.length - 512);
value = jedis.append(bfoo, rest); value = jedis.append(bfoo, rest);
assertEquals(binaryValue.length, value); assertEquals(binaryValue.length, value);
assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo))); assertTrue(Arrays.equals(binaryValue, jedis.get(bfoo)));
} }
@Test @Test
public void substr() { public void substr() {
jedis.set(bfoo, binaryValue); jedis.set(bfoo, binaryValue);
byte[] first512 = new byte[512]; byte[] first512 = new byte[512];
System.arraycopy(binaryValue, 0, first512, 0, 512); System.arraycopy(binaryValue, 0, first512, 0, 512);
byte[] rfirst512 = jedis.substr(bfoo, 0, 511); byte[] rfirst512 = jedis.substr(bfoo, 0, 511);
assertTrue(Arrays.equals(first512, rfirst512)); assertTrue(Arrays.equals(first512, rfirst512));
byte[] last512 = new byte[512]; byte[] last512 = new byte[512];
System.arraycopy(binaryValue, binaryValue.length - 512, last512, 0, 512); System.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, assertTrue(Arrays.equals(last512,
jedis.substr(bfoo, binaryValue.length - 512, 100000))); jedis.substr(bfoo, binaryValue.length - 512, 100000)));
} }
@Test @Test
public void strlen() { public void strlen() {
jedis.set(bfoo, binaryValue); jedis.set(bfoo, binaryValue);
assertEquals(binaryValue.length, jedis.strlen(bfoo).intValue()); assertEquals(binaryValue.length, jedis.strlen(bfoo).intValue());
} }
} }

View File

@@ -9,189 +9,189 @@ import redis.clients.jedis.Protocol;
public class BitCommandsTest extends JedisCommandTestBase { public class BitCommandsTest extends JedisCommandTestBase {
@Test @Test
public void setAndgetbit() { public void setAndgetbit() {
boolean bit = jedis.setbit("foo", 0, true); boolean bit = jedis.setbit("foo", 0, true);
assertEquals(false, bit); assertEquals(false, bit);
bit = jedis.getbit("foo", 0); bit = jedis.getbit("foo", 0);
assertEquals(true, bit); assertEquals(true, bit);
boolean bbit = jedis.setbit("bfoo".getBytes(), 0, "1".getBytes()); boolean bbit = jedis.setbit("bfoo".getBytes(), 0, "1".getBytes());
assertFalse(bbit); assertFalse(bbit);
bbit = jedis.getbit("bfoo".getBytes(), 0); bbit = jedis.getbit("bfoo".getBytes(), 0);
assertTrue(bbit); assertTrue(bbit);
} }
@Test @Test
public void bitpos() { public void bitpos() {
String foo = "foo"; String foo = "foo";
jedis.set(foo, String.valueOf(0)); jedis.set(foo, String.valueOf(0));
jedis.setbit(foo, 3, true); jedis.setbit(foo, 3, true);
jedis.setbit(foo, 7, true); jedis.setbit(foo, 7, true);
jedis.setbit(foo, 13, true); jedis.setbit(foo, 13, true);
jedis.setbit(foo, 39, true); jedis.setbit(foo, 39, true);
/* /*
* byte: 0 1 2 3 4 bit: 00010001 / 00000100 / 00000000 / 00000000 / * byte: 0 1 2 3 4 bit: 00010001 / 00000100 / 00000000 / 00000000 /
* 00000001 * 00000001
*/ */
long offset = jedis.bitpos(foo, true); long offset = jedis.bitpos(foo, true);
assertEquals(2, offset); assertEquals(2, offset);
offset = jedis.bitpos(foo, false); offset = jedis.bitpos(foo, false);
assertEquals(0, offset); assertEquals(0, offset);
offset = jedis.bitpos(foo, true, new BitPosParams(1)); offset = jedis.bitpos(foo, true, new BitPosParams(1));
assertEquals(13, offset); assertEquals(13, offset);
offset = jedis.bitpos(foo, false, new BitPosParams(1)); offset = jedis.bitpos(foo, false, new BitPosParams(1));
assertEquals(8, offset); assertEquals(8, offset);
offset = jedis.bitpos(foo, true, new BitPosParams(2, 3)); offset = jedis.bitpos(foo, true, new BitPosParams(2, 3));
assertEquals(-1, offset); assertEquals(-1, offset);
offset = jedis.bitpos(foo, false, new BitPosParams(2, 3)); offset = jedis.bitpos(foo, false, new BitPosParams(2, 3));
assertEquals(16, offset); assertEquals(16, offset);
offset = jedis.bitpos(foo, true, new BitPosParams(3, 4)); offset = jedis.bitpos(foo, true, new BitPosParams(3, 4));
assertEquals(39, offset); assertEquals(39, offset);
} }
@Test @Test
public void bitposBinary() { public void bitposBinary() {
// binary // binary
byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 };
jedis.set(bfoo, Protocol.toByteArray(0)); jedis.set(bfoo, Protocol.toByteArray(0));
jedis.setbit(bfoo, 3, true); jedis.setbit(bfoo, 3, true);
jedis.setbit(bfoo, 7, true); jedis.setbit(bfoo, 7, true);
jedis.setbit(bfoo, 13, true); jedis.setbit(bfoo, 13, true);
jedis.setbit(bfoo, 39, true); jedis.setbit(bfoo, 39, true);
/* /*
* byte: 0 1 2 3 4 bit: 00010001 / 00000100 / 00000000 / 00000000 / * byte: 0 1 2 3 4 bit: 00010001 / 00000100 / 00000000 / 00000000 /
* 00000001 * 00000001
*/ */
long offset = jedis.bitpos(bfoo, true); long offset = jedis.bitpos(bfoo, true);
assertEquals(2, offset); assertEquals(2, offset);
offset = jedis.bitpos(bfoo, false); offset = jedis.bitpos(bfoo, false);
assertEquals(0, offset); assertEquals(0, offset);
offset = jedis.bitpos(bfoo, true, new BitPosParams(1)); offset = jedis.bitpos(bfoo, true, new BitPosParams(1));
assertEquals(13, offset); assertEquals(13, offset);
offset = jedis.bitpos(bfoo, false, new BitPosParams(1)); offset = jedis.bitpos(bfoo, false, new BitPosParams(1));
assertEquals(8, offset); assertEquals(8, offset);
offset = jedis.bitpos(bfoo, true, new BitPosParams(2, 3)); offset = jedis.bitpos(bfoo, true, new BitPosParams(2, 3));
assertEquals(-1, offset); assertEquals(-1, offset);
offset = jedis.bitpos(bfoo, false, new BitPosParams(2, 3)); offset = jedis.bitpos(bfoo, false, new BitPosParams(2, 3));
assertEquals(16, offset); assertEquals(16, offset);
offset = jedis.bitpos(bfoo, true, new BitPosParams(3, 4)); offset = jedis.bitpos(bfoo, true, new BitPosParams(3, 4));
assertEquals(39, offset); assertEquals(39, offset);
} }
@Test @Test
public void bitposWithNoMatchingBitExist() { public void bitposWithNoMatchingBitExist() {
String foo = "foo"; String foo = "foo";
jedis.set(foo, String.valueOf(0)); jedis.set(foo, String.valueOf(0));
for (int idx = 0; idx < 8; idx++) { for (int idx = 0; idx < 8; idx++) {
jedis.setbit(foo, idx, true); jedis.setbit(foo, idx, true);
} }
/* /*
* byte: 0 bit: 11111111 * byte: 0 bit: 11111111
*/ */
long offset = jedis.bitpos(foo, false); long offset = jedis.bitpos(foo, false);
// offset should be last index + 1 // offset should be last index + 1
assertEquals(8, offset); assertEquals(8, offset);
} }
@Test @Test
public void bitposWithNoMatchingBitExistWithinRange() { public void bitposWithNoMatchingBitExistWithinRange() {
String foo = "foo"; String foo = "foo";
jedis.set(foo, String.valueOf(0)); jedis.set(foo, String.valueOf(0));
for (int idx = 0; idx < 8 * 5; idx++) { for (int idx = 0; idx < 8 * 5; idx++) {
jedis.setbit(foo, idx, true); jedis.setbit(foo, idx, true);
} }
/* /*
* byte: 0 1 2 3 4 bit: 11111111 / 11111111 / 11111111 / 11111111 / * byte: 0 1 2 3 4 bit: 11111111 / 11111111 / 11111111 / 11111111 /
* 11111111 * 11111111
*/ */
long offset = jedis.bitpos(foo, false, new BitPosParams(2, 3)); long offset = jedis.bitpos(foo, false, new BitPosParams(2, 3));
// offset should be -1 // offset should be -1
assertEquals(-1, offset); assertEquals(-1, offset);
} }
@Test @Test
public void setAndgetrange() { public void setAndgetrange() {
jedis.set("key1", "Hello World"); jedis.set("key1", "Hello World");
long reply = jedis.setrange("key1", 6, "Jedis"); long reply = jedis.setrange("key1", 6, "Jedis");
assertEquals(11, reply); assertEquals(11, reply);
assertEquals(jedis.get("key1"), "Hello Jedis"); assertEquals(jedis.get("key1"), "Hello Jedis");
assertEquals("Hello", jedis.getrange("key1", 0, 4)); assertEquals("Hello", jedis.getrange("key1", 0, 4));
assertEquals("Jedis", jedis.getrange("key1", 6, 11)); assertEquals("Jedis", jedis.getrange("key1", 6, 11));
} }
@Test @Test
public void bitCount() { public void bitCount() {
jedis.del("foo"); jedis.del("foo");
jedis.setbit("foo", 16, true); jedis.setbit("foo", 16, true);
jedis.setbit("foo", 24, true); jedis.setbit("foo", 24, true);
jedis.setbit("foo", 40, true); jedis.setbit("foo", 40, true);
jedis.setbit("foo", 56, true); jedis.setbit("foo", 56, true);
long c4 = jedis.bitcount("foo"); long c4 = jedis.bitcount("foo");
assertEquals(4, c4); assertEquals(4, c4);
long c3 = jedis.bitcount("foo", 2L, 5L); long c3 = jedis.bitcount("foo", 2L, 5L);
assertEquals(3, c3); assertEquals(3, c3);
jedis.del("foo"); jedis.del("foo");
} }
@Test @Test
public void bitOp() { public void bitOp() {
jedis.set("key1", "\u0060"); jedis.set("key1", "\u0060");
jedis.set("key2", "\u0044"); jedis.set("key2", "\u0044");
jedis.bitop(BitOP.AND, "resultAnd", "key1", "key2"); jedis.bitop(BitOP.AND, "resultAnd", "key1", "key2");
String resultAnd = jedis.get("resultAnd"); String resultAnd = jedis.get("resultAnd");
assertEquals("\u0040", resultAnd); assertEquals("\u0040", resultAnd);
jedis.bitop(BitOP.OR, "resultOr", "key1", "key2"); jedis.bitop(BitOP.OR, "resultOr", "key1", "key2");
String resultOr = jedis.get("resultOr"); String resultOr = jedis.get("resultOr");
assertEquals("\u0064", resultOr); assertEquals("\u0064", resultOr);
jedis.bitop(BitOP.XOR, "resultXor", "key1", "key2"); jedis.bitop(BitOP.XOR, "resultXor", "key1", "key2");
String resultXor = jedis.get("resultXor"); String resultXor = jedis.get("resultXor");
assertEquals("\u0024", resultXor); assertEquals("\u0024", resultXor);
jedis.del("resultAnd"); jedis.del("resultAnd");
jedis.del("resultOr"); jedis.del("resultOr");
jedis.del("resultXor"); jedis.del("resultXor");
jedis.del("key1"); jedis.del("key1");
jedis.del("key2"); jedis.del("key2");
} }
@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);
jedis.bitop(BitOP.NOT, "resultNot", "key"); jedis.bitop(BitOP.NOT, "resultNot", "key");
String resultNot = jedis.get("resultNot"); String resultNot = jedis.get("resultNot");
assertEquals("\u0077", resultNot); assertEquals("\u0077", resultNot);
jedis.del("key"); jedis.del("key");
jedis.del("resultNot"); jedis.del("resultNot");
} }
} }

View File

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

View File

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

View File

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

View File

@@ -30,388 +30,388 @@ public class HashesCommandsTest extends JedisCommandTestBase {
@Test @Test
public void hset() { public void hset() {
long status = jedis.hset("foo", "bar", "car"); long status = jedis.hset("foo", "bar", "car");
assertEquals(1, status); assertEquals(1, status);
status = jedis.hset("foo", "bar", "foo"); status = jedis.hset("foo", "bar", "foo");
assertEquals(0, status); assertEquals(0, status);
// Binary // Binary
long bstatus = jedis.hset(bfoo, bbar, bcar); long bstatus = jedis.hset(bfoo, bbar, bcar);
assertEquals(1, bstatus); assertEquals(1, bstatus);
bstatus = jedis.hset(bfoo, bbar, bfoo); bstatus = jedis.hset(bfoo, bbar, bfoo);
assertEquals(0, bstatus); assertEquals(0, bstatus);
} }
@Test @Test
public void hget() { public void hget() {
jedis.hset("foo", "bar", "car"); jedis.hset("foo", "bar", "car");
assertEquals(null, jedis.hget("bar", "foo")); assertEquals(null, jedis.hget("bar", "foo"));
assertEquals(null, jedis.hget("foo", "car")); assertEquals(null, jedis.hget("foo", "car"));
assertEquals("car", jedis.hget("foo", "bar")); assertEquals("car", jedis.hget("foo", "bar"));
// Binary // Binary
jedis.hset(bfoo, bbar, bcar); jedis.hset(bfoo, bbar, bcar);
assertEquals(null, jedis.hget(bbar, bfoo)); assertEquals(null, jedis.hget(bbar, bfoo));
assertEquals(null, jedis.hget(bfoo, bcar)); assertEquals(null, jedis.hget(bfoo, bcar));
assertArrayEquals(bcar, jedis.hget(bfoo, bbar)); assertArrayEquals(bcar, jedis.hget(bfoo, bbar));
} }
@Test @Test
public void hsetnx() { public void hsetnx() {
long status = jedis.hsetnx("foo", "bar", "car"); long status = jedis.hsetnx("foo", "bar", "car");
assertEquals(1, status); assertEquals(1, status);
assertEquals("car", jedis.hget("foo", "bar")); assertEquals("car", jedis.hget("foo", "bar"));
status = jedis.hsetnx("foo", "bar", "foo"); status = jedis.hsetnx("foo", "bar", "foo");
assertEquals(0, status); assertEquals(0, status);
assertEquals("car", jedis.hget("foo", "bar")); assertEquals("car", jedis.hget("foo", "bar"));
status = jedis.hsetnx("foo", "car", "bar"); status = jedis.hsetnx("foo", "car", "bar");
assertEquals(1, status); assertEquals(1, status);
assertEquals("bar", jedis.hget("foo", "car")); assertEquals("bar", jedis.hget("foo", "car"));
// Binary // Binary
long bstatus = jedis.hsetnx(bfoo, bbar, bcar); long bstatus = jedis.hsetnx(bfoo, bbar, bcar);
assertEquals(1, bstatus); assertEquals(1, bstatus);
assertArrayEquals(bcar, jedis.hget(bfoo, bbar)); assertArrayEquals(bcar, jedis.hget(bfoo, bbar));
bstatus = jedis.hsetnx(bfoo, bbar, bfoo); bstatus = jedis.hsetnx(bfoo, bbar, bfoo);
assertEquals(0, bstatus); assertEquals(0, bstatus);
assertArrayEquals(bcar, jedis.hget(bfoo, bbar)); assertArrayEquals(bcar, jedis.hget(bfoo, bbar));
bstatus = jedis.hsetnx(bfoo, bcar, bbar); bstatus = jedis.hsetnx(bfoo, bcar, bbar);
assertEquals(1, bstatus); assertEquals(1, bstatus);
assertArrayEquals(bbar, jedis.hget(bfoo, bcar)); assertArrayEquals(bbar, jedis.hget(bfoo, bcar));
} }
@Test @Test
public void hmset() { public void hmset() {
Map<String, String> hash = new HashMap<String, String>(); Map<String, String> hash = new HashMap<String, String>();
hash.put("bar", "car"); hash.put("bar", "car");
hash.put("car", "bar"); hash.put("car", "bar");
String status = jedis.hmset("foo", hash); String status = jedis.hmset("foo", hash);
assertEquals("OK", status); assertEquals("OK", status);
assertEquals("car", jedis.hget("foo", "bar")); assertEquals("car", jedis.hget("foo", "bar"));
assertEquals("bar", jedis.hget("foo", "car")); assertEquals("bar", jedis.hget("foo", "car"));
// Binary // Binary
Map<byte[], byte[]> bhash = new HashMap<byte[], byte[]>(); Map<byte[], byte[]> bhash = new HashMap<byte[], byte[]>();
bhash.put(bbar, bcar); bhash.put(bbar, bcar);
bhash.put(bcar, bbar); bhash.put(bcar, bbar);
String bstatus = jedis.hmset(bfoo, bhash); String bstatus = jedis.hmset(bfoo, bhash);
assertEquals("OK", bstatus); assertEquals("OK", bstatus);
assertArrayEquals(bcar, jedis.hget(bfoo, bbar)); assertArrayEquals(bcar, jedis.hget(bfoo, bbar));
assertArrayEquals(bbar, jedis.hget(bfoo, bcar)); assertArrayEquals(bbar, jedis.hget(bfoo, bcar));
} }
@Test @Test
public void hmget() { public void hmget() {
Map<String, String> hash = new HashMap<String, String>(); Map<String, String> hash = new HashMap<String, String>();
hash.put("bar", "car"); hash.put("bar", "car");
hash.put("car", "bar"); hash.put("car", "bar");
jedis.hmset("foo", hash); jedis.hmset("foo", hash);
List<String> values = jedis.hmget("foo", "bar", "car", "foo"); List<String> values = jedis.hmget("foo", "bar", "car", "foo");
List<String> expected = new ArrayList<String>(); List<String> expected = new ArrayList<String>();
expected.add("car"); expected.add("car");
expected.add("bar"); expected.add("bar");
expected.add(null); expected.add(null);
assertEquals(expected, values); assertEquals(expected, values);
// Binary // Binary
Map<byte[], byte[]> bhash = new HashMap<byte[], byte[]>(); Map<byte[], byte[]> bhash = new HashMap<byte[], byte[]>();
bhash.put(bbar, bcar); bhash.put(bbar, bcar);
bhash.put(bcar, bbar); bhash.put(bcar, bbar);
jedis.hmset(bfoo, bhash); jedis.hmset(bfoo, bhash);
List<byte[]> bvalues = jedis.hmget(bfoo, bbar, bcar, bfoo); List<byte[]> bvalues = jedis.hmget(bfoo, bbar, bcar, bfoo);
List<byte[]> bexpected = new ArrayList<byte[]>(); List<byte[]> bexpected = new ArrayList<byte[]>();
bexpected.add(bcar); bexpected.add(bcar);
bexpected.add(bbar); bexpected.add(bbar);
bexpected.add(null); bexpected.add(null);
assertEquals(bexpected, bvalues); assertEquals(bexpected, bvalues);
} }
@Test @Test
public void hincrBy() { public void hincrBy() {
long value = jedis.hincrBy("foo", "bar", 1); long value = jedis.hincrBy("foo", "bar", 1);
assertEquals(1, value); assertEquals(1, value);
value = jedis.hincrBy("foo", "bar", -1); value = jedis.hincrBy("foo", "bar", -1);
assertEquals(0, value); assertEquals(0, value);
value = jedis.hincrBy("foo", "bar", -10); value = jedis.hincrBy("foo", "bar", -10);
assertEquals(-10, value); assertEquals(-10, value);
// Binary // Binary
long bvalue = jedis.hincrBy(bfoo, bbar, 1); long bvalue = jedis.hincrBy(bfoo, bbar, 1);
assertEquals(1, bvalue); assertEquals(1, bvalue);
bvalue = jedis.hincrBy(bfoo, bbar, -1); bvalue = jedis.hincrBy(bfoo, bbar, -1);
assertEquals(0, bvalue); assertEquals(0, bvalue);
bvalue = jedis.hincrBy(bfoo, bbar, -10); bvalue = jedis.hincrBy(bfoo, bbar, -10);
assertEquals(-10, bvalue); assertEquals(-10, bvalue);
} }
@Test @Test
public void hincrByFloat() { public void hincrByFloat() {
Double value = jedis.hincrByFloat("foo", "bar", 1.5d); Double value = jedis.hincrByFloat("foo", "bar", 1.5d);
assertEquals((Double) 1.5d, value); assertEquals((Double) 1.5d, value);
value = jedis.hincrByFloat("foo", "bar", -1.5d); value = jedis.hincrByFloat("foo", "bar", -1.5d);
assertEquals((Double) 0d, value); assertEquals((Double) 0d, value);
value = jedis.hincrByFloat("foo", "bar", -10.7d); value = jedis.hincrByFloat("foo", "bar", -10.7d);
assertEquals(Double.compare(-10.7d, value), 0); assertEquals(Double.compare(-10.7d, value), 0);
// Binary // Binary
double bvalue = jedis.hincrByFloat(bfoo, bbar, 1.5d); double bvalue = jedis.hincrByFloat(bfoo, bbar, 1.5d);
assertEquals(Double.compare(1.5d, bvalue), 0); assertEquals(Double.compare(1.5d, bvalue), 0);
bvalue = jedis.hincrByFloat(bfoo, bbar, -1.5d); bvalue = jedis.hincrByFloat(bfoo, bbar, -1.5d);
assertEquals(Double.compare(0d, bvalue), 0); assertEquals(Double.compare(0d, bvalue), 0);
bvalue = jedis.hincrByFloat(bfoo, bbar, -10.7d); bvalue = jedis.hincrByFloat(bfoo, bbar, -10.7d);
assertEquals(Double.compare(-10.7d, value), 0); assertEquals(Double.compare(-10.7d, value), 0);
} }
@Test @Test
public void hexists() { public void hexists() {
Map<String, String> hash = new HashMap<String, String>(); Map<String, String> hash = new HashMap<String, String>();
hash.put("bar", "car"); hash.put("bar", "car");
hash.put("car", "bar"); hash.put("car", "bar");
jedis.hmset("foo", hash); jedis.hmset("foo", hash);
assertFalse(jedis.hexists("bar", "foo")); assertFalse(jedis.hexists("bar", "foo"));
assertFalse(jedis.hexists("foo", "foo")); assertFalse(jedis.hexists("foo", "foo"));
assertTrue(jedis.hexists("foo", "bar")); assertTrue(jedis.hexists("foo", "bar"));
// Binary // Binary
Map<byte[], byte[]> bhash = new HashMap<byte[], byte[]>(); Map<byte[], byte[]> bhash = new HashMap<byte[], byte[]>();
bhash.put(bbar, bcar); bhash.put(bbar, bcar);
bhash.put(bcar, bbar); bhash.put(bcar, bbar);
jedis.hmset(bfoo, bhash); jedis.hmset(bfoo, bhash);
assertFalse(jedis.hexists(bbar, bfoo)); assertFalse(jedis.hexists(bbar, bfoo));
assertFalse(jedis.hexists(bfoo, bfoo)); assertFalse(jedis.hexists(bfoo, bfoo));
assertTrue(jedis.hexists(bfoo, bbar)); assertTrue(jedis.hexists(bfoo, bbar));
} }
@Test @Test
public void hdel() { public void hdel() {
Map<String, String> hash = new HashMap<String, String>(); Map<String, String> hash = new HashMap<String, String>();
hash.put("bar", "car"); hash.put("bar", "car");
hash.put("car", "bar"); hash.put("car", "bar");
jedis.hmset("foo", hash); jedis.hmset("foo", hash);
assertEquals(0, jedis.hdel("bar", "foo").intValue()); assertEquals(0, jedis.hdel("bar", "foo").intValue());
assertEquals(0, jedis.hdel("foo", "foo").intValue()); assertEquals(0, jedis.hdel("foo", "foo").intValue());
assertEquals(1, jedis.hdel("foo", "bar").intValue()); assertEquals(1, jedis.hdel("foo", "bar").intValue());
assertEquals(null, jedis.hget("foo", "bar")); assertEquals(null, jedis.hget("foo", "bar"));
// Binary // Binary
Map<byte[], byte[]> bhash = new HashMap<byte[], byte[]>(); Map<byte[], byte[]> bhash = new HashMap<byte[], byte[]>();
bhash.put(bbar, bcar); bhash.put(bbar, bcar);
bhash.put(bcar, bbar); bhash.put(bcar, bbar);
jedis.hmset(bfoo, bhash); jedis.hmset(bfoo, bhash);
assertEquals(0, jedis.hdel(bbar, bfoo).intValue()); assertEquals(0, jedis.hdel(bbar, bfoo).intValue());
assertEquals(0, jedis.hdel(bfoo, bfoo).intValue()); assertEquals(0, jedis.hdel(bfoo, bfoo).intValue());
assertEquals(1, jedis.hdel(bfoo, bbar).intValue()); assertEquals(1, jedis.hdel(bfoo, bbar).intValue());
assertEquals(null, jedis.hget(bfoo, bbar)); assertEquals(null, jedis.hget(bfoo, bbar));
} }
@Test @Test
public void hlen() { public void hlen() {
Map<String, String> hash = new HashMap<String, String>(); Map<String, String> hash = new HashMap<String, String>();
hash.put("bar", "car"); hash.put("bar", "car");
hash.put("car", "bar"); hash.put("car", "bar");
jedis.hmset("foo", hash); jedis.hmset("foo", hash);
assertEquals(0, jedis.hlen("bar").intValue()); assertEquals(0, jedis.hlen("bar").intValue());
assertEquals(2, jedis.hlen("foo").intValue()); assertEquals(2, jedis.hlen("foo").intValue());
// Binary // Binary
Map<byte[], byte[]> bhash = new HashMap<byte[], byte[]>(); Map<byte[], byte[]> bhash = new HashMap<byte[], byte[]>();
bhash.put(bbar, bcar); bhash.put(bbar, bcar);
bhash.put(bcar, bbar); bhash.put(bcar, bbar);
jedis.hmset(bfoo, bhash); jedis.hmset(bfoo, bhash);
assertEquals(0, jedis.hlen(bbar).intValue()); assertEquals(0, jedis.hlen(bbar).intValue());
assertEquals(2, jedis.hlen(bfoo).intValue()); assertEquals(2, jedis.hlen(bfoo).intValue());
} }
@Test @Test
public void hkeys() { public void hkeys() {
Map<String, String> hash = new LinkedHashMap<String, String>(); Map<String, String> hash = new LinkedHashMap<String, String>();
hash.put("bar", "car"); hash.put("bar", "car");
hash.put("car", "bar"); hash.put("car", "bar");
jedis.hmset("foo", hash); jedis.hmset("foo", hash);
Set<String> keys = jedis.hkeys("foo"); Set<String> keys = jedis.hkeys("foo");
Set<String> expected = new LinkedHashSet<String>(); Set<String> expected = new LinkedHashSet<String>();
expected.add("bar"); expected.add("bar");
expected.add("car"); expected.add("car");
assertEquals(expected, keys); assertEquals(expected, keys);
// Binary // Binary
Map<byte[], byte[]> bhash = new LinkedHashMap<byte[], byte[]>(); Map<byte[], byte[]> bhash = new LinkedHashMap<byte[], byte[]>();
bhash.put(bbar, bcar); bhash.put(bbar, bcar);
bhash.put(bcar, bbar); bhash.put(bcar, bbar);
jedis.hmset(bfoo, bhash); jedis.hmset(bfoo, bhash);
Set<byte[]> bkeys = jedis.hkeys(bfoo); Set<byte[]> bkeys = jedis.hkeys(bfoo);
Set<byte[]> bexpected = new LinkedHashSet<byte[]>(); Set<byte[]> bexpected = new LinkedHashSet<byte[]>();
bexpected.add(bbar); bexpected.add(bbar);
bexpected.add(bcar); bexpected.add(bcar);
assertEquals(bexpected, bkeys); assertEquals(bexpected, bkeys);
} }
@Test @Test
public void hvals() { public void hvals() {
Map<String, String> hash = new LinkedHashMap<String, String>(); Map<String, String> hash = new LinkedHashMap<String, String>();
hash.put("bar", "car"); hash.put("bar", "car");
hash.put("car", "bar"); hash.put("car", "bar");
jedis.hmset("foo", hash); jedis.hmset("foo", hash);
List<String> vals = jedis.hvals("foo"); List<String> vals = jedis.hvals("foo");
assertEquals(2, vals.size()); assertEquals(2, vals.size());
assertTrue(vals.contains("bar")); assertTrue(vals.contains("bar"));
assertTrue(vals.contains("car")); assertTrue(vals.contains("car"));
// Binary // Binary
Map<byte[], byte[]> bhash = new LinkedHashMap<byte[], byte[]>(); Map<byte[], byte[]> bhash = new LinkedHashMap<byte[], byte[]>();
bhash.put(bbar, bcar); bhash.put(bbar, bcar);
bhash.put(bcar, bbar); bhash.put(bcar, bbar);
jedis.hmset(bfoo, bhash); jedis.hmset(bfoo, bhash);
List<byte[]> bvals = jedis.hvals(bfoo); List<byte[]> bvals = jedis.hvals(bfoo);
assertEquals(2, bvals.size()); assertEquals(2, bvals.size());
assertTrue(arrayContains(bvals, bbar)); assertTrue(arrayContains(bvals, bbar));
assertTrue(arrayContains(bvals, bcar)); assertTrue(arrayContains(bvals, bcar));
} }
@Test @Test
public void hgetAll() { public void hgetAll() {
Map<String, String> h = new HashMap<String, String>(); Map<String, String> h = new HashMap<String, String>();
h.put("bar", "car"); h.put("bar", "car");
h.put("car", "bar"); h.put("car", "bar");
jedis.hmset("foo", h); jedis.hmset("foo", h);
Map<String, String> hash = jedis.hgetAll("foo"); Map<String, String> hash = jedis.hgetAll("foo");
assertEquals(2, hash.size()); assertEquals(2, hash.size());
assertEquals("car", hash.get("bar")); assertEquals("car", hash.get("bar"));
assertEquals("bar", hash.get("car")); assertEquals("bar", hash.get("car"));
// Binary // Binary
Map<byte[], byte[]> bh = new HashMap<byte[], byte[]>(); Map<byte[], byte[]> bh = new HashMap<byte[], byte[]>();
bh.put(bbar, bcar); bh.put(bbar, bcar);
bh.put(bcar, bbar); bh.put(bcar, bbar);
jedis.hmset(bfoo, bh); jedis.hmset(bfoo, bh);
Map<byte[], byte[]> bhash = jedis.hgetAll(bfoo); Map<byte[], byte[]> bhash = jedis.hgetAll(bfoo);
assertEquals(2, bhash.size()); assertEquals(2, bhash.size());
assertArrayEquals(bcar, bhash.get(bbar)); assertArrayEquals(bcar, bhash.get(bbar));
assertArrayEquals(bbar, bhash.get(bcar)); assertArrayEquals(bbar, bhash.get(bcar));
} }
@Test @Test
public void hgetAllPipeline() { public void hgetAllPipeline() {
Map<byte[], byte[]> bh = new HashMap<byte[], byte[]>(); Map<byte[], byte[]> bh = new HashMap<byte[], byte[]>();
bh.put(bbar, bcar); bh.put(bbar, bcar);
bh.put(bcar, bbar); bh.put(bcar, bbar);
jedis.hmset(bfoo, bh); jedis.hmset(bfoo, bh);
Pipeline pipeline = jedis.pipelined(); Pipeline pipeline = jedis.pipelined();
Response<Map<byte[], byte[]>> bhashResponse = pipeline.hgetAll(bfoo); Response<Map<byte[], byte[]>> bhashResponse = pipeline.hgetAll(bfoo);
pipeline.sync(); pipeline.sync();
Map<byte[], byte[]> bhash = bhashResponse.get(); Map<byte[], byte[]> bhash = bhashResponse.get();
assertEquals(2, bhash.size()); assertEquals(2, bhash.size());
assertArrayEquals(bcar, bhash.get(bbar)); assertArrayEquals(bcar, bhash.get(bbar));
assertArrayEquals(bbar, bhash.get(bcar)); assertArrayEquals(bbar, bhash.get(bcar));
} }
@Test @Test
public void hscan() { public void hscan() {
jedis.hset("foo", "b", "b"); jedis.hset("foo", "b", "b");
jedis.hset("foo", "a", "a"); jedis.hset("foo", "a", "a");
ScanResult<Map.Entry<String, String>> result = jedis.hscan("foo", ScanResult<Map.Entry<String, String>> result = jedis.hscan("foo",
SCAN_POINTER_START); SCAN_POINTER_START);
assertEquals(SCAN_POINTER_START, result.getCursor()); assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty()); assertFalse(result.getResult().isEmpty());
// binary // binary
jedis.hset(bfoo, bbar, bcar); jedis.hset(bfoo, bbar, bcar);
ScanResult<Map.Entry<byte[], byte[]>> bResult = jedis.hscan(bfoo, ScanResult<Map.Entry<byte[], byte[]>> bResult = jedis.hscan(bfoo,
SCAN_POINTER_START_BINARY); SCAN_POINTER_START_BINARY);
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty()); assertFalse(bResult.getResult().isEmpty());
} }
@Test @Test
public void hscanMatch() { public void hscanMatch() {
ScanParams params = new ScanParams(); ScanParams params = new ScanParams();
params.match("a*"); params.match("a*");
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", ScanResult<Map.Entry<String, String>> result = jedis.hscan("foo",
SCAN_POINTER_START, params); SCAN_POINTER_START, params);
assertEquals(SCAN_POINTER_START, result.getCursor()); assertEquals(SCAN_POINTER_START, result.getCursor());
assertFalse(result.getResult().isEmpty()); assertFalse(result.getResult().isEmpty());
// binary // binary
params = new ScanParams(); params = new ScanParams();
params.match(bbarstar); params.match(bbarstar);
jedis.hset(bfoo, bbar, bcar); jedis.hset(bfoo, bbar, bcar);
jedis.hset(bfoo, bbar1, bcar); jedis.hset(bfoo, bbar1, bcar);
jedis.hset(bfoo, bbar2, bcar); jedis.hset(bfoo, bbar2, bcar);
jedis.hset(bfoo, bbar3, bcar); jedis.hset(bfoo, bbar3, bcar);
ScanResult<Map.Entry<byte[], byte[]>> bResult = jedis.hscan(bfoo, ScanResult<Map.Entry<byte[], byte[]>> bResult = jedis.hscan(bfoo,
SCAN_POINTER_START_BINARY, params); SCAN_POINTER_START_BINARY, params);
assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes());
assertFalse(bResult.getResult().isEmpty()); assertFalse(bResult.getResult().isEmpty());
} }
@Test @Test
public void hscanCount() { public void hscanCount() {
ScanParams params = new ScanParams(); ScanParams params = new ScanParams();
params.count(2); params.count(2);
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
jedis.hset("foo", "a" + i, "a" + i); jedis.hset("foo", "a" + i, "a" + i);
} }
ScanResult<Map.Entry<String, String>> result = jedis.hscan("foo", ScanResult<Map.Entry<String, String>> result = jedis.hscan("foo",
SCAN_POINTER_START, params); SCAN_POINTER_START, params);
assertFalse(result.getResult().isEmpty()); assertFalse(result.getResult().isEmpty());
// binary // binary
params = new ScanParams(); params = new ScanParams();
params.count(2); params.count(2);
jedis.hset(bfoo, bbar, bcar); jedis.hset(bfoo, bbar, bcar);
jedis.hset(bfoo, bbar1, bcar); jedis.hset(bfoo, bbar1, bcar);
jedis.hset(bfoo, bbar2, bcar); jedis.hset(bfoo, bbar2, bcar);
jedis.hset(bfoo, bbar3, bcar); jedis.hset(bfoo, bbar3, bcar);
ScanResult<Map.Entry<byte[], byte[]>> bResult = jedis.hscan(bfoo, ScanResult<Map.Entry<byte[], byte[]>> bResult = jedis.hscan(bfoo,
SCAN_POINTER_START_BINARY, params); SCAN_POINTER_START_BINARY, params);
assertFalse(bResult.getResult().isEmpty()); assertFalse(bResult.getResult().isEmpty());
} }
} }

Some files were not shown because too many files have changed in this diff Show More