


How to cache database data to Redis through custom cache annotations in SpringBoot
Implementation
First create a new table bus_student in Mysql
Then use code generation based on this table, and the front-end Vue and back-end code generation are combined Add menu.
#Then come to the background code. In the background framework, the relevant dependencies and tool classes for operating redis have been added.
But you also need to add aspect dependencies here
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects --><dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.3.14.RELEASE</version> </dependency>
Then create annotations for adding 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;/* * @Author * @Description 新增redis缓存 **/@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD)public @interface AopCacheEnable {//redis缓存key String[] key();//redis缓存存活时间默认值(可自定义)long expireTime() default 3600; }
and deleting redis cache 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;/* * @Description 删除redis缓存注解 **/@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME)public @interface AopCacheEvict {//redis中的key值 String[] key(); }
Then create a new custom cache aspect specific 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; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit;/* * @Description 自定义缓存切面具体实现类 **/@Aspect @Componentpublic class CacheEnableAspect { @Autowiredpublic RedisTemplate redisCache;/** * Mapper层切点 使用到了我们定义的 AopCacheEnable 作为切点表达式。 */@Pointcut("@annotation(com.ruoyi.system.redisAop.AopCacheEnable)")public void queryCache() { }/** * Mapper层切点 使用到了我们定义的 AopCacheEvict 作为切点表达式。 */@Pointcut("@annotation(com.ruoyi.system.redisAop.AopCacheEvict)")public void ClearCache() { } @Around("queryCache()")public Object Interceptor(ProceedingJoinPoint pjp) { Object result = null;//注解中是否有#标识boolean spelFlg = false;//判断是否需要走数据库查询boolean selectDb = false;//redis中缓存的keyString redisKey = "";//获取当前被切注解的方法名Method method = getMethod(pjp);//获取当前被切方法的注解AopCacheEnable aopCacheEnable = method.getAnnotation(AopCacheEnable.class);//获取方法参数值Object[] arguments = pjp.getArgs();//从注解中获取字符串String[] spels = aopCacheEnable.key();for (String spe1l : spels) {if (spe1l.contains("#")) {//注解中包含#标识,则需要拼接spel字符串,返回redis的存储redisKeyredisKey = spe1l.substring(1) + arguments[0].toString(); } else {//没有参数或者参数是List的方法,在缓存中的keyredisKey = spe1l; }//取出缓存中的数据result = redisCache.opsForValue().get(redisKey);//缓存是空的,则需要重新查询数据库if (result == null || selectDb) {try { result = pjp.proceed();//从数据库查询到的结果不是空的if (result != null && result instanceof ArrayList) {//将redis中缓存的结果转换成对象listList<BusStudent> students = (List<BusStudent>) result;//判断方法里面的参数是不是BusStudentif (arguments[0] instanceof BusStudent) {//将rediskey-students 存入到redisredisCache.opsForValue().set(redisKey, students, aopCacheEnable.expireTime(), TimeUnit.SECONDS); } } } catch (Throwable e) { e.printStackTrace(); } } }return result; }/*** 定义清除缓存逻辑,先操作数据库,后清除缓存*/@Around(value = "ClearCache()")public Object evict(ProceedingJoinPoint pjp) throws Throwable {//redis中缓存的keyMethod method = getMethod(pjp);// 获取方法的注解AopCacheEvict cacheEvict = method.getAnnotation(AopCacheEvict.class);//先操作dbObject result = pjp.proceed();// 获取注解的key值String[] fieldKeys = cacheEvict.key();for (String spe1l : fieldKeys) {//根据key从缓存中删除 redisCache.delete(spe1l); }return result; }/** * 获取被拦截方法对象 */public Method getMethod(ProceedingJoinPoint pjp) { Signature signature = pjp.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method targetMethod = methodSignature.getMethod();return targetMethod; } }
@AopCacheEnable(key = "BusStudent",expireTime = 40)public List<BusStudent> selectBusStudentList(BusStudent busStudent);
/** * 新增学生 * * @param busStudent 学生 * @return 结果 */@AopCacheEvict(key = "BusStudent")public int insertBusStudent(BusStudent busStudent);/** * 修改学生 * * @param busStudent 学生 * @return 结果 */@AopCacheEvict(key = "BusStudent")public int updateBusStudent(BusStudent busStudent);/** * 删除学生 * * @param id 学生ID * @return 结果 */@AopCacheEvict(key = "BusStudent")public int deleteBusStudentById(Integer id);
the consumer to acce
The above is the detailed content of How to cache database data to Redis through custom cache annotations in SpringBoot. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

How to integrate GoWebSocket with a database: Set up a database connection: Use the database/sql package to connect to the database. Store WebSocket messages to the database: Use the INSERT statement to insert the message into the database. Retrieve WebSocket messages from the database: Use the SELECT statement to retrieve messages from the database.

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.

Use the DataAccessObjects (DAO) library in C++ to connect and operate the database, including establishing database connections, executing SQL queries, inserting new records and updating existing records. The specific steps are: 1. Include necessary library statements; 2. Open the database file; 3. Create a Recordset object to execute SQL queries or manipulate data; 4. Traverse the results or update records according to specific needs.

PHP database connection guide: MySQL: Install the MySQLi extension and create a connection (servername, username, password, dbname). PostgreSQL: Install the PgSQL extension and create a connection (host, dbname, user, password). Oracle: Install the OracleOCI8 extension and create a connection (servername, username, password). Practical case: Obtain MySQL data, PostgreSQL query, OracleOCI8 update record.

Through the Go standard library database/sql package, you can connect to remote databases such as MySQL, PostgreSQL or SQLite: create a connection string containing database connection information. Use the sql.Open() function to open a database connection. Perform database operations such as SQL queries and insert operations. Use defer to close the database connection to release resources.
