美文网首页
Redis-Spring Cache

Redis-Spring Cache

作者: 石头耳东 | 来源:发表于2022-04-26 09:45 被阅读0次

    零、本文纲要

    • 一、Spring Cache介绍
    1. Spring Cache
    2. Spring Cache常用注解
    • 二、 Spring Cache使用
    1. 导入maven坐标
    2. 配置application.yml
    3. 在启动类上加入@EnableCaching注解,开启缓存注解功能
    4. 在Controller的方法上加入对应注解,进行缓存操作

    一、Spring Cache介绍

    1. Spring Cache

    基于注解的缓存功能,通过CacheManager接口来统一不同的缓存技术。
    CacheManager是Spring提供的各种缓存技术的抽象接口。

    CacheManager 描述
    EhCacheCacheManager 使用EhCache作为缓存技术
    GuavaCacheManager 使用Google的GuavaCache作为缓存技术
    RedisCacheManager 使用Redis作为缓存技术

    2. Spring Cache常用注解

    注解 说明
    @EnableCaching 开启缓存注解功能
    @Cacheable 在方法执行前Spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;</br>若没有数据,调用方法并将方法返回值放到缓存中
    @CachePut 将方法的返回值放到缓存中
    @CacheEvict 将一条或多条数据从缓存中删除

    在Spring Boot项目中,使用缓存技术只需要在项目中导入相关缓存技术的依赖包,并在启动类上使用@EnableCaching注解开启缓存支持即可。
    例如,使用Redis作为缓存技术,则只需要导入spring-data-redis的maven坐标。

    • 2.1 @CachePut注解

    @CachePut:将方法的返回值放到缓存中

    ① value

    缓存的名称,每个缓存名称下面可以有多个key

    ② key

    缓存的key
    #result:返回的结果
    #root:当前方法体
    #形参名:参数体,数据是方法执行后的数据

    实例:
    key = "#root.args[0]"
    key = "#p0"
    key = "#首位形参名" 推荐此种写法,可读性更强

    @Cacheable与@CachePut均有此属性,此处使用@Cacheable注解为例,如下:

    @GetMapping("/dish/{id}")
    //@Cacheable(value = "setmeal", key = "#root.args[0]")
    //@Cacheable(value = "setmeal", key = "#p0")
    @Cacheable(value = "setmeal", key = "#id")
    public R<SetmealDto> getDish(@PathVariable Long id){
        ... ...
    }
    
    • 2.2 @CacheEvict

    @CacheEvict:将一条或多条数据从缓存中删除

    value、key属性同上

    ① allEntries

    allEntries = true 表示删除该分类下所有缓存,默认为false

    @DeleteMapping
    @CacheEvict(value = "setmeal", allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids){
        ... ...
    }
    
    • 2.3 @Cacheable注解

    @Cacheable:先查询缓存,有则直接返回,否则调用方法并将返回值放到缓存中

    value、key属性同上

    ① condition

    满足这个条件,则缓存该数据

    ② unless

    满足这个条件,则不缓存该数据

    二、 Spring Cache使用

    1. 导入maven坐标

    spring-boot-starter-data-redis
    spring-boot-starter-cache

    <!--redis-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <!--cache-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    

    2. 配置application.yml

    spring:
        cache:
            redis:
                time-to-live: 1800000 # 设置缓存有效期
    

    3. 在启动类上加入@EnableCaching注解,开启缓存注解功能

    @Slf4j
    @SpringBootApplication
    @ServletComponentScan
    @EnableTransactionManagement
    @EnableCaching // 开启缓存注解的支持
    public class DemoApplication {
        public static void main(String[] args) {
            SpringApplication.run(ReggieApplication.class, args);
            log.info("项目启动成功!");
        }
    }
    

    4. 在Controller的方法上加入对应注解,进行缓存操作

        /**
         * 根据条件查询套餐数据
         * @param setmeal 套餐
         * @return 结果信息
         */
        @GetMapping("/list")
        @Cacheable(value = "setmeal", key = "#setmeal.categoryId + ':' + #setmeal.status")
        public R<List<Setmeal>> list(Setmeal setmeal){
            // 构造查询条件
            LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(setmeal.getCategoryId() != null,
                    Setmeal::getCategoryId, setmeal.getCategoryId());
            wrapper.eq(setmeal.getStatus() != null,
                    Setmeal::getStatus, setmeal.getStatus());
            wrapper.orderByDesc(Setmeal::getUpdateTime);
    
            List<Setmeal> setmealList = setmealService.list(wrapper);
            return R.success(setmealList);
        }
    

    三、结尾

    以上即为Redis-Spring Cache的基础内容,感谢阅读。

    相关文章

      网友评论

          本文标题:Redis-Spring Cache

          本文链接:https://www.haomeiwen.com/subject/ygmqyrtx.html