使用Redis作为缓存对象,常用的存储格式为字符串,所以在存储缓存时,将对象转为字符串存储.由于存的时候为字符串,所以取出的也为json字符串.
此工具类在设值时只需要将key与对象传入即可
取值时只需要将key与要取的对象类型传入即可
public class CacheUtilImpl implements CacheUtil {
private Jedis jedis = JedisUtil.getJedis();
@Override
public <T> Object getCache(String key, Class<T> cls) {
Object obj = null;
try {
Gson gson = new Gson();
String json = jedis.get(key);
String s = json.substring(0, 1);
if(s.equals("[")){
List<T> list = new ArrayList<T>();
JsonArray arry = new JsonParser().parse(json).getAsJsonArray();
for (JsonElement jsonElement : arry) {
list.add(gson.fromJson(jsonElement, cls));
}
obj=list;
}else{
obj = gson.fromJson(json, cls);
}
return obj;
} catch (Exception e) {
return null;
}finally {
JedisUtil.close(jedis);
}
}
@Override
public boolean setCache(String key,Object obj) {
try {
Gson gson = new Gson();
String json = gson.toJson(obj);
String s = jedis.set(key, json);
if(s.equals("OK")){
return true;
}
return false;
} catch (Exception e) {
return false;
}finally {
JedisUtil.close(jedis);
}
}
}
Redis连接池工具类
public class JedisUtil {
//连接池
private static JedisPool pool;
//连接密码
private static String pwd = "123";
static{
JedisPoolConfig poolConf = new JedisPoolConfig();
poolConf.setMaxTotal(10);
poolConf.setMaxIdle(5);
poolConf.setMaxWaitMillis(5000);
pool = new JedisPool(poolConf, "localhost", 6379);
}
public static Jedis getJedis(){
Jedis jedis= pool.getResource();
jedis.auth(pwd);
return jedis;
}
public static void close(Jedis jedis){
jedis.close();
}
}