Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to cache database data to Redis through custom cache annotation in SpringBoot

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to cache database data to Redis through custom cache annotations in SpringBoot". The explanation in this article is simple and clear, easy to learn and understand, and now please follow the editor's idea to slowly deepen, to study and learn "how to cache database data to Redis through custom cache annotations in SpringBoot".

First create a new table bus_student in Mysql

Then use code generation based on this table, front-end Vue and background layers of code generation and add menus.

Then come to the background code, where the related dependencies and utility classes for manipulating redis have been added to the background framework.

But you also need to add aspect dependencies here

Org.springframework spring-aspects 4.3.14.RELEASE

Then create a new redis cache comment in the place where the configuration class is stored

Package com.ruoyi.system.redisAop;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/* * @ Author * @ Description added redis cache * * / @ Retention (RetentionPolicy.RUNTIME) @ Target (ElementType.METHOD) public @ interface AopCacheEnable {/ / redis cache key String [] key (); / / redis cache lifetime default (customizable) long expireTime () default 3600;}

And delete the comments for redis cache

Package com.ruoyi.system.redisAop;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/* * @ Description deletes redis cache comments * * / @ Target (ElementType.METHOD) @ Retention (RetentionPolicy.RUNTIME) public @ interface AopCacheEvict {/ / redis key value String [] key ();}

Then create a custom cache aspect concrete implementation class CacheEnableAspect

Storage location

Package com.ruoyi.system.redisAop;import com.ruoyi.system.domain.BusStudent;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.Signature;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Pointcut;import org.aspectj.lang.reflect.MethodSignature;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.stereotype.Component;import java.lang.reflect.Method The import java.util.ArrayList;import java.util.List;import java.util.concurrent.TimeUnit;/* * @ Description custom cache aspect concrete implementation class * * / @ Aspect@Componentpublic class CacheEnableAspect {@ Autowiredpublic RedisTemplate redisCache;/** * Mapper layer pointcut uses the AopCacheEnable we defined as the pointcut expression. The * / @ Pointcut ("@ annotation (com.ruoyi.system.redisAop.AopCacheEnable)") public void queryCache () {} / * Mapper layer pointcut uses the AopCacheEvict we defined as the pointcut expression. * / @ Pointcut ("@ annotation (com.ruoyi.system.redisAop.AopCacheEvict)") public void ClearCache () {} @ Around ("queryCache ()") public Object Interceptor (ProceedingJoinPoint pjp) {Object result = null;// Note whether there is a # flag boolean spelFlg = false;// to determine whether it is necessary to use the keyString redisKey = "" cached in the database query boolean selectDb = false;//redis; / / to get the name of the method currently being annotated Method method = getMethod (pjp) / / get the annotation of the current cut method AopCacheEnable aopCacheEnable = method.getAnnotation (AopCacheEnable.class); / / get the method parameter value Object [] arguments = pjp.getArgs (); / / get the string String [] spels = aopCacheEnable.key () from the comment For (String spe1l: spels) {if (spe1l.contains ("#")) {/ / contains the # flag, then you need to concatenate the spel string and return the redis storage redisKeyredisKey = spe1l.substring (1) + arguments [0] .toString ();} else {/ / has no parameter or the parameter is the method of List, and keyredisKey = spe1l;} / / fetches the data in the cache result = redisCache.opsForValue (). Get (redisKey) / / if the cache is empty, you need to re-query the database if (result = = null | | selectDb) {try {result = pjp.proceed (); / / the result queried from the database is not empty if (result! = null & & result instanceof ArrayList) {/ / convert the cached result in redis to object listList students = (List) result / / determine whether the parameter in the method is BusStudentif (arguments [0] instanceof BusStudent) {/ / store rediskey-students into redisredisCache.opsForValue (). Set (redisKey, students, aopCacheEnable.expireTime (), TimeUnit.SECONDS);} catch (Throwable e) {e.printStackTrace () } return result;} / * defines clearing cache logic, first operating the database, then clearing the cache * / @ Around (value = "ClearCache ()") public Object evict (ProceedingJoinPoint pjp) throws Throwable {/ / redis cached keyMethod method = getMethod (pjp); / / get the annotation of the method AopCacheEvict cacheEvict = method.getAnnotation (AopCacheEvict.class); / / operate dbObject result = pjp.proceed () first / / get the annotated key value String [] fieldKeys = cacheEvict.key (); for (String spe1l: fieldKeys) {/ / remove redisCache.delete (spe1l) from the cache according to key;} return result;} / * get the intercepted method object * / public Method getMethod (ProceedingJoinPoint pjp) {Signature signature = pjp.getSignature (); MethodSignature methodSignature = (MethodSignature) signature Method targetMethod = methodSignature.getMethod (); return targetMethod;}}

Notice the queryCache and ClearCache here, where the tangent expression

Correspond to the two AopCacheEnable and AopCacheEvict customized above.

Then when the queryCache method of the surround notification is executed

Get the parameters of the cut method and the key in the parameters, and then go to redis to query according to key.

If not, the returned result of the method is converted into an object List and stored in redis.

If it can be found, the result is returned.

Then find the query method of this table, the mapper layer, for example, to store the returned results of the query in redis

AopCacheEnable (key = "BusStudent", expireTime = 40) public List selectBusStudentList (BusStudent busStudent)

Then add to the mapper methods for adding, editing, and deleting the table

/ * * New param busStudent student * @ return result * / @ AopCacheEvict (key = "BusStudent") public int insertBusStudent (BusStudent busStudent); / * modify student * * @ param busStudent student * @ return result * / @ AopCacheEvict (key = "BusStudent") public int updateBusStudent (BusStudent busStudent) / * Delete student * * @ param id student ID * @ return result * / @ AopCacheEvict (key = "BusStudent") public int deleteBusStudentById (Integer id)

Note that the key on the comments here is the same as the key of the comments in the query above.

Then start the project, if prompted at startup:

Consider marking one of the beans as @ Primary, updating

The consumer to acce

Because sringboot found multiple classes when it injected the implementation class of the @ Autowired interface, that is, multiple classes inherited the interface, the spring container didn't know which one to use.

Find the configuration class of redis and add @ Primary annotation to RedisTemplate

Verify the use of annotations

Debug starts the project, queries the breakpoints in the comments in CacheEnableAspect, and then calls the query method

You can see that you can enter the breakpoint, and then you can modify the comments according to the logic and effect you want.

Thank you for reading, the above is the content of "how to cache database data to Redis through custom cache annotations in SpringBoot". After the study of this article, I believe you have a deeper understanding of how to cache database data to Redis through custom cache annotations in SpringBoot, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report