SpringCache学习笔记

核心

  • Cache接口,提供缓存操作API
  • CacheManager管理各类缓存

使用条件

依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
复制代码

配置文件

spring:
    cache:
        #指定缓存类型
        type:redis
复制代码

启动类注解

@EnableCaching
复制代码

Cache使用方法

注解Cacheable

  • 可标注类也可以标注方法
  • 缓存标注对象的返回结果,标注在方法上缓存该方法的返回值,标注在类上缓存该类所有方法的返回值
  • value缓存名称可有多个
  • key 缓存的key规则,可以⽤springEL表达式,默认是⽅法参数组合
  • condition 缓存条件,使⽤springEL编写,返回true才缓存
@Cacheable(value = {"redis中缓存的名称"},key = "#root.methodName")
//root.methodName就只用方法名作为唯一Key
//root.args[0]可以用参数名作为key,0代表第一个入参,以此类推
//#参数名:可以直接获取该参数
public ProductDO findById(int id)
复制代码

CacheManager使用

  • 设置Redis过期时间以及序列化
@Bean//可根据自己需要添加自己所需的过期时间方法
    public RedisCacheManager cacheManager1Day(RedisConnectionFactory connectionFactory) {
        RedisCacheConfiguration config = instanceConfig(3600 * 24L);
        return RedisCacheManager.builder(connectionFactory).
                cacheDefaults(config).
                transactionAware().
                build();
    }
    private RedisCacheConfiguration instanceConfig(Long ttl) {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.registerModule(new JavaTimeModule());
        // 去掉各种@JsonSerialize注解的解析
        objectMapper.configure(MapperFeature.USE_ANNOTATIONS, false);
        // 只针对⾮空的值进⾏序列化
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        // 将类型序列化到属性json字符串中
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
                ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);

        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        
        return RedisCacheConfiguration.defaultCacheConfig().
                entryTtl(Duration.ofSeconds(ttl)).
                disableCachingNullValues().
                serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer));
    }
复制代码

自定义key:KeyGenerator

    @Bean
    public KeyGenerator springCacheCustomKeyGenerator(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object o, Method method, Object... objects) {
                //自定义的命名方法
            }
        }
    }
复制代码
  • 使用CacheManager和KeyGenerator

@Cacheable(value = {"product"},keyGenerator = "springCacheCustomKeyGenerator",cacheManager = "cacheManager1Min")

CachePut

  • 用于数据库更新数据时,实时更新redis中缓存数据,每次请求都会触发
  • value缓存名称,可以有多个
  • key可用SpringEL表达式,不能使用KeyGenerator
  • condition缓存条件,使用SpringEL编写,返回true才缓存
//key通过入参productDO的属性id来保证和redis中key一致
@CachePut(value = {"product"},key = "#productDO.id",cacheManager = "cacheManager1Min")
复制代码

CacheEvict

  • 用于从缓存中删除数据
  • 当数据库数据被删除时,同时删除redis中缓存的数据
  • key可用SpringEL表达式,不能使用KeyGenerator
  • beforeInvocation = false
    • 清除缓存是否在方法是之前执行,默认是方法之后执行
    • 如果出现异常,缓存则不清除
  • beforeInvocation = true
    • 代表清除缓存是在方法执行之前,不管是否异常,都清除
@CacheEvict(value = {"product"},beforeInvocation = false)
复制代码

Caching

  • 多注解组合,在Caching注解中可以嵌套多个Cacheable、CachePut、CacheEvict注解
//嵌套的注解对应的redis中的key会执行相关操作
@Caching(
            cacheable = {
                    @Cacheable(value = {}...),
                    @Cacheable(value = ...)
            },
            put = {
                    @CachePut(...)
            }
    )
复制代码

sync属性

  • SpringCache的sync属性,true为开启锁,请求一个一个的解决,可以用来缓存击穿

@Cacheable(value = {"product"},key = "xxx",sync = true)

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享