您的位置:首页 > 数据库 > Redis

redis在java中的客户端连接

2016-01-18 18:05 861 查看
单例模式下创建连接池,包括断线重连等机制。

public class RedisClient {

private static JedisPool pool = null;
private RedisClient(){

initial();
}
private static RedisClient client = new RedisClient();
public static RedisClient getClient(){
return client;
}

private void initial() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxActive(30000);
jedisPoolConfig.setMaxIdle(600);
jedisPoolConfig.setMaxWait(1000);
jedisPoolConfig.setTestOnBorrow(true);
if (pool == null) {
try {
pool = new JedisPool(jedisPoolConfig, "10.0.201.140", 5379,4000000);
} catch (Exception e) {
e.printStackTrace();
pool.destroy();
initial();//断线重连
}
}
}
/**
* 获取redis连接的 Pipelined
* @return
*/
public synchronized jedis getJedis() {
Jedis jd = null;
try {
jd= pool.getResource();
} catch (Exception e) {
if(jd!=null){
pool.returnBrokenResource(jd);
}
e.printStackTrace();
jd = getJedis();//递归进行断线重连
}
return jd;
}
/**
* 释放被损坏的jedis.
*
* @param jd
*/
public synchronized void releaseBrokenJedis(Jedis jd) {
pool.returnBrokenResource(jd);
jd = null;
}

/**
* 从连接池中释放jedis
*
* @param jd
*/
public synchronized void releaseJedis(Jedis jd) {
pool.returnResource(jd);
jd = null;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: