redis连接池操作
/**
* @類描述 redis 工具
* @功能名 POJO
* @author zxf
* @date 2014年11月25日
*/
public final class RedisUtil {
private static JedisPool jedisPool = null;
/**
* 初始化Redis連接池
*/
static {
try {
//加載redis配置文件
ResourceBundle bundle = ResourceBundle.getBundle("redis");
if (bundle == null) {
throw new IllegalArgumentException("[redis.properties] is not found!");
}
int maxActivity = Integer.valueOf(bundle.getString("redis.pool.maxActive"));
int maxIdle = Integer.valueOf(bundle.getString("redis.pool.maxIdle"));
long maxWait = Long.valueOf(bundle.getString("redis.pool.maxWait"));
boolean testOnBorrow = Boolean.valueOf(bundle.getString("redis.pool.testOnBorrow"));
boolean onreturn = Boolean.valueOf(bundle.getString("redis.pool.testOnReturn"));
//創建jedis池配置實例
JedisPoolConfig config = new JedisPoolConfig();
//設置池配置項值
config.setMaxActive(maxActivity);
config.setMaxIdle(maxIdle);
config.setMaxWait(maxWait);
config.setTestOnBorrow(testOnBorrow);
config.setTestOnReturn(onreturn);
jedisPool = new JedisPool(config, bundle.getString("redis.ip"), Integer.valueOf(bundle.getString("redis.port")));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 獲取Jedis實例
* @return
*/
public synchronized static Jedis getJedis() {
try {
if (jedisPool != null) {
Jedis resource = jedisPool.getResource();
return resource;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 釋放jedis資源
* @param jedis
*/
public static void returnResource(final Jedis jedis) {
if (jedis != null) {
jedisPool.returnResource(jedis);
}
}
/**
* 查詢數據
*/
public String find(String key,String value){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.get(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}finally{
jedisPool.returnResource(jedis);
}
}
/**
* 查詢特定字符串
*/
public String findSubStr(String key,Integer startOffset,Integer endOffset){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.getrange(key, startOffset, endOffset);
} catch (Exception e) {
e.printStackTrace();
return null;
}finally{
jedisPool.returnResource(jedis);
}
}
/**
* 向緩存中設置字符串內容 新增數據|修改
* @param key key
* @param value value
* @return
* @throws Exception
*/
public static int add(String key,String value) throws Exception{
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.set(key, value);
return 0;
} catch (Exception e) {
e.printStackTrace();
return -1;
}finally{
jedisPool.returnResource(jedis);
}
}
/**
* 刪除緩存中得對象,根據key
* @param key
* @return
*/
public static int del(String key){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.del(key);
return 0;
} catch (Exception e) {
e.printStackTrace();
return -1;
}finally{
jedisPool.returnResource(jedis);
}
}
}
轉載于:https://www.cnblogs.com/austinspark-jessylu/p/6088627.html
總結
以上是生活随笔為你收集整理的redis连接池操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android内部自带的SQLite数据
- 下一篇: 11.21 if条件语句 年月日执