Redis作为缓存实现工具类

使用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();
     }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值