JedisPool
maven依赖
redis.clients
jedis
2.9.0
基本案例,用来测试环境是否正常
public class DemoTest {
private static String host = "127.0.0.1";
private static int port = 6379;
private static String password = "1234";
private static int db = 0;
private static int timeout = 30000;
public static void main(String[] args) {
JedisPoolConfig cfg = new JedisPoolConfig();
cfg.setMaxTotal(20);//连接池中最多连接数
cfg.setMaxIdle(5);//连接池中连接最大空闲数
//创建连接池对象
JedisPool pool = new JedisPool(cfg, host, port, timeout, password, db);
Jedis jedis = pool.getResource(); //获取Jedis对象
jedis.set("k1", "hello world");
String val = jedis.get("k1");
System.out.println(val);
//jedis.del("jedis");
jedis.close();
pool.close();
System.out.println("finish");
}
}
JedisPool连接池
数据库连接池工具类:懒汉单例设计模式保证JedisPool对象是唯一的
public class JedisPoolUtil { //单例设计模式
private static String host = "127.0.0.1";
private static int port = 6379;
private static String password = "1234";
private static Integer db = 0;
private static int timeout = 30000;
private static int maxWaitMillis = 20000;
private volatile static JedisPool pool = null;//懒汉式单例
private JedisPoolUtil() {
}
public static JedisPool getJedisPool() {
if (pool == null) {
synchronized (JedisPoolUtil.class) {
JedisPoolConfig cfg = new JedisPoolConfig();
cfg.setMaxTotal(20);//连接池中最多连接数
cfg.setMaxIdle(5);//连接池中连接最大空闲数
cfg.setMaxWaitMillis(maxWaitMillis);
//创建连接池对象
if (pool == null) {
pool = new JedisPool(cfg, host, port, timeout);
}
}
}
return pool;
}
public static Jedis getJedis(){
Jedis jedis = getJedisPool().getResource();
if(password != null){
jedis.auth(password);
}
if(db != null){
jedis.select(db);
}
return jedis;//从连接池中取一个Jedis对象
}
public static void release(Jedis jedis){
if(jedis != null){
jedis.close();//将jedis放回连接池
}
}
}
测试代码:
public static void main(String[] args) {
System.out.println(getJedis());
}
结果: