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[]> zrangeByScore(byte[] key, double min, double max, int offset,
int count);
int count);
Set<byte[]> zrevrangeByScore(byte[] key, byte[] max, byte[] min);
Set<byte[]> zrangeByScore(byte[] key, byte[] min, byte[] max, int offset,
int count);
int count);
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> zrevrangeByScoreWithScores(byte[] key, double max, double min);
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,
int offset, int count);
int offset, int count);
Set<Tuple> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max);
Set<Tuple> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min);
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,
int offset, int count);
int offset, int count);
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);
@@ -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, int offset, int count);
final byte[] max, int offset, int count);
Set<byte[]> zrevrangeByLex(final byte[] key, final byte[] max,
final byte[] min);
final byte[] min);
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 linsert(byte[] key, Client.LIST_POSITION where, byte[] pivot,
byte[] value);
byte[] value);
Long lpushx(byte[] key, byte[]... arg);

View File

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

View File

@@ -67,7 +67,7 @@ public interface BinaryRedisPipeline {
Response<byte[]> lindex(byte[] key, long index);
Response<Long> linsert(byte[] key, BinaryClient.LIST_POSITION where,
byte[] pivot, byte[] value);
byte[] pivot, byte[] value);
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, double min, double max,
int offset, int count);
int offset, int count);
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,
double max);
double max);
Response<Set<Tuple>> zrangeByScoreWithScores(byte[] key, byte[] min,
byte[] max);
byte[] max);
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,
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, byte[] max, byte[] 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,
int offset, int count);
int offset, int count);
Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key, double max,
double min);
double min);
Response<Set<Tuple>> zrevrangeByScoreWithScores(byte[] key, byte[] max,
byte[] min);
byte[] min);
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,
byte[] min, int offset, int count);
byte[] min, int offset, int count);
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<Long> zlexcount(final byte[] key, final byte[] min,
final byte[] max);
final byte[] max);
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,
final byte[] max, int offset, int count);
final byte[] max, int offset, int count);
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,
final byte[] min, int offset, int count);
final byte[] min, int offset, int count);
Response<Long> zremrangeByLex(final byte[] key, final byte[] min,
final byte[] max);
final byte[] max);
Response<Long> bitcount(byte[] key);

View File

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

View File

@@ -12,16 +12,16 @@ public class BitPosParams {
}
public BitPosParams(long start) {
params.add(Protocol.toByteArray(start));
params.add(Protocol.toByteArray(start));
}
public BitPosParams(long start, long end) {
this(start);
this(start);
params.add(Protocol.toByteArray(end));
params.add(Protocol.toByteArray(end));
}
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 static final Builder<Double> DOUBLE = new Builder<Double>() {
public Double build(Object data) {
String asString = STRING.build(data);
return asString == null ? null : Double.valueOf(asString);
}
public Double build(Object data) {
String asString = STRING.build(data);
return asString == null ? null : Double.valueOf(asString);
}
public String toString() {
return "double";
}
public String toString() {
return "double";
}
};
public static final Builder<Boolean> BOOLEAN = new Builder<Boolean>() {
public Boolean build(Object data) {
return ((Long) data) == 1;
}
public Boolean build(Object data) {
return ((Long) data) == 1;
}
public String toString() {
return "boolean";
}
public String toString() {
return "boolean";
}
};
public static final Builder<byte[]> BYTE_ARRAY = new Builder<byte[]>() {
public byte[] build(Object data) {
return ((byte[]) data); // deleted == 1
}
public byte[] build(Object data) {
return ((byte[]) data); // deleted == 1
}
public String toString() {
return "byte[]";
}
public String toString() {
return "byte[]";
}
};
public static final Builder<Long> LONG = new Builder<Long>() {
public Long build(Object data) {
return (Long) data;
}
public Long build(Object data) {
return (Long) data;
}
public String toString() {
return "long";
}
public String toString() {
return "long";
}
};
public static final Builder<String> STRING = new Builder<String>() {
public String build(Object data) {
return data == null ? null : SafeEncoder.encode((byte[]) data);
}
public String build(Object data) {
return data == null ? null : SafeEncoder.encode((byte[]) data);
}
public String toString() {
return "string";
}
public String toString() {
return "string";
}
};
public static final Builder<List<String>> STRING_LIST = new Builder<List<String>>() {
@SuppressWarnings("unchecked")
public List<String> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final ArrayList<String> result = new ArrayList<String>(l.size());
for (final byte[] barray : l) {
if (barray == null) {
result.add(null);
} else {
result.add(SafeEncoder.encode(barray));
}
}
return result;
}
@SuppressWarnings("unchecked")
public List<String> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final ArrayList<String> result = new ArrayList<String>(l.size());
for (final byte[] barray : l) {
if (barray == null) {
result.add(null);
} else {
result.add(SafeEncoder.encode(barray));
}
}
return result;
}
public String toString() {
return "List<String>";
}
public String toString() {
return "List<String>";
}
};
public static final Builder<Map<String, String>> STRING_MAP = new Builder<Map<String, String>>() {
@SuppressWarnings("unchecked")
public Map<String, String> build(Object data) {
final List<byte[]> flatHash = (List<byte[]>) data;
final Map<String, String> hash = new HashMap<String, String>();
final Iterator<byte[]> iterator = flatHash.iterator();
while (iterator.hasNext()) {
hash.put(SafeEncoder.encode(iterator.next()),
SafeEncoder.encode(iterator.next()));
}
@SuppressWarnings("unchecked")
public Map<String, String> build(Object data) {
final List<byte[]> flatHash = (List<byte[]>) data;
final Map<String, String> hash = new HashMap<String, String>();
final Iterator<byte[]> iterator = flatHash.iterator();
while (iterator.hasNext()) {
hash.put(SafeEncoder.encode(iterator.next()),
SafeEncoder.encode(iterator.next()));
}
return hash;
}
return hash;
}
public String toString() {
return "Map<String, String>";
}
public String toString() {
return "Map<String, String>";
}
};
public static final Builder<Map<String, String>> PUBSUB_NUMSUB_MAP = new Builder<Map<String, String>>() {
@SuppressWarnings("unchecked")
public Map<String, String> build(Object data) {
final List<Object> flatHash = (List<Object>) data;
final Map<String, String> hash = new HashMap<String, String>();
final Iterator<Object> iterator = flatHash.iterator();
while (iterator.hasNext()) {
hash.put(SafeEncoder.encode((byte[]) iterator.next()),
String.valueOf((Long) iterator.next()));
}
@SuppressWarnings("unchecked")
public Map<String, String> build(Object data) {
final List<Object> flatHash = (List<Object>) data;
final Map<String, String> hash = new HashMap<String, String>();
final Iterator<Object> iterator = flatHash.iterator();
while (iterator.hasNext()) {
hash.put(SafeEncoder.encode((byte[]) iterator.next()),
String.valueOf((Long) iterator.next()));
}
return hash;
}
return hash;
}
public String toString() {
return "PUBSUB_NUMSUB_MAP<String, String>";
}
public String toString() {
return "PUBSUB_NUMSUB_MAP<String, String>";
}
};
public static final Builder<Set<String>> STRING_SET = new Builder<Set<String>>() {
@SuppressWarnings("unchecked")
public Set<String> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final Set<String> result = new HashSet<String>(l.size());
for (final byte[] barray : l) {
if (barray == null) {
result.add(null);
} else {
result.add(SafeEncoder.encode(barray));
}
}
return result;
}
@SuppressWarnings("unchecked")
public Set<String> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final Set<String> result = new HashSet<String>(l.size());
for (final byte[] barray : l) {
if (barray == null) {
result.add(null);
} else {
result.add(SafeEncoder.encode(barray));
}
}
return result;
}
public String toString() {
return "Set<String>";
}
public String toString() {
return "Set<String>";
}
};
public static final Builder<List<byte[]>> BYTE_ARRAY_LIST = new Builder<List<byte[]>>() {
@SuppressWarnings("unchecked")
public List<byte[]> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
@SuppressWarnings("unchecked")
public List<byte[]> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
return l;
}
return l;
}
public String toString() {
return "List<byte[]>";
}
public String toString() {
return "List<byte[]>";
}
};
public static final Builder<Set<byte[]>> BYTE_ARRAY_ZSET = new Builder<Set<byte[]>>() {
@SuppressWarnings("unchecked")
public Set<byte[]> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final Set<byte[]> result = new LinkedHashSet<byte[]>(l);
for (final byte[] barray : l) {
if (barray == null) {
result.add(null);
} else {
result.add(barray);
}
}
return result;
}
@SuppressWarnings("unchecked")
public Set<byte[]> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final Set<byte[]> result = new LinkedHashSet<byte[]>(l);
for (final byte[] barray : l) {
if (barray == null) {
result.add(null);
} else {
result.add(barray);
}
}
return result;
}
public String toString() {
return "ZSet<byte[]>";
}
public String toString() {
return "ZSet<byte[]>";
}
};
public static final Builder<Map<byte[], byte[]>> BYTE_ARRAY_MAP = new Builder<Map<byte[], byte[]>>() {
@SuppressWarnings("unchecked")
public Map<byte[], byte[]> build(Object data) {
final List<byte[]> flatHash = (List<byte[]>) data;
final Map<byte[], byte[]> hash = new JedisByteHashMap();
final Iterator<byte[]> iterator = flatHash.iterator();
while (iterator.hasNext()) {
hash.put(iterator.next(), iterator.next());
}
@SuppressWarnings("unchecked")
public Map<byte[], byte[]> build(Object data) {
final List<byte[]> flatHash = (List<byte[]>) data;
final Map<byte[], byte[]> hash = new JedisByteHashMap();
final Iterator<byte[]> iterator = flatHash.iterator();
while (iterator.hasNext()) {
hash.put(iterator.next(), iterator.next());
}
return hash;
}
return hash;
}
public String toString() {
return "Map<byte[], byte[]>";
}
public String toString() {
return "Map<byte[], byte[]>";
}
};
public static final Builder<Set<String>> STRING_ZSET = new Builder<Set<String>>() {
@SuppressWarnings("unchecked")
public Set<String> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final Set<String> result = new LinkedHashSet<String>(l.size());
for (final byte[] barray : l) {
if (barray == null) {
result.add(null);
} else {
result.add(SafeEncoder.encode(barray));
}
}
return result;
}
@SuppressWarnings("unchecked")
public Set<String> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final Set<String> result = new LinkedHashSet<String>(l.size());
for (final byte[] barray : l) {
if (barray == null) {
result.add(null);
} else {
result.add(SafeEncoder.encode(barray));
}
}
return result;
}
public String toString() {
return "ZSet<String>";
}
public String toString() {
return "ZSet<String>";
}
};
public static final Builder<Set<Tuple>> TUPLE_ZSET = new Builder<Set<Tuple>>() {
@SuppressWarnings("unchecked")
public Set<Tuple> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final Set<Tuple> result = new LinkedHashSet<Tuple>(l.size());
Iterator<byte[]> iterator = l.iterator();
while (iterator.hasNext()) {
result.add(new Tuple(SafeEncoder.encode(iterator.next()),
Double.valueOf(SafeEncoder.encode(iterator.next()))));
}
return result;
}
@SuppressWarnings("unchecked")
public Set<Tuple> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final Set<Tuple> result = new LinkedHashSet<Tuple>(l.size());
Iterator<byte[]> iterator = l.iterator();
while (iterator.hasNext()) {
result.add(new Tuple(SafeEncoder.encode(iterator.next()),
Double.valueOf(SafeEncoder.encode(iterator.next()))));
}
return result;
}
public String toString() {
return "ZSet<Tuple>";
}
public String toString() {
return "ZSet<Tuple>";
}
};
public static final Builder<Set<Tuple>> TUPLE_ZSET_BINARY = new Builder<Set<Tuple>>() {
@SuppressWarnings("unchecked")
public Set<Tuple> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final Set<Tuple> result = new LinkedHashSet<Tuple>(l.size());
Iterator<byte[]> iterator = l.iterator();
while (iterator.hasNext()) {
result.add(new Tuple(iterator.next(), Double
.valueOf(SafeEncoder.encode(iterator.next()))));
}
@SuppressWarnings("unchecked")
public Set<Tuple> build(Object data) {
if (null == data) {
return null;
}
List<byte[]> l = (List<byte[]>) data;
final Set<Tuple> result = new LinkedHashSet<Tuple>(l.size());
Iterator<byte[]> iterator = l.iterator();
while (iterator.hasNext()) {
result.add(new Tuple(iterator.next(), Double
.valueOf(SafeEncoder.encode(iterator.next()))));
}
return result;
return result;
}
}
public String toString() {
return "ZSet<Tuple>";
}
public String toString() {
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, final String nxxx,
final String expx, final long time);
final String expx, final long time);
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 hincrByFloat(final String key, final String field,
final double value);
final double value);
public void hexists(final String key, final String field);
@@ -127,7 +127,7 @@ public interface Commands {
public void spop(final String key);
public void smove(final String srckey, final String dstkey,
final String member);
final String member);
public void scard(final String key);
@@ -156,7 +156,7 @@ public interface Commands {
public void zrem(final String key, final String... members);
public void zincrby(final String key, final double score,
final String member);
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 zrangeWithScores(final String key, final long start,
final long end);
final long end);
public void zrevrangeWithScores(final String key, final long start,
final long end);
final long end);
public void zcard(final String key);
@@ -183,79 +183,79 @@ public interface Commands {
public void blpop(final String[] args);
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 brpop(final String[] args);
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 String min, final String max);
public void zrangeByScore(final String key, final double min,
final double max);
final double max);
public void zrangeByScore(final String key, final String min,
final String max);
final String max);
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,
final double max);
final double max);
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,
final String max);
final String max);
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,
final double min);
final double min);
public void zrevrangeByScore(final String key, final String max,
final String min);
final String min);
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,
final double min);
final double min);
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,
final String min);
final String min);
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,
final long end);
final long end);
public void zremrangeByScore(final String key, final double start,
final double end);
final double end);
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 ZParams params,
final String... sets);
final String... sets);
public void zinterstore(final String dstkey, final String... sets);
public void zinterstore(final String dstkey, final ZParams params,
final String... sets);
final String... sets);
public void strlen(final String key);
@@ -268,7 +268,7 @@ public interface Commands {
public void echo(final String string);
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();
@@ -305,13 +305,13 @@ public interface Commands {
public void scan(final String cursor, final ScanParams params);
public void hscan(final String key, final String cursor,
final ScanParams params);
final ScanParams params);
public void sscan(final String key, final String cursor,
final ScanParams params);
final ScanParams params);
public void zscan(final String key, final String cursor,
final ScanParams params);
final ScanParams params);
public void waitReplicas(int replicas, long timeout);
}

View File

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

View File

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

View File

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

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

View File

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

View File

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

View File

@@ -157,38 +157,38 @@ public interface JedisCommands {
Set<String> zrevrangeByScore(String key, double max, double min);
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> zrangeByScore(String key, String min, String max, int offset,
int count);
int count);
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> zrevrangeByScoreWithScores(String key, double max, double min);
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,
int offset, int count);
int offset, int count);
Set<Tuple> zrangeByScoreWithScores(String key, String min, String max);
Set<Tuple> zrevrangeByScoreWithScores(String key, String max, String min);
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,
int offset, int count);
int offset, int count);
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);
@@ -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, final int offset, final int count);
final String max, final int offset, final int count);
Set<String> zrevrangeByLex(final String key, final String max,
final String min);
final String min);
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 linsert(String key, Client.LIST_POSITION where, String pivot,
String value);
String value);
Long lpushx(String key, String... string);
@@ -245,7 +245,7 @@ public interface JedisCommands {
Long bitcount(final String key, long start, long end);
ScanResult<Map.Entry<String, String>> hscan(final String key,
final String cursor);
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;
public JedisFactory(final String host, final int port, final int timeout,
final String password, final int database) {
this(host, port, timeout, password, database, null);
final String password, final int database) {
this(host, port, timeout, password, database, null);
}
public JedisFactory(final String host, final int port, final int timeout,
final String password, final int database, final String clientName) {
super();
this.hostAndPort.set(new HostAndPort(host, port));
this.timeout = timeout;
this.password = password;
this.database = database;
this.clientName = clientName;
final String password, final int database, final String clientName) {
super();
this.hostAndPort.set(new HostAndPort(host, port));
this.timeout = timeout;
this.password = password;
this.database = database;
this.clientName = clientName;
}
public void setHostAndPort(final HostAndPort hostAndPort) {
this.hostAndPort.set(hostAndPort);
this.hostAndPort.set(hostAndPort);
}
@Override
public void activateObject(PooledObject<Jedis> pooledJedis)
throws Exception {
final BinaryJedis jedis = pooledJedis.getObject();
if (jedis.getDB() != database) {
jedis.select(database);
}
throws Exception {
final BinaryJedis jedis = pooledJedis.getObject();
if (jedis.getDB() != database) {
jedis.select(database);
}
}
@Override
public void destroyObject(PooledObject<Jedis> pooledJedis) throws Exception {
final BinaryJedis jedis = pooledJedis.getObject();
if (jedis.isConnected()) {
try {
try {
jedis.quit();
} catch (Exception e) {
}
jedis.disconnect();
} catch (Exception e) {
final BinaryJedis jedis = pooledJedis.getObject();
if (jedis.isConnected()) {
try {
try {
jedis.quit();
} catch (Exception e) {
}
jedis.disconnect();
} catch (Exception e) {
}
}
}
}
}
@Override
public PooledObject<Jedis> makeObject() throws Exception {
final HostAndPort hostAndPort = this.hostAndPort.get();
final Jedis jedis = new Jedis(hostAndPort.getHost(),
hostAndPort.getPort(), this.timeout);
final HostAndPort hostAndPort = this.hostAndPort.get();
final Jedis jedis = new Jedis(hostAndPort.getHost(),
hostAndPort.getPort(), this.timeout);
jedis.connect();
if (null != this.password) {
jedis.auth(this.password);
}
if (database != 0) {
jedis.select(database);
}
if (clientName != null) {
jedis.clientSetname(clientName);
}
jedis.connect();
if (null != this.password) {
jedis.auth(this.password);
}
if (database != 0) {
jedis.select(database);
}
if (clientName != null) {
jedis.clientSetname(clientName);
}
return new DefaultPooledObject<Jedis>(jedis);
return new DefaultPooledObject<Jedis>(jedis);
}
@Override
public void passivateObject(PooledObject<Jedis> pooledJedis)
throws Exception {
// TODO maybe should select db 0? Not sure right now.
throws Exception {
// TODO maybe should select db 0? Not sure right now.
}
@Override
public boolean validateObject(PooledObject<Jedis> pooledJedis) {
final BinaryJedis jedis = pooledJedis.getObject();
try {
HostAndPort hostAndPort = this.hostAndPort.get();
final BinaryJedis jedis = pooledJedis.getObject();
try {
HostAndPort hostAndPort = this.hostAndPort.get();
String connectionHost = jedis.getClient().getHost();
int connectionPort = jedis.getClient().getPort();
String connectionHost = jedis.getClient().getHost();
int connectionPort = jedis.getClient().getPort();
return hostAndPort.getHost().equals(connectionHost)
&& hostAndPort.getPort() == connectionPort
&& jedis.isConnected() && jedis.ping().equals("PONG");
} catch (final Exception e) {
return false;
}
return hostAndPort.getHost().equals(connectionHost)
&& hostAndPort.getPort() == connectionPort
&& jedis.isConnected() && jedis.ping().equals("PONG");
} catch (final Exception e) {
return false;
}
}
}

View File

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

View File

@@ -12,104 +12,104 @@ import redis.clients.util.Pool;
public class JedisPool extends Pool<Jedis> {
public JedisPool() {
this(Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT);
this(Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host) {
this(poolConfig, host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT,
null, Protocol.DEFAULT_DATABASE, null);
this(poolConfig, host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT,
null, Protocol.DEFAULT_DATABASE, null);
}
public JedisPool(String host, int port) {
this(new GenericObjectPoolConfig(), host, port,
Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE, null);
this(new GenericObjectPoolConfig(), host, port,
Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE, null);
}
public JedisPool(final String host) {
URI uri = URI.create(host);
if (uri.getScheme() != null && uri.getScheme().equals("redis")) {
String h = uri.getHost();
int port = uri.getPort();
String password = JedisURIHelper.getPassword(uri);
int database = 0;
Integer dbIndex = JedisURIHelper.getDBIndex(uri);
if (dbIndex != null) {
database = dbIndex.intValue();
}
this.internalPool = new GenericObjectPool<Jedis>(
new JedisFactory(h, port, Protocol.DEFAULT_TIMEOUT,
password, database, null),
new GenericObjectPoolConfig());
} else {
this.internalPool = new GenericObjectPool<Jedis>(new JedisFactory(
host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT,
null, Protocol.DEFAULT_DATABASE, null),
new GenericObjectPoolConfig());
}
URI uri = URI.create(host);
if (uri.getScheme() != null && uri.getScheme().equals("redis")) {
String h = uri.getHost();
int port = uri.getPort();
String password = JedisURIHelper.getPassword(uri);
int database = 0;
Integer dbIndex = JedisURIHelper.getDBIndex(uri);
if (dbIndex != null) {
database = dbIndex.intValue();
}
this.internalPool = new GenericObjectPool<Jedis>(
new JedisFactory(h, port, Protocol.DEFAULT_TIMEOUT,
password, database, null),
new GenericObjectPoolConfig());
} else {
this.internalPool = new GenericObjectPool<Jedis>(new JedisFactory(
host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT,
null, Protocol.DEFAULT_DATABASE, null),
new GenericObjectPoolConfig());
}
}
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) {
this(new GenericObjectPoolConfig(), uri, timeout);
this(new GenericObjectPoolConfig(), uri, timeout);
}
public JedisPool(final GenericObjectPoolConfig poolConfig,
final String host, int port, int timeout, final String password) {
this(poolConfig, host, port, timeout, password,
Protocol.DEFAULT_DATABASE, null);
final String host, int port, int timeout, final String password) {
this(poolConfig, host, port, timeout, password,
Protocol.DEFAULT_DATABASE, null);
}
public JedisPool(final GenericObjectPoolConfig poolConfig,
final String host, final int port) {
this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT, null,
Protocol.DEFAULT_DATABASE, null);
final String host, final int port) {
this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT, null,
Protocol.DEFAULT_DATABASE, null);
}
public JedisPool(final GenericObjectPoolConfig poolConfig,
final String host, final int port, final int timeout) {
this(poolConfig, host, port, timeout, null, Protocol.DEFAULT_DATABASE,
null);
final String host, final int port, final int timeout) {
this(poolConfig, host, port, timeout, null, Protocol.DEFAULT_DATABASE,
null);
}
public JedisPool(final GenericObjectPoolConfig poolConfig,
final String host, int port, int timeout, final String password,
final int database) {
this(poolConfig, host, port, timeout, password, database, null);
final String host, int port, int timeout, final String password,
final int database) {
this(poolConfig, host, port, timeout, password, database, null);
}
public JedisPool(final GenericObjectPoolConfig poolConfig,
final String host, int port, int timeout, final String password,
final int database, final String clientName) {
super(poolConfig, new JedisFactory(host, port, timeout, password,
database, clientName));
final String host, int port, int timeout, final String password,
final int database, final String clientName) {
super(poolConfig, new JedisFactory(host, port, timeout, password,
database, clientName));
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri) {
this(poolConfig, uri, Protocol.DEFAULT_TIMEOUT);
this(poolConfig, uri, Protocol.DEFAULT_TIMEOUT);
}
public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri,
final int timeout) {
super(poolConfig, new JedisFactory(uri.getHost(), uri.getPort(),
timeout, JedisURIHelper.getPassword(uri),
JedisURIHelper.getDBIndex(uri) != null ? JedisURIHelper
.getDBIndex(uri) : 0, null));
final int timeout) {
super(poolConfig, new JedisFactory(uri.getHost(), uri.getPort(),
timeout, JedisURIHelper.getPassword(uri),
JedisURIHelper.getDBIndex(uri) != null ? JedisURIHelper
.getDBIndex(uri) : 0, null));
}
@Override
public Jedis getResource() {
Jedis jedis = super.getResource();
jedis.setDataSource(this);
return jedis;
Jedis jedis = super.getResource();
jedis.setDataSource(this);
return jedis;
}
public void returnBrokenResource(final Jedis resource) {
if (resource != null) {
returnBrokenResourceObject(resource);
}
if (resource != null) {
returnBrokenResourceObject(resource);
}
}
public void returnResource(final Jedis resource) {
@@ -127,10 +127,10 @@ public class JedisPool extends Pool<Jedis> {
}
public int getNumActive() {
if (this.internalPool == null || this.internalPool.isClosed()) {
return -1;
}
if (this.internalPool == null || this.internalPool.isClosed()) {
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 JedisPoolConfig() {
// defaults to make your life with connection pool easier :)
setTestWhileIdle(true);
setMinEvictableIdleTimeMillis(60000);
setTimeBetweenEvictionRunsMillis(30000);
setNumTestsPerEvictionRun(-1);
// defaults to make your life with connection pool easier :)
setTestWhileIdle(true);
setMinEvictableIdleTimeMillis(60000);
setTimeBetweenEvictionRunsMillis(30000);
setNumTestsPerEvictionRun(-1);
}
}

View File

@@ -18,152 +18,152 @@ public abstract class JedisPubSub {
private int subscribedChannels = 0;
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() {
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub was not subscribed to a Jedis instance.");
}
client.unsubscribe();
client.flush();
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub was not subscribed to a Jedis instance.");
}
client.unsubscribe();
client.flush();
}
public void unsubscribe(String... channels) {
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance.");
}
client.unsubscribe(channels);
client.flush();
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance.");
}
client.unsubscribe(channels);
client.flush();
}
public void subscribe(String... channels) {
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance.");
}
client.subscribe(channels);
client.flush();
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance.");
}
client.subscribe(channels);
client.flush();
}
public void psubscribe(String... patterns) {
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance.");
}
client.psubscribe(patterns);
client.flush();
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance.");
}
client.psubscribe(patterns);
client.flush();
}
public void punsubscribe() {
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance.");
}
client.punsubscribe();
client.flush();
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance.");
}
client.punsubscribe();
client.flush();
}
public void punsubscribe(String... patterns) {
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance.");
}
client.punsubscribe(patterns);
client.flush();
if (client == null) {
throw new JedisConnectionException(
"JedisPubSub is not subscribed to a Jedis instance.");
}
client.punsubscribe(patterns);
client.flush();
}
public boolean isSubscribed() {
return subscribedChannels > 0;
return subscribedChannels > 0;
}
public void proceedWithPatterns(Client client, String... patterns) {
this.client = client;
client.psubscribe(patterns);
client.flush();
process(client);
this.client = client;
client.psubscribe(patterns);
client.flush();
process(client);
}
public void proceed(Client client, String... channels) {
this.client = client;
client.subscribe(channels);
client.flush();
process(client);
this.client = client;
client.subscribe(channels);
client.flush();
process(client);
}
private void process(Client client) {
do {
List<Object> reply = client.getRawObjectMultiBulkReply();
final Object firstObj = reply.get(0);
if (!(firstObj instanceof byte[])) {
throw new JedisException("Unknown message type: " + firstObj);
}
final byte[] resp = (byte[]) firstObj;
if (Arrays.equals(SUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bchannel = (byte[]) reply.get(1);
final String strchannel = (bchannel == null) ? null
: SafeEncoder.encode(bchannel);
onSubscribe(strchannel, subscribedChannels);
} else if (Arrays.equals(UNSUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bchannel = (byte[]) reply.get(1);
final String strchannel = (bchannel == null) ? null
: SafeEncoder.encode(bchannel);
onUnsubscribe(strchannel, subscribedChannels);
} else if (Arrays.equals(MESSAGE.raw, resp)) {
final byte[] bchannel = (byte[]) reply.get(1);
final byte[] bmesg = (byte[]) reply.get(2);
final String strchannel = (bchannel == null) ? null
: SafeEncoder.encode(bchannel);
final String strmesg = (bmesg == null) ? null : SafeEncoder
.encode(bmesg);
onMessage(strchannel, strmesg);
} else if (Arrays.equals(PMESSAGE.raw, resp)) {
final byte[] bpattern = (byte[]) reply.get(1);
final byte[] bchannel = (byte[]) reply.get(2);
final byte[] bmesg = (byte[]) reply.get(3);
final String strpattern = (bpattern == null) ? null
: SafeEncoder.encode(bpattern);
final String strchannel = (bchannel == null) ? null
: SafeEncoder.encode(bchannel);
final String strmesg = (bmesg == null) ? null : SafeEncoder
.encode(bmesg);
onPMessage(strpattern, strchannel, strmesg);
} else if (Arrays.equals(PSUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bpattern = (byte[]) reply.get(1);
final String strpattern = (bpattern == null) ? null
: SafeEncoder.encode(bpattern);
onPSubscribe(strpattern, subscribedChannels);
} else if (Arrays.equals(PUNSUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bpattern = (byte[]) reply.get(1);
final String strpattern = (bpattern == null) ? null
: SafeEncoder.encode(bpattern);
onPUnsubscribe(strpattern, subscribedChannels);
} else {
throw new JedisException("Unknown message type: " + firstObj);
}
} while (isSubscribed());
do {
List<Object> reply = client.getRawObjectMultiBulkReply();
final Object firstObj = reply.get(0);
if (!(firstObj instanceof byte[])) {
throw new JedisException("Unknown message type: " + firstObj);
}
final byte[] resp = (byte[]) firstObj;
if (Arrays.equals(SUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bchannel = (byte[]) reply.get(1);
final String strchannel = (bchannel == null) ? null
: SafeEncoder.encode(bchannel);
onSubscribe(strchannel, subscribedChannels);
} else if (Arrays.equals(UNSUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bchannel = (byte[]) reply.get(1);
final String strchannel = (bchannel == null) ? null
: SafeEncoder.encode(bchannel);
onUnsubscribe(strchannel, subscribedChannels);
} else if (Arrays.equals(MESSAGE.raw, resp)) {
final byte[] bchannel = (byte[]) reply.get(1);
final byte[] bmesg = (byte[]) reply.get(2);
final String strchannel = (bchannel == null) ? null
: SafeEncoder.encode(bchannel);
final String strmesg = (bmesg == null) ? null : SafeEncoder
.encode(bmesg);
onMessage(strchannel, strmesg);
} else if (Arrays.equals(PMESSAGE.raw, resp)) {
final byte[] bpattern = (byte[]) reply.get(1);
final byte[] bchannel = (byte[]) reply.get(2);
final byte[] bmesg = (byte[]) reply.get(3);
final String strpattern = (bpattern == null) ? null
: SafeEncoder.encode(bpattern);
final String strchannel = (bchannel == null) ? null
: SafeEncoder.encode(bchannel);
final String strmesg = (bmesg == null) ? null : SafeEncoder
.encode(bmesg);
onPMessage(strpattern, strchannel, strmesg);
} else if (Arrays.equals(PSUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bpattern = (byte[]) reply.get(1);
final String strpattern = (bpattern == null) ? null
: SafeEncoder.encode(bpattern);
onPSubscribe(strpattern, subscribedChannels);
} else if (Arrays.equals(PUNSUBSCRIBE.raw, resp)) {
subscribedChannels = ((Long) reply.get(2)).intValue();
final byte[] bpattern = (byte[]) reply.get(1);
final String strpattern = (bpattern == null) ? null
: SafeEncoder.encode(bpattern);
onPUnsubscribe(strpattern, subscribedChannels);
} else {
throw new JedisException("Unknown message type: " + firstObj);
}
} while (isSubscribed());
/* Invalidate instance since this thread is no longer listening */
this.client = null;
/* Invalidate instance since this thread is no longer listening */
this.client = null;
}
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());
public JedisSentinelPool(String masterName, Set<String> sentinels,
final GenericObjectPoolConfig poolConfig) {
this(masterName, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT, null,
Protocol.DEFAULT_DATABASE);
final GenericObjectPoolConfig poolConfig) {
this(masterName, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT, null,
Protocol.DEFAULT_DATABASE);
}
public JedisSentinelPool(String masterName, Set<String> sentinels) {
this(masterName, sentinels, new GenericObjectPoolConfig(),
Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE);
this(masterName, sentinels, new GenericObjectPoolConfig(),
Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE);
}
public JedisSentinelPool(String masterName, Set<String> sentinels,
String password) {
this(masterName, sentinels, new GenericObjectPoolConfig(),
Protocol.DEFAULT_TIMEOUT, password);
String password) {
this(masterName, sentinels, new GenericObjectPoolConfig(),
Protocol.DEFAULT_TIMEOUT, password);
}
public JedisSentinelPool(String masterName, Set<String> sentinels,
final GenericObjectPoolConfig poolConfig, int timeout,
final String password) {
this(masterName, sentinels, poolConfig, timeout, password,
Protocol.DEFAULT_DATABASE);
final GenericObjectPoolConfig poolConfig, int timeout,
final String password) {
this(masterName, sentinels, poolConfig, timeout, password,
Protocol.DEFAULT_DATABASE);
}
public JedisSentinelPool(String masterName, Set<String> sentinels,
final GenericObjectPoolConfig poolConfig, final int timeout) {
this(masterName, sentinels, poolConfig, timeout, null,
Protocol.DEFAULT_DATABASE);
final GenericObjectPoolConfig poolConfig, final int timeout) {
this(masterName, sentinels, poolConfig, timeout, null,
Protocol.DEFAULT_DATABASE);
}
public JedisSentinelPool(String masterName, Set<String> sentinels,
final GenericObjectPoolConfig poolConfig, final String password) {
this(masterName, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT,
password);
final GenericObjectPoolConfig poolConfig, final String password) {
this(masterName, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT,
password);
}
public JedisSentinelPool(String masterName, Set<String> sentinels,
final GenericObjectPoolConfig poolConfig, int timeout,
final String password, final int database) {
final GenericObjectPoolConfig poolConfig, int timeout,
final String password, final int database) {
this.poolConfig = poolConfig;
this.timeout = timeout;
this.password = password;
this.database = database;
this.poolConfig = poolConfig;
this.timeout = timeout;
this.password = password;
this.database = database;
HostAndPort master = initSentinels(sentinels, masterName);
initPool(master);
HostAndPort master = initSentinels(sentinels, masterName);
initPool(master);
}
private volatile JedisFactory factory;
private volatile HostAndPort currentHostMaster;
public void destroy() {
for (MasterListener m : masterListeners) {
m.shutdown();
}
for (MasterListener m : masterListeners) {
m.shutdown();
}
super.destroy();
super.destroy();
}
public HostAndPort getCurrentHostMaster() {
return currentHostMaster;
return currentHostMaster;
}
private void initPool(HostAndPort master) {
if (!master.equals(currentHostMaster)) {
currentHostMaster = master;
if (factory == null) {
factory = new JedisFactory(master.getHost(), master.getPort(),
timeout, password, database);
initPool(poolConfig, factory);
} else {
factory.setHostAndPort(currentHostMaster);
// although we clear the pool, we still have to check the
// returned object
// in getResource, this call only clears idle instances, not
// borrowed instances
internalPool.clear();
}
if (!master.equals(currentHostMaster)) {
currentHostMaster = master;
if (factory == null) {
factory = new JedisFactory(master.getHost(), master.getPort(),
timeout, password, database);
initPool(poolConfig, factory);
} else {
factory.setHostAndPort(currentHostMaster);
// although we clear the pool, we still have to check the
// returned object
// in getResource, this call only clears idle instances, not
// borrowed instances
internalPool.clear();
}
log.info("Created JedisPool to master at " + master);
}
log.info("Created JedisPool to master at " + master);
}
}
private HostAndPort initSentinels(Set<String> sentinels,
final String masterName) {
final String masterName) {
HostAndPort master = null;
boolean sentinelAvailable = false;
HostAndPort master = null;
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) {
final HostAndPort hap = toHostAndPort(Arrays.asList(sentinel
.split(":")));
for (String sentinel : sentinels) {
final HostAndPort hap = toHostAndPort(Arrays.asList(sentinel
.split(":")));
log.fine("Connecting to Sentinel " + hap);
log.fine("Connecting to Sentinel " + hap);
Jedis jedis = null;
try {
jedis = new Jedis(hap.getHost(), hap.getPort());
Jedis jedis = null;
try {
jedis = new Jedis(hap.getHost(), hap.getPort());
List<String> masterAddr = jedis
.sentinelGetMasterAddrByName(masterName);
List<String> masterAddr = jedis
.sentinelGetMasterAddrByName(masterName);
// connected to sentinel...
sentinelAvailable = true;
// connected to sentinel...
sentinelAvailable = true;
if (masterAddr == null || masterAddr.size() != 2) {
log.warning("Can not get master addr, master name: "
+ masterName + ". Sentinel: " + hap + ".");
continue;
}
if (masterAddr == null || masterAddr.size() != 2) {
log.warning("Can not get master addr, master name: "
+ masterName + ". Sentinel: " + hap + ".");
continue;
}
master = toHostAndPort(masterAddr);
log.fine("Found Redis master at " + master);
break;
} catch (JedisConnectionException e) {
log.warning("Cannot connect to sentinel running @ " + hap
+ ". Trying next one.");
} finally {
if (jedis != null) {
jedis.close();
}
}
}
master = toHostAndPort(masterAddr);
log.fine("Found Redis master at " + master);
break;
} catch (JedisConnectionException e) {
log.warning("Cannot connect to sentinel running @ " + hap
+ ". Trying next one.");
} finally {
if (jedis != null) {
jedis.close();
}
}
}
if (master == null) {
if (sentinelAvailable) {
// can connect to sentinel, but master name seems to not
// monitored
throw new JedisException("Can connect to sentinel, but "
+ masterName + " seems to be not monitored...");
} else {
throw new JedisConnectionException(
"All sentinels down, cannot determine where is "
+ masterName + " master is running...");
}
}
if (master == null) {
if (sentinelAvailable) {
// can connect to sentinel, but master name seems to not
// monitored
throw new JedisException("Can connect to sentinel, but "
+ masterName + " seems to be not monitored...");
} else {
throw new JedisConnectionException(
"All sentinels down, cannot determine where is "
+ masterName + " master is running...");
}
}
log.info("Redis master running at " + master
+ ", starting Sentinel listeners...");
log.info("Redis master running at " + master
+ ", starting Sentinel listeners...");
for (String sentinel : sentinels) {
final HostAndPort hap = toHostAndPort(Arrays.asList(sentinel
.split(":")));
MasterListener masterListener = new MasterListener(masterName,
hap.getHost(), hap.getPort());
masterListeners.add(masterListener);
masterListener.start();
}
for (String sentinel : sentinels) {
final HostAndPort hap = toHostAndPort(Arrays.asList(sentinel
.split(":")));
MasterListener masterListener = new MasterListener(masterName,
hap.getHost(), hap.getPort());
masterListeners.add(masterListener);
masterListener.start();
}
return master;
return master;
}
private HostAndPort toHostAndPort(List<String> getMasterAddrByNameResult) {
String host = getMasterAddrByNameResult.get(0);
int port = Integer.parseInt(getMasterAddrByNameResult.get(1));
String host = getMasterAddrByNameResult.get(0);
int port = Integer.parseInt(getMasterAddrByNameResult.get(1));
return new HostAndPort(host, port);
return new HostAndPort(host, port);
}
@Override
public Jedis getResource() {
while (true) {
Jedis jedis = super.getResource();
jedis.setDataSource(this);
while (true) {
Jedis jedis = super.getResource();
jedis.setDataSource(this);
// get a reference because it can change concurrently
final HostAndPort master = currentHostMaster;
final HostAndPort connection = new HostAndPort(jedis.getClient()
.getHost(), jedis.getClient().getPort());
// get a reference because it can change concurrently
final HostAndPort master = currentHostMaster;
final HostAndPort connection = new HostAndPort(jedis.getClient()
.getHost(), jedis.getClient().getPort());
if (master.equals(connection)) {
// connected to the correct master
return jedis;
} else {
returnBrokenResource(jedis);
}
}
if (master.equals(connection)) {
// connected to the correct master
return jedis;
} else {
returnBrokenResource(jedis);
}
}
}
public void returnBrokenResource(final Jedis resource) {
if (resource != null) {
returnBrokenResourceObject(resource);
}
if (resource != null) {
returnBrokenResourceObject(resource);
}
}
public void returnResource(final Jedis resource) {
if (resource != null) {
resource.resetState();
returnResourceObject(resource);
}
if (resource != null) {
resource.resetState();
returnResourceObject(resource);
}
}
protected class MasterListener extends Thread {
protected String masterName;
protected String host;
protected int port;
protected long subscribeRetryWaitTimeMillis = 5000;
protected Jedis j;
protected AtomicBoolean running = new AtomicBoolean(false);
protected String masterName;
protected String host;
protected int port;
protected long subscribeRetryWaitTimeMillis = 5000;
protected Jedis j;
protected AtomicBoolean running = new AtomicBoolean(false);
protected MasterListener() {
}
protected MasterListener() {
}
public MasterListener(String masterName, String host, int port) {
this.masterName = masterName;
this.host = host;
this.port = port;
}
public MasterListener(String masterName, String host, int port) {
this.masterName = masterName;
this.host = host;
this.port = port;
}
public MasterListener(String masterName, String host, int port,
long subscribeRetryWaitTimeMillis) {
this(masterName, host, port);
this.subscribeRetryWaitTimeMillis = subscribeRetryWaitTimeMillis;
}
public MasterListener(String masterName, String host, int port,
long subscribeRetryWaitTimeMillis) {
this(masterName, host, port);
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 {
j.subscribe(new JedisPubSub() {
@Override
public void onMessage(String channel, String message) {
log.fine("Sentinel " + host + ":" + port
+ " published: " + message + ".");
try {
j.subscribe(new JedisPubSub() {
@Override
public void onMessage(String channel, String message) {
log.fine("Sentinel " + host + ":" + port
+ " published: " + message + ".");
String[] switchMasterMsg = message.split(" ");
String[] switchMasterMsg = message.split(" ");
if (switchMasterMsg.length > 3) {
if (switchMasterMsg.length > 3) {
if (masterName.equals(switchMasterMsg[0])) {
initPool(toHostAndPort(Arrays.asList(
switchMasterMsg[3],
switchMasterMsg[4])));
} else {
log.fine("Ignoring message on +switch-master for master name "
+ switchMasterMsg[0]
+ ", our master name is "
+ masterName);
}
if (masterName.equals(switchMasterMsg[0])) {
initPool(toHostAndPort(Arrays.asList(
switchMasterMsg[3],
switchMasterMsg[4])));
} else {
log.fine("Ignoring message on +switch-master for master name "
+ switchMasterMsg[0]
+ ", our master name is "
+ masterName);
}
} else {
log.severe("Invalid message received on Sentinel "
+ host
+ ":"
+ port
+ " on channel +switch-master: "
+ message);
}
}
}, "+switch-master");
} else {
log.severe("Invalid message received on Sentinel "
+ host
+ ":"
+ port
+ " on channel +switch-master: "
+ message);
}
}
}, "+switch-master");
} catch (JedisConnectionException e) {
} catch (JedisConnectionException e) {
if (running.get()) {
log.severe("Lost connection to Sentinel at " + host
+ ":" + port
+ ". Sleeping 5000ms and retrying.");
try {
Thread.sleep(subscribeRetryWaitTimeMillis);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} else {
log.fine("Unsubscribing from Sentinel at " + host + ":"
+ port);
}
}
}
}
if (running.get()) {
log.severe("Lost connection to Sentinel at " + host
+ ":" + port
+ ". Sleeping 5000ms and retrying.");
try {
Thread.sleep(subscribeRetryWaitTimeMillis);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} else {
log.fine("Unsubscribing from Sentinel at " + host + ":"
+ port);
}
}
}
}
public void shutdown() {
try {
log.fine("Shutting down listener on " + host + ":" + port);
running.set(false);
// This isn't good, the Jedis object is not thread safe
j.disconnect();
} catch (Exception e) {
log.severe("Caught exception while shutting down: "
+ e.getMessage());
}
}
public void shutdown() {
try {
log.fine("Shutting down listener on " + host + ":" + port);
running.set(false);
// This isn't good, the Jedis object is not thread safe
j.disconnect();
} catch (Exception e) {
log.severe("Caught exception while shutting down: "
+ e.getMessage());
}
}
}
}

View File

@@ -7,7 +7,7 @@ import redis.clients.util.Sharded;
public class JedisShardInfo extends ShardInfo<Jedis> {
public String toString() {
return host + ":" + port + "*" + getWeight();
return host + ":" + port + "*" + getWeight();
}
private int timeout;
@@ -17,83 +17,83 @@ public class JedisShardInfo extends ShardInfo<Jedis> {
private String name = null;
public String getHost() {
return host;
return host;
}
public int getPort() {
return port;
return port;
}
public JedisShardInfo(String host) {
super(Sharded.DEFAULT_WEIGHT);
URI uri = URI.create(host);
if (uri.getScheme() != null && uri.getScheme().equals("redis")) {
this.host = uri.getHost();
this.port = uri.getPort();
this.password = uri.getUserInfo().split(":", 2)[1];
} else {
this.host = host;
this.port = Protocol.DEFAULT_PORT;
}
super(Sharded.DEFAULT_WEIGHT);
URI uri = URI.create(host);
if (uri.getScheme() != null && uri.getScheme().equals("redis")) {
this.host = uri.getHost();
this.port = uri.getPort();
this.password = uri.getUserInfo().split(":", 2)[1];
} else {
this.host = host;
this.port = Protocol.DEFAULT_PORT;
}
}
public JedisShardInfo(String host, String name) {
this(host, Protocol.DEFAULT_PORT, name);
this(host, Protocol.DEFAULT_PORT, name);
}
public JedisShardInfo(String host, int port) {
this(host, port, 2000);
this(host, port, 2000);
}
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) {
this(host, port, timeout, Sharded.DEFAULT_WEIGHT);
this(host, port, timeout, Sharded.DEFAULT_WEIGHT);
}
public JedisShardInfo(String host, int port, int timeout, String name) {
this(host, port, timeout, Sharded.DEFAULT_WEIGHT);
this.name = name;
this(host, port, timeout, Sharded.DEFAULT_WEIGHT);
this.name = name;
}
public JedisShardInfo(String host, int port, int timeout, int weight) {
super(weight);
this.host = host;
this.port = port;
this.timeout = timeout;
super(weight);
this.host = host;
this.port = port;
this.timeout = timeout;
}
public JedisShardInfo(URI uri) {
super(Sharded.DEFAULT_WEIGHT);
this.host = uri.getHost();
this.port = uri.getPort();
this.password = uri.getUserInfo().split(":", 2)[1];
super(Sharded.DEFAULT_WEIGHT);
this.host = uri.getHost();
this.port = uri.getPort();
this.password = uri.getUserInfo().split(":", 2)[1];
}
public String getPassword() {
return password;
return password;
}
public void setPassword(String auth) {
this.password = auth;
this.password = auth;
}
public int getTimeout() {
return timeout;
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
this.timeout = timeout;
}
public String getName() {
return name;
return name;
}
@Override
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;
public class JedisSlotBasedConnectionHandler extends
JedisClusterConnectionHandler {
JedisClusterConnectionHandler {
public JedisSlotBasedConnectionHandler(Set<HostAndPort> nodes,
final GenericObjectPoolConfig poolConfig) {
super(nodes, poolConfig);
final GenericObjectPoolConfig poolConfig) {
super(nodes, poolConfig);
}
public Jedis getConnection() {
// In antirez's redis-rb-cluster implementation,
// getRandomConnection always return valid connection (able to
// ping-pong)
// or exception if all connections are invalid
// In antirez's redis-rb-cluster implementation,
// getRandomConnection always return valid connection (able to
// ping-pong)
// or exception if all connections are invalid
List<JedisPool> pools = getShuffledNodesPool();
List<JedisPool> pools = getShuffledNodesPool();
for (JedisPool pool : pools) {
Jedis jedis = null;
try {
jedis = pool.getResource();
for (JedisPool pool : pools) {
Jedis jedis = null;
try {
jedis = pool.getResource();
if (jedis == null) {
continue;
}
if (jedis == null) {
continue;
}
String result = jedis.ping();
String result = jedis.ping();
if (result.equalsIgnoreCase("pong"))
return jedis;
if (result.equalsIgnoreCase("pong"))
return jedis;
pool.returnBrokenResource(jedis);
} catch (JedisConnectionException ex) {
if (jedis != null) {
pool.returnBrokenResource(jedis);
}
}
}
pool.returnBrokenResource(jedis);
} catch (JedisConnectionException ex) {
if (jedis != null) {
pool.returnBrokenResource(jedis);
}
}
}
throw new JedisConnectionException("no reachable node in cluster");
throw new JedisConnectionException("no reachable node in cluster");
}
@Override
public Jedis getConnectionFromSlot(int slot) {
JedisPool connectionPool = cache.getSlotPool(slot);
if (connectionPool != null) {
// It can't guaranteed to get valid connection because of node
// assignment
return connectionPool.getResource();
} else {
return getConnection();
}
JedisPool connectionPool = cache.getSlotPool(slot);
if (connectionPool != null) {
// It can't guaranteed to get valid connection because of node
// assignment
return connectionPool.getResource();
} else {
return getConnection();
}
}
private List<JedisPool> getShuffledNodesPool() {
List<JedisPool> pools = new ArrayList<JedisPool>();
pools.addAll(cache.getNodes().values());
Collections.shuffle(pools);
return pools;
List<JedisPool> pools = new ArrayList<JedisPool>();
pools.addAll(cache.getNodes().values());
Collections.shuffle(pools);
return pools;
}
}

View File

@@ -40,7 +40,7 @@ public interface MultiKeyBinaryRedisPipeline {
Response<Long> smove(byte[] srckey, byte[] dstkey, byte[] member);
Response<Long> sort(byte[] key, SortingParams sortingParameters,
byte[] dstkey);
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> sort(String key, SortingParams sortingParameters,
String dstkey);
String dstkey);
Response<Long> sort(String key, String dstkey);

View File

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

View File

@@ -10,81 +10,81 @@ public class Pipeline extends MultiKeyPipelineBase {
private MultiResponseBuilder currentMulti;
private class MultiResponseBuilder extends Builder<List<Object>> {
private List<Response<?>> responses = new ArrayList<Response<?>>();
private List<Response<?>> responses = new ArrayList<Response<?>>();
@Override
public List<Object> build(Object data) {
@SuppressWarnings("unchecked")
List<Object> list = (List<Object>) data;
List<Object> values = new ArrayList<Object>();
@Override
public List<Object> build(Object data) {
@SuppressWarnings("unchecked")
List<Object> list = (List<Object>) data;
List<Object> values = new ArrayList<Object>();
if (list.size() != responses.size()) {
throw new JedisDataException("Expected data size "
+ responses.size() + " but was " + list.size());
}
if (list.size() != responses.size()) {
throw new JedisDataException("Expected data size "
+ responses.size() + " but was " + list.size());
}
for (int i = 0; i < list.size(); i++) {
Response<?> response = responses.get(i);
response.set(list.get(i));
Object builtResponse;
try {
builtResponse = response.get();
} catch (JedisDataException e) {
builtResponse = e;
}
values.add(builtResponse);
}
return values;
}
for (int i = 0; i < list.size(); i++) {
Response<?> response = responses.get(i);
response.set(list.get(i));
Object builtResponse;
try {
builtResponse = response.get();
} catch (JedisDataException e) {
builtResponse = e;
}
values.add(builtResponse);
}
return values;
}
public void setResponseDependency(Response<?> dependency) {
for (Response<?> response : responses) {
response.setDependency(dependency);
}
}
public void setResponseDependency(Response<?> dependency) {
for (Response<?> response : responses) {
response.setDependency(dependency);
}
}
public void addResponse(Response<?> response) {
responses.add(response);
}
public void addResponse(Response<?> response) {
responses.add(response);
}
}
@Override
protected <T> Response<T> getResponse(Builder<T> builder) {
if (currentMulti != null) {
super.getResponse(BuilderFactory.STRING); // Expected QUEUED
if (currentMulti != null) {
super.getResponse(BuilderFactory.STRING); // Expected QUEUED
Response<T> lr = new Response<T>(builder);
currentMulti.addResponse(lr);
return lr;
} else {
return super.getResponse(builder);
}
Response<T> lr = new Response<T>(builder);
currentMulti.addResponse(lr);
return lr;
} else {
return super.getResponse(builder);
}
}
public void setClient(Client client) {
this.client = client;
this.client = client;
}
@Override
protected Client getClient(byte[] key) {
return client;
return client;
}
@Override
protected Client getClient(String key) {
return client;
return client;
}
public void clear() {
if (isInMulti()) {
discard();
}
if (isInMulti()) {
discard();
}
sync();
sync();
}
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.
*/
public void sync() {
if (getPipelinedResponseLength() > 0) {
if (getPipelinedResponseLength() > 0) {
List<Object> unformatted = client.getMany(getPipelinedResponseLength());
for (Object o : unformatted) {
generateResponse(o);
}
}
}
}
/**
* Synchronize pipeline by reading all responses. This operation close the
@@ -126,33 +126,33 @@ public class Pipeline extends MultiKeyPipelineBase {
}
public Response<String> discard() {
if (currentMulti == null)
throw new JedisDataException("DISCARD without MULTI");
client.discard();
currentMulti = null;
return getResponse(BuilderFactory.STRING);
if (currentMulti == null)
throw new JedisDataException("DISCARD without MULTI");
client.discard();
currentMulti = null;
return getResponse(BuilderFactory.STRING);
}
public Response<List<Object>> exec() {
if (currentMulti == null)
throw new JedisDataException("EXEC without MULTI");
if (currentMulti == null)
throw new JedisDataException("EXEC without MULTI");
client.exec();
Response<List<Object>> response = super.getResponse(currentMulti);
currentMulti.setResponseDependency(response);
currentMulti = null;
return response;
client.exec();
Response<List<Object>> response = super.getResponse(currentMulti);
currentMulti.setResponseDependency(response);
currentMulti = null;
return response;
}
public Response<String> multi() {
if (currentMulti != null)
throw new JedisDataException("MULTI calls can not be nested");
if (currentMulti != null)
throw new JedisDataException("MULTI calls can not be nested");
client.multi();
Response<String> response = getResponse(BuilderFactory.STRING); // Expecting
// OK
currentMulti = new MultiResponseBuilder();
return response;
client.multi();
Response<String> response = getResponse(BuilderFactory.STRING); // Expecting
// OK
currentMulti = new MultiResponseBuilder();
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";
private Protocol() {
// this prevent the class from instantiation
// this prevent the class from instantiation
}
public static void sendCommand(final RedisOutputStream os,
final Command command, final byte[]... args) {
sendCommand(os, command.raw, args);
final Command command, final byte[]... args) {
sendCommand(os, command.raw, args);
}
private static void sendCommand(final RedisOutputStream os,
final byte[] command, final byte[]... args) {
try {
os.write(ASTERISK_BYTE);
os.writeIntCrLf(args.length + 1);
os.write(DOLLAR_BYTE);
os.writeIntCrLf(command.length);
os.write(command);
os.writeCrLf();
final byte[] command, final byte[]... args) {
try {
os.write(ASTERISK_BYTE);
os.writeIntCrLf(args.length + 1);
os.write(DOLLAR_BYTE);
os.writeIntCrLf(command.length);
os.write(command);
os.writeCrLf();
for (final byte[] arg : args) {
os.write(DOLLAR_BYTE);
os.writeIntCrLf(arg.length);
os.write(arg);
os.writeCrLf();
}
} catch (IOException e) {
throw new JedisConnectionException(e);
}
for (final byte[] arg : args) {
os.write(DOLLAR_BYTE);
os.writeIntCrLf(arg.length);
os.write(arg);
os.writeCrLf();
}
} catch (IOException e) {
throw new JedisConnectionException(e);
}
}
private static void processError(final RedisInputStream is) {
String message = is.readLine();
// TODO: I'm not sure if this is the best way to do this.
// Maybe Read only first 5 bytes instead?
if (message.startsWith(MOVED_RESPONSE)) {
String[] movedInfo = parseTargetHostAndSlot(message);
throw new JedisMovedDataException(message, new HostAndPort(
movedInfo[1], Integer.valueOf(movedInfo[2])),
Integer.valueOf(movedInfo[0]));
} else if (message.startsWith(ASK_RESPONSE)) {
String[] askInfo = parseTargetHostAndSlot(message);
throw new JedisAskDataException(message, new HostAndPort(
askInfo[1], Integer.valueOf(askInfo[2])),
Integer.valueOf(askInfo[0]));
} else if (message.startsWith(CLUSTERDOWN_RESPONSE)) {
throw new JedisClusterException(message);
}
throw new JedisDataException(message);
String message = is.readLine();
// TODO: I'm not sure if this is the best way to do this.
// Maybe Read only first 5 bytes instead?
if (message.startsWith(MOVED_RESPONSE)) {
String[] movedInfo = parseTargetHostAndSlot(message);
throw new JedisMovedDataException(message, new HostAndPort(
movedInfo[1], Integer.valueOf(movedInfo[2])),
Integer.valueOf(movedInfo[0]));
} else if (message.startsWith(ASK_RESPONSE)) {
String[] askInfo = parseTargetHostAndSlot(message);
throw new JedisAskDataException(message, new HostAndPort(
askInfo[1], Integer.valueOf(askInfo[2])),
Integer.valueOf(askInfo[0]));
} else if (message.startsWith(CLUSTERDOWN_RESPONSE)) {
throw new JedisClusterException(message);
}
throw new JedisDataException(message);
}
private static String[] parseTargetHostAndSlot(
String clusterRedirectResponse) {
String[] response = new String[3];
String[] messageInfo = clusterRedirectResponse.split(" ");
String[] targetHostAndPort = messageInfo[2].split(":");
response[0] = messageInfo[1];
response[1] = targetHostAndPort[0];
response[2] = targetHostAndPort[1];
return response;
String clusterRedirectResponse) {
String[] response = new String[3];
String[] messageInfo = clusterRedirectResponse.split(" ");
String[] targetHostAndPort = messageInfo[2].split(":");
response[0] = messageInfo[1];
response[1] = targetHostAndPort[0];
response[2] = targetHostAndPort[1];
return response;
}
private static Object process(final RedisInputStream is) {
final byte b = is.readByte();
if (b == PLUS_BYTE) {
return processStatusCodeReply(is);
} else if (b == DOLLAR_BYTE) {
return processBulkReply(is);
} else if (b == ASTERISK_BYTE) {
return processMultiBulkReply(is);
} else if (b == COLON_BYTE) {
return processInteger(is);
} else if (b == MINUS_BYTE) {
processError(is);
return null;
} else {
throw new JedisConnectionException("Unknown reply: " + (char) b);
}
final byte b = is.readByte();
if (b == PLUS_BYTE) {
return processStatusCodeReply(is);
} else if (b == DOLLAR_BYTE) {
return processBulkReply(is);
} else if (b == ASTERISK_BYTE) {
return processMultiBulkReply(is);
} else if (b == COLON_BYTE) {
return processInteger(is);
} else if (b == MINUS_BYTE) {
processError(is);
return null;
} else {
throw new JedisConnectionException("Unknown reply: " + (char) b);
}
}
private static byte[] processStatusCodeReply(final RedisInputStream is) {
return is.readLineBytes();
return is.readLineBytes();
}
private static byte[] processBulkReply(final RedisInputStream is) {
final int len = is.readIntCrLf();
if (len == -1) {
return null;
}
final int len = is.readIntCrLf();
if (len == -1) {
return null;
}
final byte[] read = new byte[len];
int offset = 0;
while (offset < len) {
final int size = is.read(read, offset, (len - offset));
if (size == -1)
throw new JedisConnectionException(
"It seems like server has closed the connection.");
offset += size;
}
final byte[] read = new byte[len];
int offset = 0;
while (offset < len) {
final int size = is.read(read, offset, (len - offset));
if (size == -1)
throw new JedisConnectionException(
"It seems like server has closed the connection.");
offset += size;
}
// read 2 more bytes for the command delimiter
is.readByte();
is.readByte();
// read 2 more bytes for the command delimiter
is.readByte();
is.readByte();
return read;
return read;
}
private static Long processInteger(final RedisInputStream is) {
return is.readLongCrLf();
return is.readLongCrLf();
}
private static List<Object> processMultiBulkReply(final RedisInputStream is) {
final int num = is.readIntCrLf();
if (num == -1) {
return null;
}
final List<Object> ret = new ArrayList<Object>(num);
for (int i = 0; i < num; i++) {
try {
ret.add(process(is));
} catch (JedisDataException e) {
ret.add(e);
}
}
return ret;
final int num = is.readIntCrLf();
if (num == -1) {
return null;
}
final List<Object> ret = new ArrayList<Object>(num);
for (int i = 0; i < num; i++) {
try {
ret.add(process(is));
} catch (JedisDataException e) {
ret.add(e);
}
}
return ret;
}
public static Object read(final RedisInputStream is) {
return process(is);
return process(is);
}
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) {
return SafeEncoder.encode(String.valueOf(value));
return SafeEncoder.encode(String.valueOf(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) {
return SafeEncoder.encode(String.valueOf(value));
return SafeEncoder.encode(String.valueOf(value));
}
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() {
raw = SafeEncoder.encode(this.name());
}
Command() {
raw = SafeEncoder.encode(this.name());
}
}
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;
public final byte[] raw;
AGGREGATE, ALPHA, ASC, BY, DESC, GET, LIMIT, MESSAGE, NO, NOSORT, PMESSAGE, PSUBSCRIBE, PUNSUBSCRIBE, OK, ONE, QUEUED, SET, STORE, SUBSCRIBE, UNSUBSCRIBE, WEIGHTS, WITHSCORES, RESETSTAT, RESET, FLUSH, EXISTS, LOAD, KILL, LEN, REFCOUNT, ENCODING, IDLETIME, AND, OR, XOR, NOT, GETNAME, SETNAME, LIST, MATCH, COUNT;
public final byte[] raw;
Keyword() {
raw = SafeEncoder.encode(this.name().toLowerCase());
}
Keyword() {
raw = SafeEncoder.encode(this.name().toLowerCase());
}
}
}

View File

@@ -7,28 +7,28 @@ public class Queable {
private Queue<Response<?>> pipelinedResponses = new LinkedList<Response<?>>();
protected void clean() {
pipelinedResponses.clear();
pipelinedResponses.clear();
}
protected Response<?> generateResponse(Object data) {
Response<?> response = pipelinedResponses.poll();
if (response != null) {
response.set(data);
}
return response;
Response<?> response = pipelinedResponses.poll();
if (response != null) {
response.set(data);
}
return response;
}
protected <T> Response<T> getResponse(Builder<T> builder) {
Response<T> lr = new Response<T>(builder);
pipelinedResponses.add(lr);
return lr;
Response<T> lr = new Response<T>(builder);
pipelinedResponses.add(lr);
return lr;
}
protected boolean hasPipelinedResponse() {
return pipelinedResponses.size() > 0;
return pipelinedResponses.size() > 0;
}
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<Long> linsert(String key, BinaryClient.LIST_POSITION where,
String pivot, String value);
String pivot, String value);
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, double min, double max,
int offset, int count);
int offset, int count);
Response<Set<Tuple>> zrangeByScoreWithScores(String key, double min,
double max);
double max);
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, String max, String 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,
double min);
double min);
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);
@@ -186,22 +186,22 @@ public interface RedisPipeline {
Response<Double> zscore(String key, String member);
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,
final String max);
final String max);
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,
final String min);
final String min);
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,
final String end);
final String end);
Response<Long> bitcount(String key);

View File

@@ -12,50 +12,50 @@ public class Response<T> {
private boolean requestDependencyBuild = false;
public Response(Builder<T> b) {
this.builder = b;
this.builder = b;
}
public void set(Object data) {
this.data = data;
set = true;
this.data = data;
set = true;
}
public T get() {
// if response has dependency response and dependency is not built,
// build it first and no more!!
if (!requestDependencyBuild && dependency != null && dependency.set
&& !dependency.built) {
requestDependencyBuild = true;
dependency.build();
}
if (!set) {
throw new JedisDataException(
"Please close pipeline or multi block before calling this method.");
}
if (!built) {
build();
}
return response;
// if response has dependency response and dependency is not built,
// build it first and no more!!
if (!requestDependencyBuild && dependency != null && dependency.set
&& !dependency.built) {
requestDependencyBuild = true;
dependency.build();
}
if (!set) {
throw new JedisDataException(
"Please close pipeline or multi block before calling this method.");
}
if (!built) {
build();
}
return response;
}
public void setDependency(Response<?> dependency) {
this.dependency = dependency;
this.requestDependencyBuild = false;
this.dependency = dependency;
this.requestDependencyBuild = false;
}
private void build() {
if (data != null) {
if (data instanceof JedisDataException) {
throw new JedisDataException((JedisDataException) data);
}
response = builder.build(data);
}
data = null;
built = true;
if (data != null) {
if (data instanceof JedisDataException) {
throw new JedisDataException((JedisDataException) data);
}
response = builder.build(data);
}
data = null;
built = true;
}
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[]>();
public final static String SCAN_POINTER_START = String.valueOf(0);
public final static byte[] SCAN_POINTER_START_BINARY = SafeEncoder
.encode(SCAN_POINTER_START);
.encode(SCAN_POINTER_START);
public ScanParams match(final byte[] pattern) {
params.add(MATCH.raw);
params.add(pattern);
return this;
params.add(MATCH.raw);
params.add(pattern);
return this;
}
public ScanParams match(final String pattern) {
params.add(MATCH.raw);
params.add(SafeEncoder.encode(pattern));
return this;
params.add(MATCH.raw);
params.add(SafeEncoder.encode(pattern));
return this;
}
public ScanParams count(final int count) {
params.add(COUNT.raw);
params.add(Protocol.toByteArray(count));
return this;
params.add(COUNT.raw);
params.add(Protocol.toByteArray(count));
return this;
}
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;
public ScanResult(String cursor, List<T> results) {
this(SafeEncoder.encode(cursor), results);
this(SafeEncoder.encode(cursor), results);
}
public ScanResult(byte[] cursor, List<T> results) {
this.cursor = cursor;
this.results = results;
this.cursor = cursor;
this.results = results;
}
public String getCursor() {
return SafeEncoder.encode(cursor);
return SafeEncoder.encode(cursor);
}
public byte[] getCursorAsBytes() {
return cursor;
return cursor;
}
public List<T> getResult() {
return results;
return results;
}
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -14,75 +14,75 @@ public class Transaction extends MultiKeyPipelineBase {
protected boolean inTransaction = true;
protected Transaction() {
// client will be set later in transaction block
// client will be set later in transaction block
}
public Transaction(final Client client) {
this.client = client;
this.client = client;
}
@Override
protected Client getClient(String key) {
return client;
return client;
}
@Override
protected Client getClient(byte[] key) {
return client;
return client;
}
public void clear() {
if (inTransaction) {
discard();
}
if (inTransaction) {
discard();
}
}
public List<Object> exec() {
// Discard QUEUED or ERROR
client.getMany(getPipelinedResponseLength());
client.exec();
// Discard QUEUED or ERROR
client.getMany(getPipelinedResponseLength());
client.exec();
List<Object> unformatted = client.getObjectMultiBulkReply();
if (unformatted == null) {
return null;
}
List<Object> formatted = new ArrayList<Object>();
for (Object o : unformatted) {
try {
formatted.add(generateResponse(o).get());
} catch (JedisDataException e) {
formatted.add(e);
}
}
return formatted;
List<Object> unformatted = client.getObjectMultiBulkReply();
if (unformatted == null) {
return null;
}
List<Object> formatted = new ArrayList<Object>();
for (Object o : unformatted) {
try {
formatted.add(generateResponse(o).get());
} catch (JedisDataException e) {
formatted.add(e);
}
}
return formatted;
}
public List<Response<?>> execGetResponse() {
// Discard QUEUED or ERROR
client.getMany(getPipelinedResponseLength());
client.exec();
// Discard QUEUED or ERROR
client.getMany(getPipelinedResponseLength());
client.exec();
List<Object> unformatted = client.getObjectMultiBulkReply();
if (unformatted == null) {
return null;
}
List<Response<?>> response = new ArrayList<Response<?>>();
for (Object o : unformatted) {
response.add(generateResponse(o));
}
return response;
List<Object> unformatted = client.getObjectMultiBulkReply();
if (unformatted == null) {
return null;
}
List<Response<?>> response = new ArrayList<Response<?>>();
for (Object o : unformatted) {
response.add(generateResponse(o));
}
return response;
}
public String discard() {
client.getMany(getPipelinedResponseLength());
client.discard();
inTransaction = false;
clean();
return client.getStatusCodeReply();
client.getMany(getPipelinedResponseLength());
client.discard();
inTransaction = false;
clean();
return client.getStatusCodeReply();
}
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;
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result;
if (null != element) {
for (final byte b : element) {
result = prime * result + b;
}
}
long temp;
temp = Double.doubleToLongBits(score);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
final int prime = 31;
int result = 1;
result = prime * result;
if (null != element) {
for (final byte b : element) {
result = prime * result + b;
}
}
long temp;
temp = Double.doubleToLongBits(score);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Tuple other = (Tuple) obj;
if (element == null) {
if (other.element != null)
return false;
} else if (!Arrays.equals(element, other.element))
return false;
return true;
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Tuple other = (Tuple) obj;
if (element == null) {
if (other.element != null)
return false;
} else if (!Arrays.equals(element, other.element))
return false;
return true;
}
public int compareTo(Tuple other) {
if (Arrays.equals(this.element, other.element))
return 0;
else
return this.score < other.getScore() ? -1 : 1;
if (Arrays.equals(this.element, other.element))
return 0;
else
return this.score < other.getScore() ? -1 : 1;
}
public Tuple(String element, Double score) {
super();
this.element = SafeEncoder.encode(element);
this.score = score;
super();
this.element = SafeEncoder.encode(element);
this.score = score;
}
public Tuple(byte[] element, Double score) {
super();
this.element = element;
this.score = score;
super();
this.element = element;
this.score = score;
}
public String getElement() {
if (null != element) {
return SafeEncoder.encode(element);
} else {
return null;
}
if (null != element) {
return SafeEncoder.encode(element);
} else {
return null;
}
}
public byte[] getBinaryElement() {
return element;
return element;
}
public double getScore() {
return score;
return score;
}
public String toString() {
return '[' + Arrays.toString(element) + ',' + score + ']';
return '[' + Arrays.toString(element) + ',' + score + ']';
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -12,37 +12,37 @@ public class ClusterNodeInformation {
private List<Integer> slotsBeingMigrated;
public ClusterNodeInformation(HostAndPort node) {
this.node = node;
this.availableSlots = new ArrayList<Integer>();
this.slotsBeingImported = new ArrayList<Integer>();
this.slotsBeingMigrated = new ArrayList<Integer>();
this.node = node;
this.availableSlots = new ArrayList<Integer>();
this.slotsBeingImported = new ArrayList<Integer>();
this.slotsBeingMigrated = new ArrayList<Integer>();
}
public void addAvailableSlot(int slot) {
availableSlots.add(slot);
availableSlots.add(slot);
}
public void addSlotBeingImported(int slot) {
slotsBeingImported.add(slot);
slotsBeingImported.add(slot);
}
public void addSlotBeingMigrated(int slot) {
slotsBeingMigrated.add(slot);
slotsBeingMigrated.add(slot);
}
public HostAndPort getNode() {
return node;
return node;
}
public List<Integer> getAvailableSlots() {
return availableSlots;
return availableSlots;
}
public List<Integer> getSlotsBeingImported() {
return slotsBeingImported;
return slotsBeingImported;
}
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 ClusterNodeInformation parse(String nodeInfo, HostAndPort current) {
String[] nodeInfoPartArray = nodeInfo.split(" ");
String[] nodeInfoPartArray = nodeInfo.split(" ");
HostAndPort node = getHostAndPortFromNodeLine(nodeInfoPartArray,
current);
ClusterNodeInformation info = new ClusterNodeInformation(node);
HostAndPort node = getHostAndPortFromNodeLine(nodeInfoPartArray,
current);
ClusterNodeInformation info = new ClusterNodeInformation(node);
if (nodeInfoPartArray.length >= SLOT_INFORMATIONS_START_INDEX) {
String[] slotInfoPartArray = extractSlotParts(nodeInfoPartArray);
fillSlotInformation(slotInfoPartArray, info);
}
if (nodeInfoPartArray.length >= SLOT_INFORMATIONS_START_INDEX) {
String[] slotInfoPartArray = extractSlotParts(nodeInfoPartArray);
fillSlotInformation(slotInfoPartArray, info);
}
return info;
return info;
}
private String[] extractSlotParts(String[] nodeInfoPartArray) {
String[] slotInfoPartArray = new String[nodeInfoPartArray.length
- SLOT_INFORMATIONS_START_INDEX];
for (int i = SLOT_INFORMATIONS_START_INDEX; i < nodeInfoPartArray.length; i++) {
slotInfoPartArray[i - SLOT_INFORMATIONS_START_INDEX] = nodeInfoPartArray[i];
}
return slotInfoPartArray;
String[] slotInfoPartArray = new String[nodeInfoPartArray.length
- SLOT_INFORMATIONS_START_INDEX];
for (int i = SLOT_INFORMATIONS_START_INDEX; i < nodeInfoPartArray.length; i++) {
slotInfoPartArray[i - SLOT_INFORMATIONS_START_INDEX] = nodeInfoPartArray[i];
}
return slotInfoPartArray;
}
public HostAndPort getHostAndPortFromNodeLine(String[] nodeInfoPartArray,
HostAndPort current) {
String stringHostAndPort = nodeInfoPartArray[HOST_AND_PORT_INDEX];
HostAndPort current) {
String stringHostAndPort = nodeInfoPartArray[HOST_AND_PORT_INDEX];
String[] arrayHostAndPort = stringHostAndPort.split(":");
return new HostAndPort(
arrayHostAndPort[0].isEmpty() ? current.getHost()
: arrayHostAndPort[0],
arrayHostAndPort[1].isEmpty() ? current.getPort() : Integer
.valueOf(arrayHostAndPort[1]));
String[] arrayHostAndPort = stringHostAndPort.split(":");
return new HostAndPort(
arrayHostAndPort[0].isEmpty() ? current.getHost()
: arrayHostAndPort[0],
arrayHostAndPort[1].isEmpty() ? current.getPort() : Integer
.valueOf(arrayHostAndPort[1]));
}
private void fillSlotInformation(String[] slotInfoPartArray,
ClusterNodeInformation info) {
for (String slotRange : slotInfoPartArray) {
fillSlotInformationFromSlotRange(slotRange, info);
}
ClusterNodeInformation info) {
for (String slotRange : slotInfoPartArray) {
fillSlotInformationFromSlotRange(slotRange, info);
}
}
private void fillSlotInformationFromSlotRange(String slotRange,
ClusterNodeInformation info) {
if (slotRange.startsWith(SLOT_IN_TRANSITION_IDENTIFIER)) {
// slot is in transition
int slot = Integer.parseInt(slotRange.substring(1).split("-")[0]);
ClusterNodeInformation info) {
if (slotRange.startsWith(SLOT_IN_TRANSITION_IDENTIFIER)) {
// slot is in transition
int slot = Integer.parseInt(slotRange.substring(1).split("-")[0]);
if (slotRange.contains(SLOT_IMPORT_IDENTIFIER)) {
// import
info.addSlotBeingImported(slot);
} else {
// migrate (->-)
info.addSlotBeingMigrated(slot);
}
} else if (slotRange.contains("-")) {
// slot range
String[] slotRangePart = slotRange.split("-");
for (int slot = Integer.valueOf(slotRangePart[0]); slot <= Integer
.valueOf(slotRangePart[1]); slot++) {
info.addAvailableSlot(slot);
}
} else {
// single slot
info.addAvailableSlot(Integer.valueOf(slotRange));
}
if (slotRange.contains(SLOT_IMPORT_IDENTIFIER)) {
// import
info.addSlotBeingImported(slot);
} else {
// migrate (->-)
info.addSlotBeingMigrated(slot);
}
} else if (slotRange.contains("-")) {
// slot range
String[] slotRangePart = slotRange.split("-");
for (int slot = Integer.valueOf(slotRangePart[0]); slot <= Integer
.valueOf(slotRangePart[1]); slot++) {
info.addAvailableSlot(slot);
}
} else {
// single slot
info.addAvailableSlot(Integer.valueOf(slotRange));
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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