1.RedisPoolUtil.java
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/*
* Redis連接配接池工具類
*/
public class RedisPoolUtil {
private static volatile JedisPool jedisPool=null;
//構造方法私有化
private RedisPoolUtil(){
}
public static JedisPool getJedisPoolInstance(){
if(null==jedisPool){
synchronized (RedisPoolUtil.class) {
if(null==jedisPool){
JedisPoolConfig jedisPoolConfig=new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(1000);
jedisPoolConfig.setMaxIdle(36);
jedisPoolConfig.setMaxWaitMillis(100*1000);
jedisPool=new JedisPool(jedisPoolConfig,"127.0.0.1",6379);
}
}
}
return jedisPool;
}
public static void release(JedisPool jedisPool,Jedis jedis){
if(null!=jedis){
jedisPool.returnResourceObject(jedis);
}
}
}
2.RedisPoolTest
import javax.servlet.jsp.tagext.TryCatchFinally;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class RedisPoolTest {
public static void main(String[] args) {
//獲得jedis連接配接池
JedisPool jedisPool=RedisPoolUtil.getJedisPoolInstance();
Jedis jedis=null;
try {
jedis=jedisPool.getResource();
jedis.set("k1", "v1");
System.out.println("k1:"+jedis.get("k1"));
jedis.set("k2", "v2");
System.out.println("k2:"+jedis.get("k2"));
} catch (Exception e) {
e.printStackTrace();
}finally{
RedisPoolUtil.release(jedisPool, jedis);
}
}
}