这里使用的是 Spring-4.3 , redis-2.8 的版本
1、添加maven依赖
redis.clients jedis 2.8.0
2、编写自己的redisAPI
package com.del.tools; import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool; /** * 用于缓存的数据访问对象 * @author Domi */public class RedisAPI { //引入jedis连接池对象 public JedisPool jedisPool; public JedisPool getJedisPool() { return jedisPool; } public void setJedisPool(JedisPool jedisPool) { this.jedisPool = jedisPool; } /** * 缓存的设置 */ public boolean set(String key,String value){ Jedis jedis = null; try { jedis = jedisPool.getResource(); jedis.set(key,value); return true; } catch (Exception e) { // TODO: handle exceptionr e.printStackTrace(); }finally{ returnResource(jedisPool, jedis); } return false; } /** * 判断缓存中是否存在某个key值 */ public boolean exist(String key){ Jedis jedis =null; try { jedis = jedisPool.getResource(); return jedis.exists(key); } catch (Exception e) { // TODO: handle exception }finally{ returnResource(jedisPool, jedis); System.out.println("关闭成功===》"); } return false; } /** * 获得缓存中的key */ public String get(String key){ String value = null; Jedis jedis =null; try { jedis = jedisPool.getResource(); value = jedis.get(key); } catch (Exception e) { // TODO: handle exception }finally{ returnResource(jedisPool, jedis); } return value; } /** * 返还jedisPool */ public static void returnResource(JedisPool jedisPool,Jedis jedis){ if (jedis!=null) { jedisPool.returnResource(jedis); } } }
3、用spring管理redis的bean组件
4、在业务中使用redisAPI
/* * 根据userID查询购物车列表 * 使用redis缓存 */ @RequestMapping(value="/list") public ModelAndView doBuyCarList(HttpSession session){ ModelAndView madnv = new ModelAndView(); User user = (User)session.getAttribute("hasLogin"); if(user!=null){ //先判斷redis裡面有沒有值 Listbuycarlist1 = null; buycarlist1 = buyCarService.findBuyCarList(user.getUserid()); String buycarlist = JSON.toJSONString(buycarlist1,true); redisAPI.set("carlist"+user.getUserid(), buycarlist); madnv.addObject("buycarlist", buycarlist1); System.out.println("buycarlist====="+buycarlist1); System.out.println("FROM DB==>"); }else{ String buycarlist = redisAPI.get("carlist"+user.getUserid()); if (buycarlist!=null && !"".equals(buycarlist)) { buycarlist1 =JSON.parseArray(buycarlist, BuyCar.class); madnv.addObject("buycarlist", buycarlist1); System.out.println("buycarlist====="+buycarlist); System.out.println("FROM REDIS==>"); }else{ System.out.println("error==>"); } } } madnv.setViewName("buycar/shopping.jsp"); return madnv; }