对基于Spring的redis客户端框架redis/twemproxy-redis/redis-cluster进行开发代码编写,但是在单元测试代码(或者功能测试代码)验证时,需要使用Jedis客户端。下面是对Jedis客户端的进一步封装,使其支持连接池的概念。
package test;
import java.util.ResourceBundle;
import com.alibaba.fastjson.JSON;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
* <p>
* Redis Client - Jedis pool
* </p>
* @author liang01.ma
* @如果以下代码没有Bug, 那肯定是马亮写的;如果有bug,那我不知道是谁写的!
*/
public class RedisClient {
public static JedisPool jedisPool; // jedis连接池
static {
ResourceBundle resourceBundle = ResourceBundle.getBundle("redis");
int maxActive = Integer.parseInt(resourceBundle.getString("redis.pool.maxActive"));
int maxIdle = Integer.parseInt(resourceBundle.getString("redis.pool.maxIdle"));
int maxWait = Integer.parseInt(resourceBundle.getString("redis.pool.maxWait"));
String ip = resourceBundle.getString("redis.ip");
int port = Integer.parseInt(resourceBundle.getString("redis.port"));
JedisPoolConfig config = new JedisPoolConfig();
//设置最大连接数
config.setMaxTotal(maxActive);
//设置最大空闲数
config.setMaxIdle(maxIdle);
//设置超时时间
config.setMaxWaitMillis(maxWait);
//初始化连接池
jedisPool = new JedisPool(config, ip, port);
}
/**
* Set 'String' to redis
* @param key key
* @param value value
* @return
* @throws Exception
*/
public static boolean set(String key,String value) throws Exception{
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}finally{
jedisPool.returnResource(jedis);
}
}
/**
* Set 'Object' to redis
* @param key
* @param value
* @return
*/
public static boolean set(String key,Object value){
Jedis jedis = null;
try {
String objectJson = JSON.toJSONString(value);
jedis = jedisPool.getResource();
jedis.set(key, objectJson);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}finally{
jedisPool.returnResource(jedis);
}
}
/**
* del value by key from redis
* @param key
* @return
*/
public static boolean del(String key){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.del(key);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}finally{
jedisPool.returnResource(jedis);
}
}
/**
* get value by key
* @param key
* @return
*/
public static Object get(String key){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
Object value = jedis.get(key);
return value;
} catch (Exception e) {
e.printStackTrace();
return false;
}finally{
jedisPool.returnResource(jedis);
}
}
/**
* get value by key from redis
* @param key
* @return
*/
public static <T> T get(String key,Class<T> clazz){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String value = jedis.get(key);
return JSON.parseObject(value, clazz);
} catch (Exception e) {
e.printStackTrace();
return null;
}finally{
jedisPool.returnResource(jedis);
}
}
}