Java自定義注解實現(xiàn)Redis自動緩存的方法
在實際開發(fā)中,可能經(jīng)常會有這樣的需要:從MySQL中查詢一條數(shù)據(jù)(比如用戶信息),此時需要將用戶信息保存至Redis。
剛開始我們可能會在查詢的業(yè)務邏輯之后再寫一段Redis相關操作的代碼,時間長了后發(fā)現(xiàn)這部分代碼實際上僅僅做了Redis的寫入動作,跟業(yè)務邏輯沒有實質的聯(lián)系,那么有沒有什么方法能讓我們省略這些重復勞動呢?
首先想到用AOP,在查詢到某些數(shù)據(jù)這一切入點(Pointcut)完成我們的切面相關處理(也就是寫入Redis)。那么,如何知道什么地方需要進行緩存呢,也就是什么地方需要用到AOP呢?參考數(shù)據(jù)庫事務的實現(xiàn)用到了@Transactional,那我們也可以自定義一個注解@RedisCache,將此注解用在需要的方法上,方法的返回結果作為需要保存的信息,方法的查詢參數(shù)(比如用戶的id)可以用來作為key。
上面的分析考慮下來貌似可行,那么接下來就動手實踐吧!
詳細步驟
1.創(chuàng)建一個自定義注解@RedisCache
package redis; import java.lang.annotation.*; /** * 自定義注解,結合AOP實現(xiàn)Redis自動緩存 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Inherited @Documented public @interface RedisCache { }
2.創(chuàng)建緩存寫入的輔助類:RedisHelper.java,其中包含一個范型方法用于接收不同類的實例對象,以保證我們的方法能夠通用。這里比較簡單,直接把對象轉成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)繞通知吧,按需要有取舍地使用具體某些類型的通知吧),我們這里用到了返回通知,也就是方法調用成功得到返回結果后進行切面處理動作
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è)務相關的代碼
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,其中get方法上使用了自定義注解@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,得到返回結果
連接Redis查看結果
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了,是不是很方便!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
了解spring中的CloudNetflix Hystrix彈性客戶端
這篇文章主要介紹了了解spring中的CloudNetflix Hystrix彈性客戶端,客戶端彈性模式是在遠程服務發(fā)生錯誤或表現(xiàn)不佳時保護遠程資源(另一個微服務調用或者數(shù)據(jù)庫查詢)免于崩潰。,需要的朋友可以參考下2019-06-06Java中@DateTimeFormat @JsonFormat失效原因及測試填坑
本文主要介紹了Java中@DateTimeFormat @JsonFormat失效原因及測試填坑,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-06-06