SpringCache(通用缓存)

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


提示:以下是本篇文章正文内容,下面案例整理于黑马

一、了解

Spring Cache是Spring提供的通用缓存框架,它利用了AOP,实现了基于注解的缓存功能。使开发者不用关心底层使用了什么缓存框架,只需要简单地加一个注解,就能实现缓存功能了。

问题:使用Spring Cache缓存注解,那么数据到底缓存到哪里了?

  1. 如果没有配置其他缓存框架,默认情况下, SpringCache使用ConcurrentHashMap作为本地缓存存储数据。
  2. 如果要使用其它的缓存框架,我们只需要做简单的配置即可。至于如何配置,请往下看.
属性 作用 常用
@Cacheable 注解用于方法,方法的返回值会被缓存下来,调用时会先查询缓存,有:则返回,无:则查询数据库然后把结果缓存。
@CachePut 注解用于方法,会把方法的返回值put到缓存里面缓存起来,供其它地方使用。【只起添加作用】
@CacheEvit 注解用于方法,会清空指定缓存 。
@Caching 注解用于方法,可操作多个缓存

二、使用步骤

1. 不使用其他缓存

1. maven 坐标

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

2. 开启缓存

@SpringBootApplication
@EnableCaching // 开启springcache缓存
public class Application {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(Application.class,args);
    }
}

3. 配置注解

	 /**
     * @Cacheable
     * 
     * value:可以理解名称空间(分组)
     * key: 支持spring EL表达式
     */
    @Cacheable(value="user" , key = "'user_' + #userID") // 添加缓存,并从缓存中获取
    @GetMapping
    public ResponseEntity findUserInfoById(Long userID) {
    
    
        UserInfoVo userInfo = userService.findUserInfoById(userID);
        return ResponseEntity.ok(userInfo); //正常返回状态码200
    }


 	/**
     * @CachePut
     *
     * value:可以理解名称空间(分组)
     * key: 支持spring EL表达式
     */
    @CachePut(value="user" , key = "'user_' + #userID") // 添加缓存,并从缓存中获取
    @GetMapping
    public ResponseEntity findUserInfoById(Long userID) {
    
    
        UserInfoVo userInfo = userService.findUserInfoById(userID);
        return ResponseEntity.ok(userInfo); //正常返回状态码200
    }


	 /**
     * @CacheEvict
     * 
     * value:可以理解名称空间(分组)
     * key: 支持spring EL表达式
     */
    @CacheEvict(value="user" , key = "'user_' + #userInfo.getId()") //清空缓存
    @PutMapping
    public ResponseEntity updateUserInfoById(@RequestBody UserInfo userInfo) {
    
    
        userService.updateUserInfoById(userInfo);
        return ResponseEntity.ok(""); //正常返回状态码200
    }


	/**
     * @Caching
     *
     * value:可以理解名称空间(分组)
     * key: 支持spring EL表达式
     */
    @Caching(
            evict = {
    
    
                    @CacheEvict(value="user" , key = "#userInfo.getId()"),
                    @CacheEvict(value="role" , key = "#userInfo.getId()")
            }
    )//清空多个缓存
    @PutMapping
    public ResponseEntity updateUserInfoById(@RequestBody UserInfo userInfo) {
    
    
        userService.updateUserInfoById(userInfo);
        return ResponseEntity.ok(""); //正常返回状态码200
    }

2. 使用其他缓存框架(redis)

1.maven坐标

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

2.application.yml配置

spring:
  redis:  #redis配置
    port: 6379
    host: 192.168.136.160

当配置好Redis,使用Spring Cache就不会在本地缓存存储数据,而是存储在了Redis中。(不使用默认配置而使用我们配置好的)

3. 设置Spring Cache缓存失效时间

import com.google.common.collect.ImmutableMap;
import org.springframework.boot.autoconfigure.cache.RedisCacheManagerBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;

import java.time.Duration;
import java.util.Map;

@Configuration
public class RedisCacheConfig {
    
    

    //设置失效map
    private static final Map<String, Duration> cacheMap;

    static {
    
    
        //将Spring Cache需要失效的命名空间添加到map
        cacheMap = ImmutableMap.<String, Duration>builder().put("user", Duration.ofSeconds(30L)).build();
        cacheMap.put("role", Duration.ofSeconds(30L));
    }

    //配置RedisCacheManagerBuilderCustomizer对象
    @Bean
    public RedisCacheManagerBuilderCustomizer redisCacheManagerBuilderCustomizer() {
    
    
        return (builder) -> {
    
    
            //根据不同的cachename设置不同的失效时间
            for (Map.Entry<String, Duration> entry : cacheMap.entrySet()) {
    
    
                builder.withCacheConfiguration(entry.getKey(),
                        RedisCacheConfiguration.defaultCacheConfig().entryTtl(entry.getValue()));
            }
        };
    }
}

猜你喜欢

转载自blog.csdn.net/packge/article/details/127440900