1初始化连接池配置
public class RedisPoolUntil {
private static JedisPool jedisPool = null;
public static JedisPool createJedisPool() {
// TODO Auto-generated method stub
//服务器IP
String ADDR = "redisIp地址";
//的端口号
int PORT = 6379;
//的端口号
String PASS = "密码;
//可用连接实例的最大数目,默认值为8;
//如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
int MAX_ACTIVE = 50;
//控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
int MAX_IDLE = 10;
//等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
int MAX_WAIT = 30000;
//客户端闲置多少秒后,断开连接
int TIME_OUT=0;
//在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
boolean TEST_ON_BORROW = true;
/**
* 初始化Redis连接池
*/
try {
if(jedisPool==null){
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(MAX_ACTIVE);
config.setMaxIdle(MAX_IDLE);
config.setMaxWaitMillis(MAX_WAIT);
config.setTestOnBorrow(TEST_ON_BORROW);
// jedisPool = new JedisPool(config, ADDR, PORT);
jedisPool=new JedisPool(config, ADDR, PORT,TIME_OUT, PASS);
System.out.println("11111111");
}
} catch (Exception e) {
System.out.println("初始化连接池失败");
e.printStackTrace();
System.out.println(e);
}
return jedisPool;
}
}
2使用连接池
public static void main(String[] args) {
Jedis jedis = null;
try {
jedis = createJedisPool().getResource();
jedis.set("1", "2");
} catch (Exception e) {
System.out.println("redis增加数据失败");
System.out.println(e);
} finally {
jedis.close();// 释放redis对象,如果不释放会占用连接数,连接数就会越来越高,以至于导致出现错误
}
}
}