Skip to content

Instantly share code, notes, and snippets.

@mox601
Created February 9, 2015 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mox601/b879526768f8f22174c9 to your computer and use it in GitHub Desktop.
Save mox601/b879526768f8f22174c9 to your computer and use it in GitHub Desktop.
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPubSub;
import redis.clients.jedis.exceptions.JedisConnectionException;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
public class JedisPoolTestCase {
private static final Logger LOGGER = LoggerFactory.getLogger(JedisPoolTestCase.class);
@Test
public void testName() throws Exception {
final GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setMaxIdle(1);
poolConfig.setMaxTotal(1);
poolConfig.setMinIdle(1);
poolConfig.setBlockWhenExhausted(false);
poolConfig.setTestOnBorrow(true);
poolConfig.setTestWhileIdle(true);
final JedisPool jedisPool = new JedisPool(poolConfig, "localhost", 6380);
LOGGER.info("pool before getResource " + jedisPool.getNumActive());
final Jedis jedis = jedisPool.getResource();
LOGGER.info("got resource");
LOGGER.info("pool after getResource " + jedisPool.getNumActive());
final LocalPubSub jedisPubSub = new LocalPubSub();
new Thread(new Runnable() {
@Override
public void run() {
LOGGER.info("subscribing");
jedis.subscribe(jedisPubSub, "a-channel");
LOGGER.info("subscribe finished, always after unsubscribing");
}
}).start();
LOGGER.info("first thread started");
Thread.sleep(100L);
new Thread(new Runnable() {
@Override
public void run() {
LOGGER.info("unsubscribing");
jedisPubSub.unsubscribe();
LOGGER.info("unsubscribed");
//from here
LOGGER.info("closing and releasing jedis");
jedis.close();
LOGGER.info("released jedis");
//to here
}
}).start();
LOGGER.info("second thread started");
Thread.sleep(5000L);
LOGGER.info("pool at end " + jedisPool.getNumActive());
Jedis resource = null;
try {
resource = jedisPool.getResource();
} catch (JedisConnectionException e) {
assertNull(e);
}
assertNotNull(resource);
}
private static class LocalPubSub extends JedisPubSub {
@Override
public void onSubscribe(String channel, int subscribedChannels) {
LOGGER.info(
"channel: '" + channel + "' subscribed channels '" + subscribedChannels + "'");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment