upgrade to commons-pool 2

This commit is contained in:
Jonathan Leibiusky
2013-11-28 08:13:57 -05:00
parent 597366343d
commit bbb867781d
19 changed files with 901 additions and 995 deletions

View File

@@ -57,7 +57,6 @@ sentinel monitor mymaster 127.0.0.1 6379 1
sentinel auth-pass mymaster foobared sentinel auth-pass mymaster foobared
sentinel down-after-milliseconds mymaster 3000 sentinel down-after-milliseconds mymaster 3000
sentinel failover-timeout mymaster 900000 sentinel failover-timeout mymaster 900000
sentinel can-failover mymaster yes
sentinel parallel-syncs mymaster 1 sentinel parallel-syncs mymaster 1
pidfile /tmp/sentinel1.pid pidfile /tmp/sentinel1.pid
logfile /tmp/sentinel1.log logfile /tmp/sentinel1.log
@@ -69,7 +68,6 @@ daemonize yes
sentinel monitor mymaster 127.0.0.1 6381 2 sentinel monitor mymaster 127.0.0.1 6381 2
sentinel auth-pass mymaster foobared sentinel auth-pass mymaster foobared
sentinel down-after-milliseconds mymaster 3000 sentinel down-after-milliseconds mymaster 3000
sentinel can-failover mymaster yes
sentinel parallel-syncs mymaster 1 sentinel parallel-syncs mymaster 1
sentinel failover-timeout mymaster 900000 sentinel failover-timeout mymaster 900000
pidfile /tmp/sentinel2.pid pidfile /tmp/sentinel2.pid
@@ -82,7 +80,6 @@ daemonize yes
sentinel monitor mymaster 127.0.0.1 6381 2 sentinel monitor mymaster 127.0.0.1 6381 2
sentinel auth-pass mymaster foobared sentinel auth-pass mymaster foobared
sentinel down-after-milliseconds mymaster 3000 sentinel down-after-milliseconds mymaster 3000
sentinel can-failover mymaster yes
sentinel parallel-syncs mymaster 1 sentinel parallel-syncs mymaster 1
sentinel failover-timeout mymaster 900000 sentinel failover-timeout mymaster 900000
pidfile /tmp/sentinel3.pid pidfile /tmp/sentinel3.pid

10
pom.xml
View File

@@ -59,9 +59,9 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>commons-pool</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-pool</artifactId> <artifactId>commons-pool2</artifactId>
<version>1.6</version> <version>2.0</version>
<type>jar</type> <type>jar</type>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
@@ -115,11 +115,11 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId> <artifactId>maven-release-plugin</artifactId>
<version>2.4.1</version> <version>2.4.2</version>
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-deploy-plugin</artifactId> <artifactId>maven-deploy-plugin</artifactId>
<version>2.7</version> <version>2.8.1</version>
<configuration> <configuration>
<altDeploymentRepository>internal.repo::default::file://${project.build.directory}/mvn-repo</altDeploymentRepository> <altDeploymentRepository>internal.repo::default::file://${project.build.directory}/mvn-repo</altDeploymentRepository>
</configuration> </configuration>

View File

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

View File

@@ -5,8 +5,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import redis.clients.jedis.BinaryClient.LIST_POSITION;
/** /**
* Common interface for sharded and non-sharded BinaryJedis * Common interface for sharded and non-sharded BinaryJedis
*/ */
@@ -159,33 +157,33 @@ public interface BinaryJedisCommands {
Set<byte[]> zrevrangeByScore(byte[] key, byte[] max, byte[] min); Set<byte[]> zrevrangeByScore(byte[] key, byte[] max, byte[] min);
Set<byte[]> zrangeByScore(byte[] key, byte[] min, byte[] max, int offset, Set<byte[]> zrangeByScore(byte[] key, byte[] min, byte[] max, int offset,
int count); int count);
Set<byte[]> zrevrangeByScore(byte[] key, double max, double min, Set<byte[]> zrevrangeByScore(byte[] key, double max, double min,
int offset, int count); int offset, int count);
Set<Tuple> zrangeByScoreWithScores(byte[] key, double min, double max); Set<Tuple> zrangeByScoreWithScores(byte[] key, double min, double max);
Set<Tuple> zrevrangeByScoreWithScores(byte[] key, double max, double min); Set<Tuple> zrevrangeByScoreWithScores(byte[] key, double max, double min);
Set<Tuple> zrangeByScoreWithScores(byte[] key, double min, double max, Set<Tuple> zrangeByScoreWithScores(byte[] key, double min, double max,
int offset, int count); int offset, int count);
Set<byte[]> zrevrangeByScore(byte[] key, byte[] max, byte[] min, Set<byte[]> zrevrangeByScore(byte[] key, byte[] max, byte[] min,
int offset, int count); int offset, int count);
Set<Tuple> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max); Set<Tuple> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max);
Set<Tuple> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min); Set<Tuple> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min);
Set<Tuple> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max, Set<Tuple> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max,
int offset, int count); int offset, int count);
Set<Tuple> zrevrangeByScoreWithScores(byte[] key, double max, double min, Set<Tuple> zrevrangeByScoreWithScores(byte[] key, double max, double min,
int offset, int count); int offset, int count);
Set<Tuple> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min, Set<Tuple> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min,
int offset, int count); int offset, int count);
Long zremrangeByRank(byte[] key, long start, long end); Long zremrangeByRank(byte[] key, long start, long end);
@@ -194,7 +192,7 @@ public interface BinaryJedisCommands {
Long zremrangeByScore(byte[] key, byte[] start, byte[] end); Long zremrangeByScore(byte[] key, byte[] start, byte[] end);
Long linsert(byte[] key, Client.LIST_POSITION where, byte[] pivot, Long linsert(byte[] key, Client.LIST_POSITION where, byte[] pivot,
byte[] value); byte[] value);
Long lpushx(byte[] key, byte[]... arg); Long lpushx(byte[] key, byte[]... arg);

View File

@@ -1,16 +1,15 @@
package redis.clients.jedis; package redis.clients.jedis;
import redis.clients.jedis.BinaryClient.LIST_POSITION;
import redis.clients.util.Hashing;
import redis.clients.util.Sharded;
import java.io.IOException;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import redis.clients.jedis.BinaryClient.LIST_POSITION;
import redis.clients.util.Hashing;
import redis.clients.util.Sharded;
public class BinaryShardedJedis extends Sharded<Jedis, JedisShardInfo> public class BinaryShardedJedis extends Sharded<Jedis, JedisShardInfo>
implements BinaryJedisCommands { implements BinaryJedisCommands {
public BinaryShardedJedis(List<JedisShardInfo> shards) { public BinaryShardedJedis(List<JedisShardInfo> shards) {
@@ -31,10 +30,10 @@ public class BinaryShardedJedis extends Sharded<Jedis, JedisShardInfo>
} }
public void disconnect() { public void disconnect() {
for (Jedis jedis : getAllShards()) { for (Jedis jedis : getAllShards()) {
jedis.quit(); jedis.quit();
jedis.disconnect(); jedis.disconnect();
} }
} }
protected Jedis create(JedisShardInfo shard) { protected Jedis create(JedisShardInfo shard) {
@@ -102,8 +101,8 @@ public class BinaryShardedJedis extends Sharded<Jedis, JedisShardInfo>
} }
public Long del(byte[] key) { public Long del(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.del(key); return j.del(key);
} }
public Long incrBy(byte[] key, long integer) { public Long incrBy(byte[] key, long integer) {
@@ -197,23 +196,23 @@ public class BinaryShardedJedis extends Sharded<Jedis, JedisShardInfo>
} }
public Long strlen(final byte[] key) { public Long strlen(final byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.strlen(key); return j.strlen(key);
} }
public Long lpushx(byte[] key, byte[]... string) { public Long lpushx(byte[] key, byte[]... string) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.lpushx(key, string); return j.lpushx(key, string);
} }
public Long persist(final byte[] key) { public Long persist(final byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.persist(key); return j.persist(key);
} }
public Long rpushx(byte[] key, byte[]... string) { public Long rpushx(byte[] key, byte[]... string) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.rpushx(key, string); return j.rpushx(key, string);
} }
public Long llen(byte[] key) { public Long llen(byte[] key) {
@@ -394,8 +393,8 @@ public class BinaryShardedJedis extends Sharded<Jedis, JedisShardInfo>
} }
public Set<byte[]> zrangeByScore(byte[] key, byte[] min, byte[] max) { public Set<byte[]> zrangeByScore(byte[] key, byte[] min, byte[] max) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrangeByScore(key, min, max); return j.zrangeByScore(key, min, max);
} }
public Set<Tuple> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max) { public Set<Tuple> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max) {
@@ -404,14 +403,15 @@ public class BinaryShardedJedis extends Sharded<Jedis, JedisShardInfo>
} }
public Set<Tuple> zrangeByScoreWithScores(byte[] key, byte[] min, public Set<Tuple> zrangeByScoreWithScores(byte[] key, byte[] min,
byte[] max, int offset, int count) { byte[] max, int offset, int count) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrangeByScoreWithScores(key, min, max, offset, count); return j.zrangeByScoreWithScores(key, min, max, offset, count);
} }
public Set<byte[]> zrangeByScore(byte[] key, byte[] min, byte[] max, int offset, int count) { public Set<byte[]> zrangeByScore(byte[] key, byte[] min, byte[] max,
Jedis j = getShard(key); int offset, int count) {
return j.zrangeByScore(key, min, max, offset, count); Jedis j = getShard(key);
return j.zrangeByScore(key, min, max, offset, count);
} }
public Set<byte[]> zrevrangeByScore(byte[] key, double max, double min) { public Set<byte[]> zrevrangeByScore(byte[] key, double max, double min) {
@@ -449,13 +449,13 @@ public class BinaryShardedJedis extends Sharded<Jedis, JedisShardInfo>
} }
public Set<Tuple> zrevrangeByScoreWithScores(byte[] key, byte[] max, public Set<Tuple> zrevrangeByScoreWithScores(byte[] key, byte[] max,
byte[] min) { byte[] min) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min); return j.zrevrangeByScoreWithScores(key, max, min);
} }
public Set<Tuple> zrevrangeByScoreWithScores(byte[] key, byte[] max, public Set<Tuple> zrevrangeByScoreWithScores(byte[] key, byte[] max,
byte[] min, int offset, int count) { byte[] min, int offset, int count) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.zrevrangeByScoreWithScores(key, max, min, offset, count); return j.zrevrangeByScoreWithScores(key, max, min, offset, count);
} }
@@ -510,57 +510,57 @@ public class BinaryShardedJedis extends Sharded<Jedis, JedisShardInfo>
} }
public Boolean setbit(byte[] key, long offset, boolean value) { public Boolean setbit(byte[] key, long offset, boolean value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.setbit(key, offset, value); return j.setbit(key, offset, value);
} }
public Boolean setbit(byte[] key, long offset, byte[] value) { public Boolean setbit(byte[] key, long offset, byte[] value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.setbit(key, offset, value); return j.setbit(key, offset, value);
} }
public Boolean getbit(byte[] key, long offset) { public Boolean getbit(byte[] key, long offset) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.getbit(key, offset); return j.getbit(key, offset);
} }
public Long setrange(byte[] key, long offset, byte[] value) { public Long setrange(byte[] key, long offset, byte[] value) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.setrange(key, offset, value); return j.setrange(key, offset, value);
} }
public byte[] getrange(byte[] key, long startOffset, long endOffset) { public byte[] getrange(byte[] key, long startOffset, long endOffset) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.getrange(key, startOffset, endOffset); return j.getrange(key, startOffset, endOffset);
} }
public Long move(byte[] key, int dbIndex) { public Long move(byte[] key, int dbIndex) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.move(key, dbIndex); return j.move(key, dbIndex);
} }
public byte[] echo(byte[] arg) { public byte[] echo(byte[] arg) {
Jedis j = getShard(arg); Jedis j = getShard(arg);
return j.echo(arg); return j.echo(arg);
} }
public List<byte[]> brpop(byte[] arg) { public List<byte[]> brpop(byte[] arg) {
Jedis j = getShard(arg); Jedis j = getShard(arg);
return j.brpop(arg); return j.brpop(arg);
} }
public List<byte[]> blpop(byte[] arg) { public List<byte[]> blpop(byte[] arg) {
Jedis j = getShard(arg); Jedis j = getShard(arg);
return j.blpop(arg); return j.blpop(arg);
} }
public Long bitcount(byte[] key) { public Long bitcount(byte[] key) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.bitcount(key); return j.bitcount(key);
} }
public Long bitcount(byte[] key, long start, long end) { public Long bitcount(byte[] key, long start, long end) {
Jedis j = getShard(key); Jedis j = getShard(key);
return j.bitcount(key, start, end); return j.bitcount(key, start, end);
} }
} }

View File

@@ -1,11 +1,13 @@
package redis.clients.jedis; package redis.clients.jedis;
import org.apache.commons.pool.BasePoolableObjectFactory; import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
/** /**
* PoolableObjectFactory custom impl. * PoolableObjectFactory custom impl.
*/ */
class JedisFactory extends BasePoolableObjectFactory { class JedisFactory implements PooledObjectFactory<Jedis> {
private final String host; private final String host;
private final int port; private final int port;
private final int timeout; private final int timeout;
@@ -13,75 +15,80 @@ class JedisFactory extends BasePoolableObjectFactory {
private final int database; private final int database;
private final String clientName; private final String clientName;
public JedisFactory(final String host, final int port, public JedisFactory(final String host, final int port, final int timeout,
final int timeout, final String password, final int database) { final String password, final int database) {
this(host, port, timeout, password, database, null); this(host, port, timeout, password, database, null);
}
public JedisFactory(final String host, final int port,
final int timeout, final String password, final int database, final String clientName) {
super();
this.host = host;
this.port = port;
this.timeout = timeout;
this.password = password;
this.database = database;
this.clientName = clientName;
} }
public Object makeObject() throws Exception { public JedisFactory(final String host, final int port, final int timeout,
final Jedis jedis = new Jedis(this.host, this.port, this.timeout); final String password, final int database, final String clientName) {
super();
jedis.connect(); this.host = host;
if (null != this.password) { this.port = port;
jedis.auth(this.password); this.timeout = timeout;
} this.password = password;
if( database != 0 ) { this.database = database;
jedis.select(database); this.clientName = clientName;
}
if ( clientName != null ) {
jedis.clientSetname(clientName);
}
return jedis;
} }
@Override @Override
public void activateObject(Object obj) throws Exception { public void activateObject(PooledObject<Jedis> pooledJedis)
if (obj instanceof Jedis) { throws Exception {
final Jedis jedis = (Jedis)obj; final BinaryJedis jedis = pooledJedis.getObject();
if (jedis.getDB() != database) { if (jedis.getDB() != database) {
jedis.select(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) {
}
}
} }
public void destroyObject(final Object obj) throws Exception { @Override
if (obj instanceof Jedis) { public PooledObject<Jedis> makeObject() throws Exception {
final Jedis jedis = (Jedis) obj; final Jedis jedis = new Jedis(this.host, this.port, this.timeout);
if (jedis.isConnected()) {
try {
try {
jedis.quit();
} catch (Exception e) {
}
jedis.disconnect();
} catch (Exception e) {
} 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);
} }
public boolean validateObject(final Object obj) { @Override
if (obj instanceof Jedis) { public void passivateObject(PooledObject<Jedis> pooledJedis)
final Jedis jedis = (Jedis) obj; throws Exception {
try { // TODO maybe should select db 0? Not sure right now.
return jedis.isConnected() && jedis.ping().equals("PONG"); }
} catch (final Exception e) {
return false; @Override
} public boolean validateObject(PooledObject<Jedis> pooledJedis) {
} else { final BinaryJedis jedis = pooledJedis.getObject();
return false; try {
} return jedis.isConnected() && jedis.ping().equals("PONG");
} catch (final Exception e) {
return false;
}
} }
} }

View File

@@ -2,19 +2,21 @@ package redis.clients.jedis;
import java.net.URI; import java.net.URI;
import org.apache.commons.pool.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool.impl.GenericObjectPool.Config; import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.util.Pool; import redis.clients.util.Pool;
public class JedisPool extends Pool<Jedis> { public class JedisPool extends Pool<Jedis> {
public JedisPool(final Config poolConfig, final String host) { 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) { public JedisPool(String host, int port) {
this(new Config(), 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) { public JedisPool(final String host) {
@@ -24,12 +26,15 @@ public class JedisPool extends Pool<Jedis> {
int port = uri.getPort(); int port = uri.getPort();
String password = uri.getUserInfo().split(":", 2)[1]; String password = uri.getUserInfo().split(":", 2)[1];
int database = Integer.parseInt(uri.getPath().split("/", 2)[1]); int database = Integer.parseInt(uri.getPath().split("/", 2)[1]);
this.internalPool = new GenericObjectPool(new JedisFactory(h, port, this.internalPool = new GenericObjectPool<Jedis>(
Protocol.DEFAULT_TIMEOUT, password, database, null), new Config()); new JedisFactory(h, port, Protocol.DEFAULT_TIMEOUT,
password, database, null),
new GenericObjectPoolConfig());
} else { } else {
this.internalPool = new GenericObjectPool(new JedisFactory(host, this.internalPool = new GenericObjectPool<Jedis>(new JedisFactory(
Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT, null, host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT,
Protocol.DEFAULT_DATABASE, null), new Config()); null, Protocol.DEFAULT_DATABASE, null),
new GenericObjectPoolConfig());
} }
} }
@@ -38,39 +43,47 @@ public class JedisPool extends Pool<Jedis> {
int port = uri.getPort(); int port = uri.getPort();
String password = uri.getUserInfo().split(":", 2)[1]; String password = uri.getUserInfo().split(":", 2)[1];
int database = Integer.parseInt(uri.getPath().split("/", 2)[1]); int database = Integer.parseInt(uri.getPath().split("/", 2)[1]);
this.internalPool = new GenericObjectPool(new JedisFactory(h, port, this.internalPool = new GenericObjectPool<Jedis>(new JedisFactory(h,
Protocol.DEFAULT_TIMEOUT, password, database, null), new Config()); port, Protocol.DEFAULT_TIMEOUT, password, database, null),
new GenericObjectPoolConfig());
} }
public JedisPool(final Config poolConfig, final String host, int port, public JedisPool(final GenericObjectPoolConfig poolConfig,
int timeout, final String password) { final String host, int port, int timeout, final String password) {
this(poolConfig, host, port, timeout, password, Protocol.DEFAULT_DATABASE, null); this(poolConfig, host, port, timeout, password,
Protocol.DEFAULT_DATABASE, null);
} }
public JedisPool(final Config poolConfig, final String host, final int port) { public JedisPool(final GenericObjectPoolConfig poolConfig,
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 Config poolConfig, final String host, final int port, final int timeout) { public JedisPool(final GenericObjectPoolConfig poolConfig,
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 Config poolConfig, final String host, int port, int timeout, final String password, public JedisPool(final GenericObjectPoolConfig poolConfig,
final int database) { final String host, int port, int timeout, final String password,
this(poolConfig, host, port, timeout, password, database, null); final int database) {
this(poolConfig, host, port, timeout, password, database, null);
} }
public JedisPool(final Config poolConfig, final String host, int port, int timeout, final String password, public JedisPool(final GenericObjectPoolConfig poolConfig,
final int database, final String clientName) { final String host, int port, int timeout, final String password,
super(poolConfig, new JedisFactory(host, port, timeout, password, database, clientName)); final int database, final String clientName) {
super(poolConfig, new JedisFactory(host, port, timeout, password,
database, clientName));
} }
public void returnBrokenResource(final Jedis resource) {
public void returnBrokenResource(final BinaryJedis resource) { returnBrokenResourceObject(resource);
returnBrokenResourceObject(resource);
} }
public void returnResource(final BinaryJedis resource) { public void returnResource(final Jedis resource) {
returnResourceObject(resource); returnResourceObject(resource);
} }
} }

View File

@@ -1,28 +1,8 @@
package redis.clients.jedis; package redis.clients.jedis;
import org.apache.commons.pool.impl.GenericObjectPool.Config; import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
/** public class JedisPoolConfig extends GenericObjectPoolConfig {
* Subclass of org.apache.commons.pool.impl.GenericObjectPool.Config that
* includes getters/setters so it can be more easily configured by Spring and
* other IoC frameworks.
*
* Spring example:
*
* <bean id="jedisConfig" class="redis.clients.jedis.JedisPoolConfig"> <property
* name="testWhileIdle" value="true"/> </bean>
*
* <bean id="jedisPool" class="redis.clients.jedis.JedisPool"
* destroy-method="destroy"> <constructor-arg ref="jedisConfig" />
* <constructor-arg value="localhost" /> <constructor-arg type="int"
* value="6379" /> </bean>
*
* For information on parameters refer to:
*
* http://commons.apache.org/pool/apidocs/org/apache/commons/pool/impl/
* GenericObjectPool.html
*/
public class JedisPoolConfig extends Config {
public JedisPoolConfig() { public JedisPoolConfig() {
// defaults to make your life with connection pool easier :) // defaults to make your life with connection pool easier :)
setTestWhileIdle(true); setTestWhileIdle(true);
@@ -30,103 +10,4 @@ public class JedisPoolConfig extends Config {
setTimeBetweenEvictionRunsMillis(30000); setTimeBetweenEvictionRunsMillis(30000);
setNumTestsPerEvictionRun(-1); setNumTestsPerEvictionRun(-1);
} }
public int getMaxIdle() {
return maxIdle;
}
public void setMaxIdle(int maxIdle) {
this.maxIdle = maxIdle;
}
public int getMinIdle() {
return minIdle;
}
public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
public int getMaxActive() {
return maxActive;
}
public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}
public long getMaxWait() {
return maxWait;
}
public void setMaxWait(long maxWait) {
this.maxWait = maxWait;
}
public byte getWhenExhaustedAction() {
return whenExhaustedAction;
}
public void setWhenExhaustedAction(byte whenExhaustedAction) {
this.whenExhaustedAction = whenExhaustedAction;
}
public boolean isTestOnBorrow() {
return testOnBorrow;
}
public void setTestOnBorrow(boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
public boolean isTestOnReturn() {
return testOnReturn;
}
public void setTestOnReturn(boolean testOnReturn) {
this.testOnReturn = testOnReturn;
}
public boolean isTestWhileIdle() {
return testWhileIdle;
}
public void setTestWhileIdle(boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
}
public long getTimeBetweenEvictionRunsMillis() {
return timeBetweenEvictionRunsMillis;
}
public void setTimeBetweenEvictionRunsMillis(
long timeBetweenEvictionRunsMillis) {
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
public int getNumTestsPerEvictionRun() {
return numTestsPerEvictionRun;
}
public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
this.numTestsPerEvictionRun = numTestsPerEvictionRun;
}
public long getMinEvictableIdleTimeMillis() {
return minEvictableIdleTimeMillis;
}
public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
public long getSoftMinEvictableIdleTimeMillis() {
return softMinEvictableIdleTimeMillis;
}
public void setSoftMinEvictableIdleTimeMillis(
long softMinEvictableIdleTimeMillis) {
this.softMinEvictableIdleTimeMillis = softMinEvictableIdleTimeMillis;
}
} }

View File

@@ -7,14 +7,14 @@ import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.apache.commons.pool.impl.GenericObjectPool.Config; import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.util.Pool; import redis.clients.util.Pool;
public class JedisSentinelPool extends Pool<Jedis> { public class JedisSentinelPool extends Pool<Jedis> {
protected Config poolConfig; protected GenericObjectPoolConfig poolConfig;
protected int timeout = Protocol.DEFAULT_TIMEOUT; protected int timeout = Protocol.DEFAULT_TIMEOUT;
@@ -27,43 +27,44 @@ public class JedisSentinelPool extends Pool<Jedis> {
protected Logger log = Logger.getLogger(getClass().getName()); protected Logger log = Logger.getLogger(getClass().getName());
public JedisSentinelPool(String masterName, Set<String> sentinels, public JedisSentinelPool(String masterName, Set<String> sentinels,
final Config poolConfig) { final GenericObjectPoolConfig poolConfig) {
this(masterName, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT, null, this(masterName, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT, null,
Protocol.DEFAULT_DATABASE); Protocol.DEFAULT_DATABASE);
} }
public JedisSentinelPool(String masterName, Set<String> sentinels) { public JedisSentinelPool(String masterName, Set<String> sentinels) {
this(masterName, sentinels, new Config(), Protocol.DEFAULT_TIMEOUT, this(masterName, sentinels, new GenericObjectPoolConfig(),
null, Protocol.DEFAULT_DATABASE); Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE);
} }
public JedisSentinelPool(String masterName, Set<String> sentinels, public JedisSentinelPool(String masterName, Set<String> sentinels,
String password) { String password) {
this(masterName, sentinels, new Config(), Protocol.DEFAULT_TIMEOUT, this(masterName, sentinels, new GenericObjectPoolConfig(),
password); Protocol.DEFAULT_TIMEOUT, password);
} }
public JedisSentinelPool(String masterName, Set<String> sentinels, public JedisSentinelPool(String masterName, Set<String> sentinels,
final Config poolConfig, int timeout, final String password) { final GenericObjectPoolConfig poolConfig, int timeout,
final String password) {
this(masterName, sentinels, poolConfig, timeout, password, this(masterName, sentinels, poolConfig, timeout, password,
Protocol.DEFAULT_DATABASE); Protocol.DEFAULT_DATABASE);
} }
public JedisSentinelPool(String masterName, Set<String> sentinels, public JedisSentinelPool(String masterName, Set<String> sentinels,
final Config poolConfig, final int timeout) { final GenericObjectPoolConfig poolConfig, final int timeout) {
this(masterName, sentinels, poolConfig, timeout, null, this(masterName, sentinels, poolConfig, timeout, null,
Protocol.DEFAULT_DATABASE); Protocol.DEFAULT_DATABASE);
} }
public JedisSentinelPool(String masterName, Set<String> sentinels, public JedisSentinelPool(String masterName, Set<String> sentinels,
final Config poolConfig, final String password) { final GenericObjectPoolConfig poolConfig, final String password) {
this(masterName, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT, this(masterName, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT,
password); password);
} }
public JedisSentinelPool(String masterName, Set<String> sentinels, public JedisSentinelPool(String masterName, Set<String> sentinels,
final Config poolConfig, int timeout, final String password, final GenericObjectPoolConfig poolConfig, int timeout,
final int database) { final String password, final int database) {
this.poolConfig = poolConfig; this.poolConfig = poolConfig;
this.timeout = timeout; this.timeout = timeout;
this.password = password; this.password = password;
@@ -73,11 +74,11 @@ public class JedisSentinelPool extends Pool<Jedis> {
initPool(master); initPool(master);
} }
public void returnBrokenResource(final BinaryJedis resource) { public void returnBrokenResource(final Jedis resource) {
returnBrokenResourceObject(resource); returnBrokenResourceObject(resource);
} }
public void returnResource(final BinaryJedis resource) { public void returnResource(final Jedis resource) {
returnResourceObject(resource); returnResourceObject(resource);
} }

View File

@@ -3,83 +3,101 @@ package redis.clients.jedis;
import java.util.List; import java.util.List;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.apache.commons.pool.BasePoolableObjectFactory; import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool.impl.GenericObjectPool; import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.util.Hashing; import redis.clients.util.Hashing;
import redis.clients.util.Pool; import redis.clients.util.Pool;
public class ShardedJedisPool extends Pool<ShardedJedis> { public class ShardedJedisPool extends Pool<ShardedJedis> {
public ShardedJedisPool(final GenericObjectPool.Config poolConfig, public ShardedJedisPool(final GenericObjectPoolConfig poolConfig,
List<JedisShardInfo> shards) { List<JedisShardInfo> shards) {
this(poolConfig, shards, Hashing.MURMUR_HASH); this(poolConfig, shards, Hashing.MURMUR_HASH);
} }
public ShardedJedisPool(final GenericObjectPool.Config poolConfig, public ShardedJedisPool(final GenericObjectPoolConfig poolConfig,
List<JedisShardInfo> shards, Hashing algo) { List<JedisShardInfo> shards, Hashing algo) {
this(poolConfig, shards, algo, null); this(poolConfig, shards, algo, null);
} }
public ShardedJedisPool(final GenericObjectPool.Config poolConfig, public ShardedJedisPool(final GenericObjectPoolConfig poolConfig,
List<JedisShardInfo> shards, Pattern keyTagPattern) { List<JedisShardInfo> shards, Pattern keyTagPattern) {
this(poolConfig, shards, Hashing.MURMUR_HASH, keyTagPattern); this(poolConfig, shards, Hashing.MURMUR_HASH, keyTagPattern);
} }
public ShardedJedisPool(final GenericObjectPool.Config poolConfig, public ShardedJedisPool(final GenericObjectPoolConfig poolConfig,
List<JedisShardInfo> shards, Hashing algo, Pattern keyTagPattern) { List<JedisShardInfo> shards, Hashing algo, Pattern keyTagPattern) {
super(poolConfig, new ShardedJedisFactory(shards, algo, keyTagPattern)); super(poolConfig, new ShardedJedisFactory(shards, algo, keyTagPattern));
} }
/** /**
* PoolableObjectFactory custom impl. * PoolableObjectFactory custom impl.
*/ */
private static class ShardedJedisFactory extends BasePoolableObjectFactory { private static class ShardedJedisFactory implements
private List<JedisShardInfo> shards; PooledObjectFactory<ShardedJedis> {
private Hashing algo; private List<JedisShardInfo> shards;
private Pattern keyTagPattern; private Hashing algo;
private Pattern keyTagPattern;
public ShardedJedisFactory(List<JedisShardInfo> shards, Hashing algo, public ShardedJedisFactory(List<JedisShardInfo> shards, Hashing algo,
Pattern keyTagPattern) { Pattern keyTagPattern) {
this.shards = shards; this.shards = shards;
this.algo = algo; this.algo = algo;
this.keyTagPattern = keyTagPattern; this.keyTagPattern = keyTagPattern;
} }
public Object makeObject() throws Exception { @Override
ShardedJedis jedis = new ShardedJedis(shards, algo, keyTagPattern); public PooledObject<ShardedJedis> makeObject() throws Exception {
return jedis; ShardedJedis jedis = new ShardedJedis(shards, algo, keyTagPattern);
} return new DefaultPooledObject<ShardedJedis>(jedis);
}
public void destroyObject(final Object obj) throws Exception { @Override
if ((obj != null) && (obj instanceof ShardedJedis)) { public void destroyObject(PooledObject<ShardedJedis> pooledShardedJedis)
ShardedJedis shardedJedis = (ShardedJedis) obj; throws Exception {
for (Jedis jedis : shardedJedis.getAllShards()) { final ShardedJedis shardedJedis = pooledShardedJedis.getObject();
try { for (Jedis jedis : shardedJedis.getAllShards()) {
try { try {
jedis.quit(); try {
} catch (Exception e) { jedis.quit();
} catch (Exception e) {
} }
jedis.disconnect(); jedis.disconnect();
} catch (Exception e) { } catch (Exception e) {
} }
} }
} }
}
public boolean validateObject(final Object obj) { @Override
try { public boolean validateObject(
ShardedJedis jedis = (ShardedJedis) obj; PooledObject<ShardedJedis> pooledShardedJedis) {
for (Jedis shard : jedis.getAllShards()) { try {
if (!shard.ping().equals("PONG")) { ShardedJedis jedis = pooledShardedJedis.getObject();
return false; for (Jedis shard : jedis.getAllShards()) {
} if (!shard.ping().equals("PONG")) {
} return false;
return true; }
} catch (Exception ex) { }
return false; return true;
} } catch (Exception ex) {
} return false;
}
}
@Override
public void activateObject(PooledObject<ShardedJedis> p)
throws Exception {
}
@Override
public void passivateObject(PooledObject<ShardedJedis> p)
throws Exception {
}
} }
} }

View File

@@ -1,82 +1,84 @@
package redis.clients.util; package redis.clients.util;
import org.apache.commons.pool.PoolableObjectFactory; import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisException; import redis.clients.jedis.exceptions.JedisException;
public abstract class Pool<T> { public abstract class Pool<T> {
protected GenericObjectPool internalPool; protected GenericObjectPool<T> internalPool;
/** /**
* Using this constructor means you have to set * Using this constructor means you have to set and initialize the
* and initialize the internalPool yourself. * internalPool yourself.
*/ */
public Pool() {} public Pool() {
public Pool(final GenericObjectPool.Config poolConfig,
PoolableObjectFactory factory) {
initPool(poolConfig, factory);
} }
public void initPool(final GenericObjectPool.Config poolConfig, PoolableObjectFactory factory) { public Pool(final GenericObjectPoolConfig poolConfig,
PooledObjectFactory<T> factory) {
if (this.internalPool != null) { initPool(poolConfig, factory);
try { }
closeInternalPool();
} catch (Exception e) { public void initPool(final GenericObjectPoolConfig poolConfig,
} PooledObjectFactory<T> factory) {
}
if (this.internalPool != null) {
this.internalPool = new GenericObjectPool(factory, poolConfig); try {
closeInternalPool();
} catch (Exception e) {
}
}
this.internalPool = new GenericObjectPool<T>(factory, poolConfig);
} }
@SuppressWarnings("unchecked")
public T getResource() { public T getResource() {
try { try {
return (T) internalPool.borrowObject(); return internalPool.borrowObject();
} catch (Exception e) { } catch (Exception e) {
throw new JedisConnectionException( throw new JedisConnectionException(
"Could not get a resource from the pool", e); "Could not get a resource from the pool", e);
} }
} }
public void returnResourceObject(final Object resource) { public void returnResourceObject(final T resource) {
try { try {
internalPool.returnObject(resource); internalPool.returnObject(resource);
} catch (Exception e) { } catch (Exception e) {
throw new JedisException( throw new JedisException(
"Could not return the resource to the pool", e); "Could not return the resource to the pool", e);
} }
} }
public void returnBrokenResource(final T resource) { public void returnBrokenResource(final T resource) {
returnBrokenResourceObject(resource); returnBrokenResourceObject(resource);
} }
public void returnResource(final T resource) { public void returnResource(final T resource) {
returnResourceObject(resource); returnResourceObject(resource);
} }
public void destroy() { public void destroy() {
closeInternalPool(); closeInternalPool();
} }
protected void returnBrokenResourceObject(final Object resource) { protected void returnBrokenResourceObject(final T resource) {
try { try {
internalPool.invalidateObject(resource); internalPool.invalidateObject(resource);
} catch (Exception e) { } catch (Exception e) {
throw new JedisException( throw new JedisException(
"Could not return the resource to the pool", e); "Could not return the resource to the pool", e);
} }
} }
protected void closeInternalPool() { protected void closeInternalPool() {
try { try {
internalPool.close(); internalPool.close();
} catch (Exception e) { } catch (Exception e) {
throw new JedisException("Could not destroy the pool", e); throw new JedisException("Could not destroy the pool", e);
} }
} }
} }

View File

@@ -3,12 +3,10 @@ package redis.clients.jedis.tests;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import org.apache.commons.pool.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.apache.commons.pool.impl.GenericObjectPool.Config;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import redis.clients.jedis.BinaryJedis;
import redis.clients.jedis.Jedis; import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.JedisPoolConfig;
@@ -20,111 +18,103 @@ public class JedisPoolTest extends Assert {
@Test @Test
public void checkConnections() { public void checkConnections() {
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.host, JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.host,
hnp.port, 2000); hnp.port, 2000);
Jedis jedis = pool.getResource(); Jedis jedis = pool.getResource();
jedis.auth("foobared"); jedis.auth("foobared");
jedis.set("foo", "bar"); jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo")); assertEquals("bar", jedis.get("foo"));
pool.returnResource(jedis); pool.returnResource(jedis);
pool.destroy(); pool.destroy();
} }
@Test @Test
public void checkConnectionWithDefaultPort() { public void checkConnectionWithDefaultPort() {
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.host, JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.host,
hnp.port); hnp.port);
Jedis jedis = pool.getResource(); Jedis jedis = pool.getResource();
jedis.auth("foobared"); jedis.auth("foobared");
jedis.set("foo", "bar"); jedis.set("foo", "bar");
assertEquals("bar", jedis.get("foo")); assertEquals("bar", jedis.get("foo"));
pool.returnResource(jedis); pool.returnResource(jedis);
pool.destroy(); pool.destroy();
} }
@Test @Test
public void checkJedisIsReusedWhenReturned() { public void checkJedisIsReusedWhenReturned() {
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.host, JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.host,
hnp.port); hnp.port);
Jedis jedis = pool.getResource(); Jedis jedis = pool.getResource();
jedis.auth("foobared"); jedis.auth("foobared");
jedis.set("foo", "0"); jedis.set("foo", "0");
pool.returnResource(jedis); pool.returnResource(jedis);
jedis = pool.getResource(); jedis = pool.getResource();
jedis.auth("foobared"); jedis.auth("foobared");
jedis.incr("foo"); jedis.incr("foo");
pool.returnResource(jedis); pool.returnResource(jedis);
pool.destroy(); pool.destroy();
} }
@Test @Test
public void checkPoolRepairedWhenJedisIsBroken() { public void checkPoolRepairedWhenJedisIsBroken() {
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.host, JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.host,
hnp.port); hnp.port);
Jedis jedis = pool.getResource(); Jedis jedis = pool.getResource();
jedis.auth("foobared"); jedis.auth("foobared");
jedis.quit(); jedis.quit();
pool.returnBrokenResource(jedis); pool.returnBrokenResource(jedis);
jedis = pool.getResource(); jedis = pool.getResource();
jedis.auth("foobared"); jedis.auth("foobared");
jedis.incr("foo"); jedis.incr("foo");
pool.returnResource(jedis); pool.returnResource(jedis);
pool.destroy(); pool.destroy();
} }
@Test(expected = JedisConnectionException.class) @Test(expected = JedisConnectionException.class)
public void checkPoolOverflow() { public void checkPoolOverflow() {
Config config = new Config(); GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.maxActive = 1; config.setMaxTotal(1);
config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL; config.setBlockWhenExhausted(false);
JedisPool pool = new JedisPool(config, hnp.host, hnp.port); JedisPool pool = new JedisPool(config, hnp.host, hnp.port);
Jedis jedis = pool.getResource(); Jedis jedis = pool.getResource();
jedis.auth("foobared"); jedis.auth("foobared");
jedis.set("foo", "0"); jedis.set("foo", "0");
Jedis newJedis = pool.getResource(); Jedis newJedis = pool.getResource();
newJedis.auth("foobared"); newJedis.auth("foobared");
newJedis.incr("foo"); newJedis.incr("foo");
} }
@Test @Test
public void securePool() { public void securePool() {
JedisPoolConfig config = new JedisPoolConfig(); JedisPoolConfig config = new JedisPoolConfig();
config.setTestOnBorrow(true); config.setTestOnBorrow(true);
JedisPool pool = new JedisPool(config, hnp.host, hnp.port, 2000, "foobared"); JedisPool pool = new JedisPool(config, hnp.host, hnp.port, 2000,
Jedis jedis = pool.getResource(); "foobared");
jedis.set("foo", "bar"); Jedis jedis = pool.getResource();
pool.returnResource(jedis); jedis.set("foo", "bar");
pool.destroy(); pool.returnResource(jedis);
pool.destroy();
} }
@Test @Test
public void nonDefaultDatabase() { public void nonDefaultDatabase() {
JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.host, JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.host,
hnp.port, 2000, "foobared"); hnp.port, 2000, "foobared");
Jedis jedis0 = pool0.getResource(); Jedis jedis0 = pool0.getResource();
jedis0.set("foo", "bar"); jedis0.set("foo", "bar");
assertEquals( "bar", jedis0.get("foo") ); assertEquals("bar", jedis0.get("foo"));
pool0.returnResource(jedis0); pool0.returnResource(jedis0);
pool0.destroy(); pool0.destroy();
JedisPool pool1 = new JedisPool(new JedisPoolConfig(), hnp.host, JedisPool pool1 = new JedisPool(new JedisPoolConfig(), hnp.host,
hnp.port, 2000, "foobared", 1); hnp.port, 2000, "foobared", 1);
Jedis jedis1 = pool1.getResource(); Jedis jedis1 = pool1.getResource();
assertNull( jedis1.get("foo") ); assertNull(jedis1.get("foo"));
pool1.returnResource(jedis0); pool1.returnResource(jedis1);
pool1.destroy(); pool1.destroy();
}
@Test
public void returnBinary() {
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.host,
hnp.port, 2000);
BinaryJedis jedis = pool.getResource();
pool.returnResource(jedis);
pool.destroy();
} }
@Test @Test
@@ -145,43 +135,44 @@ public class JedisPoolTest extends Assert {
j.auth("foobared"); j.auth("foobared");
j.select(2); j.select(2);
j.set("foo", "bar"); j.set("foo", "bar");
JedisPool pool = new JedisPool(new URI("redis://:foobared@localhost:6380/2")); JedisPool pool = new JedisPool(new URI(
"redis://:foobared@localhost:6380/2"));
Jedis jedis = pool.getResource(); Jedis jedis = pool.getResource();
assertEquals("PONG", jedis.ping()); assertEquals("PONG", jedis.ping());
assertEquals("bar", jedis.get("foo")); assertEquals("bar", jedis.get("foo"));
} }
@Test @Test
public void selectDatabaseOnActivation() { public void selectDatabaseOnActivation() {
JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.host, hnp.port, 2000, "foobared"); JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.host,
hnp.port, 2000, "foobared");
Jedis jedis0 = pool.getResource(); Jedis jedis0 = pool.getResource();
assertEquals(0L, jedis0.getDB().longValue()); assertEquals(0L, jedis0.getDB().longValue());
jedis0.select(1); jedis0.select(1);
assertEquals(1L, jedis0.getDB().longValue()); assertEquals(1L, jedis0.getDB().longValue());
pool.returnResource(jedis0); pool.returnResource(jedis0);
Jedis jedis1 = pool.getResource(); Jedis jedis1 = pool.getResource();
assertTrue("Jedis instance was not reused", jedis1 == jedis0); assertTrue("Jedis instance was not reused", jedis1 == jedis0);
assertEquals(0L, jedis1.getDB().longValue()); assertEquals(0L, jedis1.getDB().longValue());
pool.returnResource(jedis1); pool.returnResource(jedis1);
pool.destroy(); pool.destroy();
} }
@Test @Test
public void customClientName() { public void customClientName() {
JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.host, JedisPool pool0 = new JedisPool(new JedisPoolConfig(), hnp.host,
hnp.port, 2000, "foobared", 0, "my_shiny_client_name"); hnp.port, 2000, "foobared", 0, "my_shiny_client_name");
Jedis jedis = pool0.getResource(); Jedis jedis = pool0.getResource();
assertEquals("my_shiny_client_name", jedis.clientGetname()); assertEquals("my_shiny_client_name", jedis.clientGetname());
pool0.returnResource(jedis); pool0.returnResource(jedis);
pool0.destroy(); pool0.destroy();
} }
} }

View File

@@ -3,7 +3,7 @@ package redis.clients.jedis.tests;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import org.apache.commons.pool.impl.GenericObjectPool.Config; import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@@ -19,7 +19,7 @@ public class JedisSentinelPoolTest extends JedisTestBase {
protected static HostAndPort slave1 = HostAndPortUtil.getRedisServers() protected static HostAndPort slave1 = HostAndPortUtil.getRedisServers()
.get(3); .get(3);
protected static HostAndPort slave2 = HostAndPortUtil.getRedisServers() protected static HostAndPort slave2 = HostAndPortUtil.getRedisServers()
.get(4); .get(4);
protected static HostAndPort sentinel1 = HostAndPortUtil protected static HostAndPort sentinel1 = HostAndPortUtil
.getSentinelServers().get(1); .getSentinelServers().get(1);
protected static HostAndPort sentinel2 = HostAndPortUtil protected static HostAndPort sentinel2 = HostAndPortUtil
@@ -62,37 +62,38 @@ public class JedisSentinelPoolTest extends JedisTestBase {
@Test @Test
public void ensureSafeTwiceFailover() throws InterruptedException { public void ensureSafeTwiceFailover() throws InterruptedException {
JedisSentinelPool pool = new JedisSentinelPool("mymaster", sentinels, JedisSentinelPool pool = new JedisSentinelPool("mymaster", sentinels,
new Config(), 1000, "foobared", 2); new GenericObjectPoolConfig(), 1000, "foobared", 2);
// perform failover // perform failover
doSegFaultMaster(pool); doSegFaultMaster(pool);
// perform failover once again // perform failover once again
doSegFaultMaster(pool); doSegFaultMaster(pool);
// you can test failover as much as possible // you can test failover as much as possible
// but you need to prepare additional slave per failover // but you need to prepare additional slave per failover
} }
private void doSegFaultMaster(JedisSentinelPool pool) throws InterruptedException { private void doSegFaultMaster(JedisSentinelPool pool)
// jedis connection should be master throws InterruptedException {
Jedis jedis = pool.getResource(); // jedis connection should be master
assertEquals("PONG", jedis.ping()); Jedis jedis = pool.getResource();
assertEquals("PONG", jedis.ping());
try { try {
jedis.debug(DebugParams.SEGFAULT()); jedis.debug(DebugParams.SEGFAULT());
} catch (Exception e) { } catch (Exception e) {
} }
// wait for the sentinel to promote a master // wait for the sentinel to promote a master
// FIXME: we can query the sentinel and sleep // FIXME: we can query the sentinel and sleep
// right until the master is promoted // right until the master is promoted
Thread.sleep(35000); Thread.sleep(35000);
jedis = pool.getResource(); jedis = pool.getResource();
assertEquals("PONG", jedis.ping()); assertEquals("PONG", jedis.ping());
assertEquals("foobared", jedis.configGet("requirepass").get(1)); assertEquals("foobared", jedis.configGet("requirepass").get(1));
assertEquals(2, jedis.getDB().intValue()); assertEquals(2, jedis.getDB().intValue());
} }
} }

View File

@@ -1,8 +1,8 @@
package redis.clients.jedis.tests; package redis.clients.jedis.tests;
import static junit.framework.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static junit.framework.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static junit.framework.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;

View File

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

View File

@@ -5,8 +5,7 @@ import java.net.URISyntaxException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.apache.commons.pool.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.apache.commons.pool.impl.GenericObjectPool.Config;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@@ -20,154 +19,158 @@ import redis.clients.jedis.tests.HostAndPortUtil.HostAndPort;
public class ShardedJedisPoolTest extends Assert { public class ShardedJedisPoolTest extends Assert {
private static HostAndPort redis1 = HostAndPortUtil.getRedisServers() private static HostAndPort redis1 = HostAndPortUtil.getRedisServers()
.get(0); .get(0);
private static HostAndPort redis2 = HostAndPortUtil.getRedisServers() private static HostAndPort redis2 = HostAndPortUtil.getRedisServers()
.get(1); .get(1);
private List<JedisShardInfo> shards; private List<JedisShardInfo> shards;
@Before @Before
public void startUp() { public void startUp() {
shards = new ArrayList<JedisShardInfo>(); shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(redis1.host, redis1.port)); shards.add(new JedisShardInfo(redis1.host, redis1.port));
shards.add(new JedisShardInfo(redis2.host, redis2.port)); shards.add(new JedisShardInfo(redis2.host, redis2.port));
shards.get(0).setPassword("foobared"); shards.get(0).setPassword("foobared");
shards.get(1).setPassword("foobared"); shards.get(1).setPassword("foobared");
Jedis j = new Jedis(shards.get(0)); Jedis j = new Jedis(shards.get(0));
j.connect(); j.connect();
j.flushAll(); j.flushAll();
j.disconnect(); j.disconnect();
j = new Jedis(shards.get(1)); j = new Jedis(shards.get(1));
j.connect(); j.connect();
j.flushAll(); j.flushAll();
j.disconnect(); j.disconnect();
} }
@Test @Test
public void checkConnections() { public void checkConnections() {
ShardedJedisPool pool = new ShardedJedisPool(new Config(), shards); ShardedJedisPool pool = new ShardedJedisPool(
ShardedJedis jedis = pool.getResource(); new GenericObjectPoolConfig(), shards);
jedis.set("foo", "bar"); ShardedJedis jedis = pool.getResource();
assertEquals("bar", jedis.get("foo")); jedis.set("foo", "bar");
pool.returnResource(jedis); assertEquals("bar", jedis.get("foo"));
pool.destroy(); pool.returnResource(jedis);
pool.destroy();
} }
@Test @Test
public void checkConnectionWithDefaultPort() { public void checkConnectionWithDefaultPort() {
ShardedJedisPool pool = new ShardedJedisPool(new Config(), shards); ShardedJedisPool pool = new ShardedJedisPool(
ShardedJedis jedis = pool.getResource(); new GenericObjectPoolConfig(), shards);
jedis.set("foo", "bar"); ShardedJedis jedis = pool.getResource();
assertEquals("bar", jedis.get("foo")); jedis.set("foo", "bar");
pool.returnResource(jedis); assertEquals("bar", jedis.get("foo"));
pool.destroy(); pool.returnResource(jedis);
pool.destroy();
} }
@Test @Test
public void checkJedisIsReusedWhenReturned() { public void checkJedisIsReusedWhenReturned() {
ShardedJedisPool pool = new ShardedJedisPool(new Config(), shards); ShardedJedisPool pool = new ShardedJedisPool(
ShardedJedis jedis = pool.getResource(); new GenericObjectPoolConfig(), shards);
jedis.set("foo", "0"); ShardedJedis jedis = pool.getResource();
pool.returnResource(jedis); jedis.set("foo", "0");
pool.returnResource(jedis);
jedis = pool.getResource(); jedis = pool.getResource();
jedis.incr("foo"); jedis.incr("foo");
pool.returnResource(jedis); pool.returnResource(jedis);
pool.destroy(); pool.destroy();
} }
@Test @Test
public void checkPoolRepairedWhenJedisIsBroken() { public void checkPoolRepairedWhenJedisIsBroken() {
ShardedJedisPool pool = new ShardedJedisPool(new Config(), shards); ShardedJedisPool pool = new ShardedJedisPool(
ShardedJedis jedis = pool.getResource(); new GenericObjectPoolConfig(), shards);
jedis.disconnect(); ShardedJedis jedis = pool.getResource();
pool.returnBrokenResource(jedis); jedis.disconnect();
pool.returnBrokenResource(jedis);
jedis = pool.getResource(); jedis = pool.getResource();
jedis.incr("foo"); jedis.incr("foo");
pool.returnResource(jedis); pool.returnResource(jedis);
pool.destroy(); pool.destroy();
} }
@Test(expected = JedisConnectionException.class) @Test(expected = JedisConnectionException.class)
public void checkPoolOverflow() { public void checkPoolOverflow() {
Config config = new Config(); GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.maxActive = 1; config.setMaxTotal(1);
config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL; config.setBlockWhenExhausted(false);
ShardedJedisPool pool = new ShardedJedisPool(config, shards); ShardedJedisPool pool = new ShardedJedisPool(config, shards);
ShardedJedis jedis = pool.getResource(); ShardedJedis jedis = pool.getResource();
jedis.set("foo", "0"); jedis.set("foo", "0");
ShardedJedis newJedis = pool.getResource(); ShardedJedis newJedis = pool.getResource();
newJedis.incr("foo"); newJedis.incr("foo");
} }
@Test @Test
public void shouldNotShareInstances() { public void shouldNotShareInstances() {
Config config = new Config(); GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.maxActive = 2; config.setMaxTotal(2);
config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL;
ShardedJedisPool pool = new ShardedJedisPool(config, shards); ShardedJedisPool pool = new ShardedJedisPool(config, shards);
ShardedJedis j1 = pool.getResource(); ShardedJedis j1 = pool.getResource();
ShardedJedis j2 = pool.getResource(); ShardedJedis j2 = pool.getResource();
assertNotSame(j1.getShard("foo"), j2.getShard("foo")); assertNotSame(j1.getShard("foo"), j2.getShard("foo"));
} }
@Test @Test
public void checkFailedJedisServer() { public void checkFailedJedisServer() {
ShardedJedisPool pool = new ShardedJedisPool(new Config(), shards); ShardedJedisPool pool = new ShardedJedisPool(
ShardedJedis jedis = pool.getResource(); new GenericObjectPoolConfig(), shards);
jedis.incr("foo"); ShardedJedis jedis = pool.getResource();
pool.returnResource(jedis); jedis.incr("foo");
pool.destroy(); pool.returnResource(jedis);
pool.destroy();
} }
@Test @Test
public void shouldReturnActiveShardsWhenOneGoesOffline() { public void shouldReturnActiveShardsWhenOneGoesOffline() {
Config redisConfig = new Config(); GenericObjectPoolConfig redisConfig = new GenericObjectPoolConfig();
redisConfig.testOnBorrow = false; redisConfig.setTestOnBorrow(false);
ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards); ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards);
ShardedJedis jedis = pool.getResource(); ShardedJedis jedis = pool.getResource();
// fill the shards // fill the shards
for (int i = 0; i < 1000; i++) { for (int i = 0; i < 1000; i++) {
jedis.set("a-test-" + i, "0"); jedis.set("a-test-" + i, "0");
} }
pool.returnResource(jedis); pool.returnResource(jedis);
// check quantity for each shard // check quantity for each shard
Jedis j = new Jedis(shards.get(0)); Jedis j = new Jedis(shards.get(0));
j.connect(); j.connect();
Long c1 = j.dbSize(); Long c1 = j.dbSize();
j.disconnect(); j.disconnect();
j = new Jedis(shards.get(1)); j = new Jedis(shards.get(1));
j.connect(); j.connect();
Long c2 = j.dbSize(); Long c2 = j.dbSize();
j.disconnect(); j.disconnect();
// shutdown shard 2 and check thay the pool returns an instance with c1 // shutdown shard 2 and check thay the pool returns an instance with c1
// items on one shard // items on one shard
// alter shard 1 and recreate pool // alter shard 1 and recreate pool
pool.destroy(); pool.destroy();
shards.set(1, new JedisShardInfo("nohost", 1234)); shards.set(1, new JedisShardInfo("nohost", 1234));
pool = new ShardedJedisPool(redisConfig, shards); pool = new ShardedJedisPool(redisConfig, shards);
jedis = pool.getResource(); jedis = pool.getResource();
Long actual = Long.valueOf(0); Long actual = Long.valueOf(0);
Long fails = Long.valueOf(0); Long fails = Long.valueOf(0);
for (int i = 0; i < 1000; i++) { for (int i = 0; i < 1000; i++) {
try { try {
jedis.get("a-test-" + i); jedis.get("a-test-" + i);
actual++; actual++;
} catch (RuntimeException e) { } catch (RuntimeException e) {
fails++; fails++;
} }
} }
pool.returnResource(jedis); pool.returnResource(jedis);
pool.destroy(); pool.destroy();
assertEquals(actual, c1); assertEquals(actual, c1);
assertEquals(fails, c2); assertEquals(fails, c2);
} }
@Test @Test
@@ -184,10 +187,11 @@ public class ShardedJedisPoolTest extends Assert {
shards.add(new JedisShardInfo("redis://:foobared@localhost:6380")); shards.add(new JedisShardInfo("redis://:foobared@localhost:6380"));
shards.add(new JedisShardInfo("redis://:foobared@localhost:6379")); shards.add(new JedisShardInfo("redis://:foobared@localhost:6379"));
Config redisConfig = new Config(); GenericObjectPoolConfig redisConfig = new GenericObjectPoolConfig();
ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards); 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]; Jedis jedis = jedises[0];
assertEquals("PONG", jedis.ping()); assertEquals("PONG", jedis.ping());
@@ -209,13 +213,16 @@ public class ShardedJedisPoolTest extends Assert {
j.set("foo", "bar"); j.set("foo", "bar");
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(); List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(new URI("redis://:foobared@localhost:6380"))); shards.add(new JedisShardInfo(new URI(
shards.add(new JedisShardInfo(new URI("redis://:foobared@localhost:6379"))); "redis://:foobared@localhost:6380")));
shards.add(new JedisShardInfo(new URI(
"redis://:foobared@localhost:6379")));
Config redisConfig = new Config(); GenericObjectPoolConfig redisConfig = new GenericObjectPoolConfig();
ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards); 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]; Jedis jedis = jedises[0];
assertEquals("PONG", jedis.ping()); assertEquals("PONG", jedis.ping());

View File

@@ -4,7 +4,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.pool.impl.GenericObjectPool.Config; import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis; import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPool;
@@ -16,48 +16,48 @@ public class PoolBenchmark {
private static final int TOTAL_OPERATIONS = 100000; private static final int TOTAL_OPERATIONS = 100000;
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
Jedis j = new Jedis(hnp.host, hnp.port); Jedis j = new Jedis(hnp.host, hnp.port);
j.connect(); j.connect();
j.auth("foobared"); j.auth("foobared");
j.flushAll(); j.flushAll();
j.quit(); j.quit();
j.disconnect(); j.disconnect();
long t = System.currentTimeMillis(); long t = System.currentTimeMillis();
// withoutPool(); // withoutPool();
withPool(); withPool();
long elapsed = System.currentTimeMillis() - t; long elapsed = System.currentTimeMillis() - t;
System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops"); System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops");
} }
private static void withPool() throws Exception { private static void withPool() throws Exception {
final JedisPool pool = new JedisPool(new Config(), hnp.host, hnp.port, final JedisPool pool = new JedisPool(new GenericObjectPoolConfig(),
2000, "foobared"); hnp.host, hnp.port, 2000, "foobared");
List<Thread> tds = new ArrayList<Thread>(); List<Thread> tds = new ArrayList<Thread>();
final AtomicInteger ind = new AtomicInteger(); final AtomicInteger ind = new AtomicInteger();
for (int i = 0; i < 50; i++) { for (int i = 0; i < 50; i++) {
Thread hj = new Thread(new Runnable() { Thread hj = new Thread(new Runnable() {
public void run() { public void run() {
for (int i = 0; (i = ind.getAndIncrement()) < TOTAL_OPERATIONS;) { for (int i = 0; (i = ind.getAndIncrement()) < TOTAL_OPERATIONS;) {
try { try {
Jedis j = pool.getResource(); Jedis j = pool.getResource();
final String key = "foo" + i; final String key = "foo" + i;
j.set(key, key); j.set(key, key);
j.get(key); j.get(key);
pool.returnResource(j); pool.returnResource(j);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
}); });
tds.add(hj); tds.add(hj);
hj.start(); hj.start();
} }
for (Thread t : tds) for (Thread t : tds)
t.join(); t.join();
pool.destroy(); pool.destroy();
} }
} }

View File

@@ -299,11 +299,8 @@ public class AllKindOfValuesCommandsTest extends JedisCommandTestBase {
@Test @Test
public void ttl() { public void ttl() {
// This is supposed to return -2 according to
// http://redis.io/commands/ttl
// and needs to be fixed in Redis.
long ttl = jedis.ttl("foo"); long ttl = jedis.ttl("foo");
assertEquals(-1, ttl); assertEquals(-2, ttl);
jedis.set("foo", "bar"); jedis.set("foo", "bar");
ttl = jedis.ttl("foo"); ttl = jedis.ttl("foo");
@@ -313,13 +310,9 @@ public class AllKindOfValuesCommandsTest extends JedisCommandTestBase {
ttl = jedis.ttl("foo"); ttl = jedis.ttl("foo");
assertTrue(ttl >= 0 && ttl <= 20); assertTrue(ttl >= 0 && ttl <= 20);
// This is supposed to return -2 according to
// http://redis.io/commands/ttl
// and needs to be fixed in Redis.
// Binary // Binary
long bttl = jedis.ttl(bfoo); long bttl = jedis.ttl(bfoo);
assertEquals(-1, bttl); assertEquals(-2, bttl);
jedis.set(bfoo, bbar); jedis.set(bfoo, bbar);
bttl = jedis.ttl(bfoo); bttl = jedis.ttl(bfoo);
@@ -499,7 +492,7 @@ public class AllKindOfValuesCommandsTest extends JedisCommandTestBase {
@Test @Test
public void pttl() { public void pttl() {
long pttl = jedis.pttl("foo"); long pttl = jedis.pttl("foo");
assertEquals(-1, pttl); assertEquals(-2, pttl);
jedis.set("foo", "bar"); jedis.set("foo", "bar");
pttl = jedis.pttl("foo"); pttl = jedis.pttl("foo");

View File

@@ -11,11 +11,10 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import redis.clients.jedis.Jedis; import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline; import redis.clients.jedis.Protocol.Keyword;
import redis.clients.jedis.Response; import redis.clients.jedis.Response;
import redis.clients.jedis.Transaction; import redis.clients.jedis.Transaction;
import redis.clients.jedis.TransactionBlock; import redis.clients.jedis.TransactionBlock;
import redis.clients.jedis.Protocol.Keyword;
import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.exceptions.JedisDataException;
public class TransactionCommandsTest extends JedisCommandTestBase { public class TransactionCommandsTest extends JedisCommandTestBase {
@@ -30,269 +29,269 @@ public class TransactionCommandsTest extends JedisCommandTestBase {
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
super.setUp(); super.setUp();
nj = new Jedis(hnp.host, hnp.port, 500); nj = new Jedis(hnp.host, hnp.port, 500);
nj.connect(); nj.connect();
nj.auth("foobared"); nj.auth("foobared");
nj.flushAll(); nj.flushAll();
} }
@Test @Test
public void multi() { public void multi() {
Transaction trans = jedis.multi(); Transaction trans = jedis.multi();
trans.sadd("foo", "a"); trans.sadd("foo", "a");
trans.sadd("foo", "b"); trans.sadd("foo", "b");
trans.scard("foo"); trans.scard("foo");
List<Object> response = trans.exec(); List<Object> response = trans.exec();
List<Object> expected = new ArrayList<Object>(); List<Object> expected = new ArrayList<Object>();
expected.add(1L); expected.add(1L);
expected.add(1L); expected.add(1L);
expected.add(2L); expected.add(2L);
assertEquals(expected, response); assertEquals(expected, response);
// Binary // Binary
trans = jedis.multi(); trans = jedis.multi();
trans.sadd(bfoo, ba); trans.sadd(bfoo, ba);
trans.sadd(bfoo, bb); trans.sadd(bfoo, bb);
trans.scard(bfoo); trans.scard(bfoo);
response = trans.exec(); response = trans.exec();
expected = new ArrayList<Object>(); expected = new ArrayList<Object>();
expected.add(1L); expected.add(1L);
expected.add(1L); expected.add(1L);
expected.add(2L); expected.add(2L);
assertEquals(expected, response); assertEquals(expected, response);
} }
@Test @Test
public void multiBlock() { public void multiBlock() {
List<Object> response = jedis.multi(new TransactionBlock() { List<Object> response = jedis.multi(new TransactionBlock() {
@Override @Override
public void execute() { public void execute() {
sadd("foo", "a"); sadd("foo", "a");
sadd("foo", "b"); sadd("foo", "b");
scard("foo"); scard("foo");
} }
}); });
List<Object> expected = new ArrayList<Object>(); List<Object> expected = new ArrayList<Object>();
expected.add(1L); expected.add(1L);
expected.add(1L); expected.add(1L);
expected.add(2L); expected.add(2L);
assertEquals(expected, response); assertEquals(expected, response);
// Binary // Binary
response = jedis.multi(new TransactionBlock() { response = jedis.multi(new TransactionBlock() {
@Override @Override
public void execute() { public void execute() {
sadd(bfoo, ba); sadd(bfoo, ba);
sadd(bfoo, bb); sadd(bfoo, bb);
scard(bfoo); scard(bfoo);
} }
}); });
expected = new ArrayList<Object>(); expected = new ArrayList<Object>();
expected.add(1L); expected.add(1L);
expected.add(1L); expected.add(1L);
expected.add(2L); expected.add(2L);
assertEquals(expected, response); assertEquals(expected, response);
} }
@Test @Test
public void watch() throws UnknownHostException, IOException { public void watch() throws UnknownHostException, IOException {
jedis.watch("mykey", "somekey"); jedis.watch("mykey", "somekey");
Transaction t = jedis.multi(); Transaction t = jedis.multi();
nj.connect(); nj.connect();
nj.auth("foobared"); nj.auth("foobared");
nj.set("mykey", "bar"); nj.set("mykey", "bar");
nj.disconnect(); nj.disconnect();
t.set("mykey", "foo"); t.set("mykey", "foo");
List<Object> resp = t.exec(); List<Object> resp = t.exec();
assertEquals(null, resp); assertEquals(null, resp);
assertEquals("bar", jedis.get("mykey")); assertEquals("bar", jedis.get("mykey"));
// Binary // Binary
jedis.watch(bmykey, "foobar".getBytes()); jedis.watch(bmykey, "foobar".getBytes());
t = jedis.multi(); t = jedis.multi();
nj.connect(); nj.connect();
nj.auth("foobared"); nj.auth("foobared");
nj.set(bmykey, bbar); nj.set(bmykey, bbar);
nj.disconnect(); nj.disconnect();
t.set(bmykey, bfoo); t.set(bmykey, bfoo);
resp = t.exec(); resp = t.exec();
assertEquals(null, resp); assertEquals(null, resp);
assertTrue(Arrays.equals(bbar, jedis.get(bmykey))); assertTrue(Arrays.equals(bbar, jedis.get(bmykey)));
} }
@Test @Test
public void unwatch() throws UnknownHostException, IOException { public void unwatch() throws UnknownHostException, IOException {
jedis.watch("mykey"); jedis.watch("mykey");
String val = jedis.get("mykey"); String val = jedis.get("mykey");
val = "foo"; val = "foo";
String status = jedis.unwatch(); String status = jedis.unwatch();
assertEquals("OK", status); assertEquals("OK", status);
Transaction t = jedis.multi(); Transaction t = jedis.multi();
nj.connect(); nj.connect();
nj.auth("foobared"); nj.auth("foobared");
nj.set("mykey", "bar"); nj.set("mykey", "bar");
nj.disconnect(); nj.disconnect();
t.set("mykey", val); t.set("mykey", val);
List<Object> resp = t.exec(); List<Object> resp = t.exec();
assertEquals(1, resp.size()); assertEquals(1, resp.size());
assertEquals("OK", resp.get(0)); assertEquals("OK", resp.get(0));
// Binary // Binary
jedis.watch(bmykey); jedis.watch(bmykey);
byte[] bval = jedis.get(bmykey); byte[] bval = jedis.get(bmykey);
bval = bfoo; bval = bfoo;
status = jedis.unwatch(); status = jedis.unwatch();
assertEquals(Keyword.OK.name(), status); assertEquals(Keyword.OK.name(), status);
t = jedis.multi(); t = jedis.multi();
nj.connect(); nj.connect();
nj.auth("foobared"); nj.auth("foobared");
nj.set(bmykey, bbar); nj.set(bmykey, bbar);
nj.disconnect(); nj.disconnect();
t.set(bmykey, bval); t.set(bmykey, bval);
resp = t.exec(); resp = t.exec();
assertEquals(1, resp.size()); assertEquals(1, resp.size());
assertEquals("OK", resp.get(0)); assertEquals("OK", resp.get(0));
} }
@Test(expected = JedisDataException.class) @Test(expected = JedisDataException.class)
public void validateWhenInMulti() { public void validateWhenInMulti() {
jedis.multi(); jedis.multi();
jedis.ping(); jedis.ping();
} }
@Test @Test
public void discard() { public void discard() {
Transaction t = jedis.multi(); Transaction t = jedis.multi();
String status = t.discard(); String status = t.discard();
assertEquals("OK", status); assertEquals("OK", status);
} }
@Test @Test
public void transactionResponse() { public void transactionResponse() {
jedis.set("string", "foo"); jedis.set("string", "foo");
jedis.lpush("list", "foo"); jedis.lpush("list", "foo");
jedis.hset("hash", "foo", "bar"); jedis.hset("hash", "foo", "bar");
jedis.zadd("zset", 1, "foo"); jedis.zadd("zset", 1, "foo");
jedis.sadd("set", "foo"); jedis.sadd("set", "foo");
Transaction t = jedis.multi(); Transaction t = jedis.multi();
Response<String> string = t.get("string"); Response<String> string = t.get("string");
Response<String> list = t.lpop("list"); Response<String> list = t.lpop("list");
Response<String> hash = t.hget("hash", "foo"); Response<String> hash = t.hget("hash", "foo");
Response<Set<String>> zset = t.zrange("zset", 0, -1); Response<Set<String>> zset = t.zrange("zset", 0, -1);
Response<String> set = t.spop("set"); Response<String> set = t.spop("set");
t.exec(); t.exec();
assertEquals("foo", string.get()); assertEquals("foo", string.get());
assertEquals("foo", list.get()); assertEquals("foo", list.get());
assertEquals("bar", hash.get()); assertEquals("bar", hash.get());
assertEquals("foo", zset.get().iterator().next()); assertEquals("foo", zset.get().iterator().next());
assertEquals("foo", set.get()); assertEquals("foo", set.get());
} }
@Test @Test
public void transactionResponseBinary() { public void transactionResponseBinary() {
jedis.set("string", "foo"); jedis.set("string", "foo");
jedis.lpush("list", "foo"); jedis.lpush("list", "foo");
jedis.hset("hash", "foo", "bar"); jedis.hset("hash", "foo", "bar");
jedis.zadd("zset", 1, "foo"); jedis.zadd("zset", 1, "foo");
jedis.sadd("set", "foo"); jedis.sadd("set", "foo");
Transaction t = jedis.multi(); Transaction t = jedis.multi();
Response<byte[]> string = t.get("string".getBytes()); Response<byte[]> string = t.get("string".getBytes());
Response<byte[]> list = t.lpop("list".getBytes()); Response<byte[]> list = t.lpop("list".getBytes());
Response<byte[]> hash = t.hget("hash".getBytes(), "foo".getBytes()); Response<byte[]> hash = t.hget("hash".getBytes(), "foo".getBytes());
Response<Set<byte[]>> zset = t.zrange("zset".getBytes(), 0, -1); Response<Set<byte[]>> zset = t.zrange("zset".getBytes(), 0, -1);
Response<byte[]> set = t.spop("set".getBytes()); Response<byte[]> set = t.spop("set".getBytes());
t.exec(); t.exec();
assertArrayEquals("foo".getBytes(), string.get()); assertArrayEquals("foo".getBytes(), string.get());
assertArrayEquals("foo".getBytes(), list.get()); assertArrayEquals("foo".getBytes(), list.get());
assertArrayEquals("bar".getBytes(), hash.get()); assertArrayEquals("bar".getBytes(), hash.get());
assertArrayEquals("foo".getBytes(), zset.get().iterator().next()); assertArrayEquals("foo".getBytes(), zset.get().iterator().next());
assertArrayEquals("foo".getBytes(), set.get()); assertArrayEquals("foo".getBytes(), set.get());
} }
@Test(expected = JedisDataException.class) @Test(expected = JedisDataException.class)
public void transactionResponseWithinPipeline() { public void transactionResponseWithinPipeline() {
jedis.set("string", "foo"); jedis.set("string", "foo");
Transaction t = jedis.multi(); Transaction t = jedis.multi();
Response<String> string = t.get("string"); Response<String> string = t.get("string");
string.get(); string.get();
t.exec(); t.exec();
} }
@Test @Test
public void transactionResponseWithError() { public void transactionResponseWithError() {
Transaction t = jedis.multi(); Transaction t = jedis.multi();
t.set("foo", "bar"); t.set("foo", "bar");
Response<Set<String>> error = t.smembers("foo"); Response<Set<String>> error = t.smembers("foo");
Response<String> r = t.get("foo"); Response<String> r = t.get("foo");
List<Object> l = t.exec(); List<Object> l = t.exec();
assertEquals(JedisDataException.class, l.get(1).getClass()); assertEquals(JedisDataException.class, l.get(1).getClass());
try{ try {
error.get(); error.get();
fail("We expect exception here!"); fail("We expect exception here!");
}catch(JedisDataException e){ } catch (JedisDataException e) {
//that is fine we should be here // that is fine we should be here
} }
assertEquals(r.get(), "bar"); assertEquals(r.get(), "bar");
} }
@Test @Test
public void execGetResponse() { public void execGetResponse() {
Transaction t = jedis.multi(); Transaction t = jedis.multi();
t.set("foo", "bar"); t.set("foo", "bar");
t.smembers("foo"); t.smembers("foo");
t.get("foo"); t.get("foo");
List<Response<?>> lr = t.execGetResponse(); List<Response<?>> lr = t.execGetResponse();
try{ try {
lr.get(1).get(); lr.get(1).get();
fail("We expect exception here!"); fail("We expect exception here!");
}catch(JedisDataException e){ } catch (JedisDataException e) {
//that is fine we should be here // that is fine we should be here
} }
assertEquals("bar", lr.get(2).get()); assertEquals("bar", lr.get(2).get());
} }
@Test @Test
public void select() { public void select() {
jedis.select(1); jedis.select(1);
jedis.set("foo", "bar"); jedis.set("foo", "bar");
jedis.watch("foo"); jedis.watch("foo");
Transaction t = jedis.multi(); Transaction t = jedis.multi();
t.select(0); t.select(0);
t.set("bar", "foo"); t.set("bar", "foo");
Jedis jedis2 = createJedis(); Jedis jedis2 = createJedis();
jedis2.select(1); jedis2.select(1);
jedis2.set("foo", "bar2"); jedis2.set("foo", "bar2");
List<Object> results = t.exec(); List<Object> results = t.exec();
assertNull(results); assertNull(results);
} }
} }