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);
}
}
}