Redis作為快取實現工具類
阿新 • • 發佈:2018-12-07
使用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();
}
}