Spring Cache:如何使用redis进行缓存数据?

简介

  Spring Cache是一个缓存框架,实现了基于注解的缓存功能。

  它提供了一层抽象,底层可以切换不同的cache实现,通过CacheManager接口统一不同的缓存技术。

  使用不同的缓存技术只要实现对应CacheManager的接口即可,若不指定,则使用内置的基于Map的缓存。

 

使用

  在springboot项目中的使用。

  一、导入依赖

        <!--缓存默认配置-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <!--Redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

  二、编写配置信息

spring:
  cache:
    redis:
      time-to-live: 1800000 #缓存生效时间,毫秒
  redis:
    host: localhost
    port: 6379
    password: lurenjia

  三、编写代码

    1、启动类上

//开启缓存注解功能
@EnableCaching

    2、查询数据方法上

    /**
     * CachePut:把方法返回值放入缓存中
     * value:缓存的分类
     * key:缓存的key
     */
    @CachePut(value = "userCache",key = "'user:'+#user.id")
    public User getById(User user){
        userService.getById(users);
        return user;
    }

    3、修改、删除数据的方法上

    /**
     * CacheEvict:把指定缓存数据从缓存中删除
     * value:缓存分类
     * key:缓存的key
     */
    @CacheEvict(value = "userCache",key = "'user:'+#id")
    public void updateUser(Long id){
        this.removeById(id);
    }

    //删除指定分类中的所有缓存
    @CacheEvict(value = "myCache", allEntries = true)

    //删除指定多个分类中的所有缓存
    @CacheEvict(value = {"category1Cache", "category2Cache"}, allEntries = true)

    //删除指定多个分类中的指定缓存
    @CacheEvict(value = {"category1Cache", "category2Cache"}, key = "{'key1', 'key2', 'key3'}")

 

    4、查询数据方法上

    /**
     * Cacheable:从缓存中取出指定数据,若数据不存在则执行方法,并把方法返回值写入缓存中
     * value:缓存分类
     * key:缓存key
     * condition:缓存条件,为true时才进行缓存,若不指定,则会缓存空数据。
     * unless:不缓存条件,为true时不进行缓存。
     */
    @Cacheable(value = "userCahce",key = "'user:'+#id",condition = "#result !=null",unless = "#result ==null")
    public Users getById(Long id){
        Users users = this.getById(id);
        return users;
    }

 

posted @ 2023-05-01 02:08  在博客做笔记的路人甲  阅读(205)  评论(0编辑  收藏  举报