在實(shí)際開發(fā)中,可能經(jīng)常會(huì)有這樣的需要:從MySQL中查詢一條數(shù)據(jù)(比如用戶信息),此時(shí)需要將用戶信息保存至Redis。
剛開始我們可能會(huì)在查詢的業(yè)務(wù)邏輯之后再寫一段Redis相關(guān)操作的代碼,時(shí)間長了后發(fā)現(xiàn)這部分代碼實(shí)際上僅僅做了Redis的寫入動(dòng)作,跟業(yè)務(wù)邏輯沒有實(shí)質(zhì)的聯(lián)系,那么有沒有什么方法能讓我們省略這些重復(fù)勞動(dòng)呢?
首先想到用AOP,在查詢到某些數(shù)據(jù)這一切入點(diǎn)(Pointcut)完成我們的切面相關(guān)處理(也就是寫入Redis)。那么,如何知道什么地方需要進(jìn)行緩存呢,也就是什么地方需要用到AOP呢?參考數(shù)據(jù)庫事務(wù)的實(shí)現(xiàn)用到了@Transactional,那我們也可以自定義一個(gè)注解@RedisCache,將此注解用在需要的方法上,方法的返回結(jié)果作為需要保存的信息,方法的查詢參數(shù)(比如用戶的id)可以用來作為key。
上面的分析考慮下來貌似可行,那么接下來就動(dòng)手實(shí)踐吧!
詳細(xì)步驟
1.創(chuàng)建一個(gè)自定義注解@RedisCache
package redis;import java.lang.annotation.*;/** * 自定義注解,結(jié)合AOP實(shí)現(xiàn)Redis自動(dòng)緩存 */@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)@Inherited@Documentedpublic @interface RedisCache {}2.創(chuàng)建緩存寫入的輔助類:RedisHelper.java,其中包含一個(gè)范型方法用于接收不同類的實(shí)例對(duì)象,以保證我們的方法能夠通用。這里比較簡(jiǎn)單,直接把對(duì)象轉(zhuǎn)成json,在Redis中用string保存。而且不管什么情況統(tǒng)統(tǒng)寫入,實(shí)際還可以完善下具體邏輯,比如判斷緩存是否已存在,緩存信息是否最新等等。
package redis;import com.alibaba.fastjson.JSONObject;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.StringRedisTemplate;import org.springframework.stereotype.Component;@Componentpublic class RedisHelper { @Autowired private StringRedisTemplate stringRedisTemplate; public <T> void saveCache(String key,T t){ String json = JSONObject.toJSONString(t); stringRedisTemplate.opsForValue().set(key,json); }}3.創(chuàng)建RedisCacheAspect.java,利用AOP框架AspectJ完成切面處理(用萬金油環(huán)繞通知吧,按需要有取舍地使用具體某些類型的通知吧),我們這里用到了返回通知,也就是方法調(diào)用成功得到返回結(jié)果后進(jìn)行切面處理動(dòng)作
package redis;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Pointcut;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;@Aspect@Componentpublic class RedisCacheAspect { @Autowired private RedisHelper redisHelper; @Pointcut("@annotation(redis.RedisCache)") public void setJoinPoint(){} //環(huán)繞通知:可以獲取返回值 @Around(value = "setJoinPoint()") public Object aroundMethod(ProceedingJoinPoint proceedingJoinPoint){ Object result = null; try { //前置通知 result = proceedingJoinPoint.proceed(); //返回通知 //緩存至Redis Object[] args = proceedingJoinPoint.getArgs(); //key策略:需要緩存的對(duì)象的全類名-id,如:entity.User-1 redisHelper.saveCache(result.getClass().getName()+"-"+args[0],result); } catch (Throwable e) { //異常通知 } //后置通知 return result; }}4.接下來是具體業(yè)務(wù)相關(guān)的代碼
UserController.java
package controller;import com.alibaba.fastjson.JSONObject;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;import service.UserService;@SuppressWarnings("unused")@Controllerpublic class UserController { @Autowired private UserService userService; @RequestMapping(value = "/user/{id}", method = RequestMethod.GET,produces = "application/json;charset=utf-8") @ResponseBody public String test(@PathVariable Long id){ return JSONObject.toJSONString(userService.get(id)); }}UserService.java,其中g(shù)et方法上使用了自定義注解@RedisCache
package service;import dao.UserDao;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import redis.RedisCache;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;@Servicepublic class UserService<User> implements BaseService<User> { @Autowired private UserDao userDao; public Map add(User user) { return null; } public Map update(User user) { return null; } @RedisCache public User get(Long id) { return (User) userDao.get(id); } public List<User> query(User user) { List<User> list = new ArrayList<User>(); list = userDao.query(user); return list; } public Map delete(User user) { return null; }}5.測(cè)試
瀏覽器直接訪問http://localhost:8080/user/1,得到返回結(jié)果
連接Redis查看結(jié)果
127.0.0.1:6381> keys entity*1) "entity.User-1"127.0.0.1:6381> get entity.User-1"{/"id/":1,/"mobile/":/"110/",/"name/":/"/xe7/x94/xa8/xe6/x88/xb71/",/"password/":/"123456/",/"username/":/"0001/"}"127.0.0.1:6381>好了,到此我們已經(jīng)看到開頭的想法驗(yàn)證成功了,只需要在查詢的方法上加上注解@RedisCache,就自動(dòng)地悄無聲息地寫入Redis了,是不是很方便!
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選