您好,登錄后才能下訂單哦!
在實際開發(fā)中,可能經(jīng)常會有這樣的需要:從MySQL中查詢一條數(shù)據(jù)(比如用戶信息),此時需要將用戶信息保存至Redis。
剛開始我們可能會在查詢的業(yè)務(wù)邏輯之后再寫一段Redis相關(guān)操作的代碼,時間長了后發(fā)現(xiàn)這部分代碼實際上僅僅做了Redis的寫入動作,跟業(yè)務(wù)邏輯沒有實質(zhì)的聯(lián)系,那么有沒有什么方法能讓我們省略這些重復(fù)勞動呢?
首先想到用AOP,在查詢到某些數(shù)據(jù)這一切入點(Pointcut)完成我們的切面相關(guān)處理(也就是寫入Redis)。那么,如何知道什么地方需要進行緩存呢,也就是什么地方需要用到AOP呢?參考數(shù)據(jù)庫事務(wù)的實現(xiàn)用到了@Transactional,那我們也可以自定義一個注解@RedisCache,將此注解用在需要的方法上,方法的返回結(jié)果作為需要保存的信息,方法的查詢參數(shù)(比如用戶的id)可以用來作為key。
上面的分析考慮下來貌似可行,那么接下來就動手實踐吧!
詳細(xì)步驟
1.創(chuàng)建一個自定義注解@RedisCache
package redis; import java.lang.annotation.*; /** * 自定義注解,結(jié)合AOP實現(xiàn)Redis自動緩存 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Inherited @Documented public @interface RedisCache { }
2.創(chuàng)建緩存寫入的輔助類:RedisHelper.java,其中包含一個范型方法用于接收不同類的實例對象,以保證我們的方法能夠通用。這里比較簡單,直接把對象轉(zhuǎn)成json,在Redis中用string保存。而且不管什么情況統(tǒng)統(tǒng)寫入,實際還可以完善下具體邏輯,比如判斷緩存是否已存在,緩存信息是否最新等等。
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; @Component public 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é)果后進行切面處理動作
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 @Component public 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策略:需要緩存的對象的全類名-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") @Controller public 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; @Service public 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.測試
瀏覽器直接訪問http://localhost:8080/user/1,得到返回結(jié)果
http://localhost:8080/user/1
連接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)看到開頭的想法驗證成功了,只需要在查詢的方法上加上注解@RedisCache,就自動地悄無聲息地寫入Redis了,是不是很方便!
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。