引入spring-data-redis包、jedis、connection-pool包
applicationContext.xml的配置
<!-- redis Connection --> <bean id="redisConnection" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="localhost"></property> <property name="port" value="6379"></property> </bean> <!-- redisTemplate --> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="redisConnection"></property> </bean>
做一個簡單的測試
@Test public void test1() { Jedis jd = new Jedis("localhost",6379); String ping = jd.ping(); System.out.println(ping); Set<String> keys = jd.keys("*"); for(String k:keys){ System.out.println(k + ":"+ jd.type(k)); } jd.close(); } @Test public void test2(){ Jedis j=new Jedis("localhost", 6379); System.out.println(j.ping()); Set<String> filed= j.hkeys("dept"); System.out.println(filed); for(String s:filed){ System.out.println(j.hget("dept", s)); } j.close(); }
自己寫一個工具類將,進行序列化與反序列化,

public class SerializableUtil { public static byte[] objectToBytes(Object obj) {// 將對象轉換為byte數組 ByteArrayOutputStream baos = null; ObjectOutputStream oos = null; try { baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); oos.writeObject(obj);// 將數據序列化后寫入到baos中 byte[] byte1 = baos.toByteArray(); return byte1; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } finally { try { baos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { oos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static Object byteToObject(byte[] bytes) { ByteArrayInputStream bais = null; ObjectInputStream ois = null; try { bais = new ByteArrayInputStream(bytes); ois = new ObjectInputStream(bais); Object obj = ois.readObject(); return obj; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } finally { try { bais.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { ois.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
測試:
@Test public void test4(){ DeptBean bean=new DeptBean(124, "zhangsan1", "shanghai"); Jedis j=new Jedis("localhost", 6379); j.set("dept".getBytes(), SerializableUtil.objectToBytes(bean)); j.close(); } @Test public void test5(){ Jedis j=new Jedis("localhost", 6379); byte[] bean=j.get("dept".getBytes());//獲取到的是byte數組 //在將byte數組反序列化 DeptBean byteToObject = (DeptBean) SerializableUtil.byteToObject(bean); System.out.println(byteToObject); j.close(); }
上面只是簡單的使用自己寫的一個工具類進行序列化與反序列化,實際開發中還是使用工具進行的,
寫一個控制器,對其進行單元測試
@RunWith(SpringJUnit4ClassRunner.class)//這里的意思是進行一個spring環境的配置 @ContextConfiguration(locations = "classpath:applicationContext.xml")//讓其能不啟動tomcat服務器的情況下進行測試 public class TestRedis_Data { @Autowired//自動裝載 public RedisTemplate<Object, Object> tem; @Test public void test1() { // tem.setConnectionFactory(connectionFactory); // RedisTemplate DeptBean dept = new DeptBean(10, "傻強", "上海"); tem.opsForValue().set("mydeptsingle", dept);//直接可以設置對象,將其進行序列化 DeptBean object = (DeptBean) tem.opsForValue().get("mydeptsingle");// 底層已經序列化了 System.out.println(object.getDeptno() + " " + object.getDname() + " " + object.getLoc()); } }
然后在對自己有緩存需求的方法進行開啟Redis緩存,
//@Controller @RestController //相當於@Controller 和 @ResponseBody 相結合的功能 public class DeptController { @Autowired //自動裝載 private DeptDao dao; //使用redis @Autowired private RedisTemplate<Object, Object> temp; @RequestMapping(value = "/dept/all", method = RequestMethod.GET) // @ResponseBody public List<DeptBean> selectAll() { List<DeptBean> Deptlist = (List<DeptBean>) temp.opsForValue().get("Deptlist"); List<DeptBean> list = null; if (Deptlist.isEmpty()) { list = dao.findAll(); temp.opsForValue().set("Deptlist", list); return list; } return Deptlist; } // 查詢 @RequestMapping(value = "/dept/get", method = RequestMethod.GET) public DeptBean selelctDeptById(@RequestParam("no") int id) { // 從Redis中取出來 DeptBean bean = (DeptBean) temp.opsForValue().get("dept" + id); // 如果沒有,從數據庫中取出來並返回 if (bean == null) { System.out.println("從數據庫中取"); DeptBean findbean = dao.findId(id); temp.opsForValue().set("dept" + id, findbean); return findbean; } System.out.println("從緩存中取的數據"); return bean; } // 分頁查詢 // 騎牛地址: http://localhost:8060/Spring_Mybatis02/dept/list?page=3&size=3 @RequestMapping(value = "/dept/list", method = RequestMethod.GET) public PageBean pageSelect( @RequestParam(defaultValue = "1", required = false) int page, @RequestParam(defaultValue = "5", required = false) int size) { Page p = PageHelper.startPage(page, size);// 引入jar包中的jar文件,分頁只對下一條查詢代碼有作用 List<DeptBean> list = dao.findAll(); System.out.println("當前頁" + p.getPageNum() + " 總頁數" + p.getPages() + " 總記錄數" + p.getTotal()); PageBean bean = new PageBean(); bean.setList(list); bean.setPagesize(size); bean.setTotalpages(p.getPages()); bean.setTotalRecords(p.getTotal()); return bean; } // 刪除 @RequestMapping(value = "/dept/delete", method = RequestMethod.POST) public int deleteDeptById(int deptno) { //刪除緩存 temp.delete("dept" + deptno); //從數據庫刪除 return dao.deleteDeptById(deptno); } }
當然如果你需要在項目啟動時候就加載到內存中,則可以這樣,另寫一個專門加載需要緩存的數據
@Component public class InitLoadData { @Resource //裝載dao層 private DeptDao dao; @Resource private RedisTemplate<Object,Object> temp; //裝載Redis中的bean配置 @PostConstruct//項目啟動時候就會啟動該方法 的注解 public void inint(){ System.out.println("查詢數據庫將數據加載到Redis中"); DeptBean dept=dao.findId(10); temp.opsForValue().set("dept10", dept); } }