您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

SpringBoot中通过自定义缓存注解(AOP切面拦截)实现数据库数据缓存到Redis

bubuko 2022/1/25 19:01:57 java 字数 20068 阅读 822 来源 http://www.bubuko.com/infolist-5-1.html

场景 若依前后端分离版本地搭建开发环境并运行项目的教程: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/108465662 基于上面搭建起来前后端分离的Vue+SpringBoot的项目。 其中数据库使用的是Mysql,缓存层用的 ...

场景

若依前后端分离版本地搭建开发环境并运行项目的教程:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/108465662

基于上面搭建起来前后端分离的Vue+SpringBoot的项目。

其中数据库使用的是Mysql,缓存层用的是Redis。

数据库中某个表存储的信息,在业务代码比如定时任务中,需要频繁的查询。

所以将表中的数据存储到redis中一份。

其原理是,在调用查询方法时,判断redis中是否已经有,如果有则优先从redis中查询。

如果没有则在数据库中查询后并存入到Redis中一份,并给其设置过期时间。

这样在过期时间之内,查询数据会从redis中查询,过期之后会重新从Mysql中查询并存入到Redis一份。

并且还要实现,再对这个Mysql表进行新增、编辑、删除的操作时,将redis中存储的数据

进行删除,这样下次查询就会查询数据库中最新的。

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

首先在Mysql中新建一个表bus_student

技术分享图片

 

 

技术分享图片

然后基于此表使用代码生成,前端Vue与后台各层代码生成并添加菜单。

技术分享图片

 

 

然后来到后台代码中,在后台框架中已经添加了操作redis的相关依赖和工具类。

但是这里还需要添加aspect依赖

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>

 

然后在存放配置类的地方新建新增redis缓存的注解

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;

}

 

以及删除redis缓存的注解

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();
}

 

然后再新建一个自定义缓存切面具体实现类CacheEnableAspect

存放位置

技术分享图片

 

 

技术分享图片

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
@Component
public class CacheEnableAspect {

    @Autowired
    public 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中缓存的key
        String 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的存储redisKey
                redisKey = spe1l.substring(1) + arguments[0].toString();
            } else {
                //没有参数或者参数是List的方法,在缓存中的key
                redisKey = spe1l;
            }
            //取出缓存中的数据
            result = redisCache.opsForValue().get(redisKey);
            //缓存是空的,则需要重新查询数据库
            if (result == null || selectDb) {
                try {
                    result =  pjp.proceed();
                    //从数据库查询到的结果不是空的
                    if (result != null && result instanceof ArrayList) {
                        //将redis中缓存的结果转换成对象list
                        List<BusStudent> students = (List<BusStudent>) result;
                        //判断方法里面的参数是不是BusStudent
                        if (arguments[0] instanceof BusStudent) {
                            //将rediskey-students 存入到redis
                            redisCache.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中缓存的key
        Method method = getMethod(pjp);
        // 获取方法的注解
        AopCacheEvict cacheEvict = method.getAnnotation(AopCacheEvict.class);
        //先操作db
        Object 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;
    }
}

 

注意这里的queryCache和ClearCache,里面切点表达式

分别对应上面自定义的两个AopCacheEnable和AopCacheEvict。

然后在环绕通知的queryCache方法执行前后时

获取被切方法的参数,参数中的key,然后根据key去redis中去查询,

如果查不到,就把方法的返回结果转换成对象List,并存入到redis中,

如果能查到,则将结果返回。

然后找到这个表的查询方法,mapper层,比如要将查询的返回结果存储进redis

    @AopCacheEnable(key = "BusStudent",expireTime = 40)
    public List<BusStudent> selectBusStudentList(BusStudent busStudent);

 

然后在这个表的新增、编辑、删除的mapper方法上添加

    /**
     * 新增学生
     *
     * @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);

 

注意这里的注解上的key要和上面的查询的注解的key一致。

然后启动项目,如果启动时提示:

Consider marking one of the beans as @Primary, updating the consumer to acce

技术分享图片

技术分享图片

 

 

因为sringboot通过@Autowired注入接口的实现类时发现有多个,也就是有多个类继承了这个接口,spring容器不知道使用哪一个。

找到redis的配置类,在RedisTemplate上添加@Primary注解

技术分享图片

 技术分享图片

 

 

验证注解的使用

debug启动项目,在CacheEnableAspect中查询注解中打断点,然后调用查询方法,

就可以看到能进断点,然后就可以根据自己想要的逻辑和效果进行修改注解。

技术分享图片

 

 

技术分享图片

第一次查询时redis中是没有的,所以会走mysql查询,在过期时间之内就不再查询mysq,而是查询redis了。

技术分享图片

 

 

技术分享图片

然后再调用新增、编辑、删除接口时会将redis中缓存的数据删掉。

但是使用若依这套框架,在新增、编辑、删除操作后会调用查询接口,所以会直接又存储进来。

所以可以用postman等接口测试工具测试。

然后就是当操作完之后如果redis中的数据还没过期,前端页面查询的仍然是redis中的数据,不是最新数据。

所以redis中过期的时间自己把握。

另外此种缓存机制,建议不要和前端请求的mapper进行混用。

建议自定义新的mapper只取用需要的数据,然后给其他比如高频率的定时任务查询用。

SpringBoot中通过自定义缓存注解(AOP切面拦截)实现数据库数据缓存到Redis

原文:https://www.cnblogs.com/badaoliumangqizhi/p/14939964.html


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶