articleList

11-SpringCache 常用注解介绍+框架案例实战

2025/03/16 posted in  Redis
Tags: 

第 1 集 SpringCache 框架常用之 Cacheable 实战

简介:SpringCache 框架常用注解 Cacheable

  • Cacheable 注解

    • 标记在一个方法上,也可以标记在一个类上
    • 缓存标注对象的返回结果,标注在方法上缓存该方法的返回值,标注在类上缓存该类所有的方法返回值
    • value 缓存名称,可以有多个
    • key 缓存的 key 规则,可以用 springEL 表达式,默认是方法参数组合
    • condition 缓存条件,使用 springEL 编写,返回 true 才缓存
  • 案例

    //对象
    @Cacheable(value = {"product"}, key="#root.methodName")
    ​
    //分页
    @Cacheable(value = {"product_page"},key="#root.methodName + #page+'_'+#size")
    
  • spEL 表达式

    • methodName 当前被调用的方法名

      • root.methodname
    • args 当前被调用的方法的参数列表

      • root.args[0]
    • result 方法执行后的返回值

      • result

第 2 集 SpringCache 框架自定义 CacheManager 配置和过期时间

简介:SpringCache 框架自定义 CacheManager 配置和过期时间

  • 修改 redis 缓存序列化器和配置 manager 过期时间

    @Bean
    @Primary
    public RedisCacheManager cacheManager1Hour(RedisConnectionFactory connectionFactory) {
        RedisCacheConfiguration config = instanceConfig(3600L);
        return RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(config)
                .transactionAware()
                .build();
    }
    ​
    @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));
    }
    

第 3 集 SpringCache 框架自定义缓存 KeyGenerator

简介:SpringCache 框架自定义缓存 KeyGenerator

  • Key 规则定义麻烦,支持自定规则

  • 实战

    @Bean
    public KeyGenerator springCacheDefaultKeyGenerator(){
    ​
        return new KeyGenerator() {
            @Override
            public Object generate(Object o, Method method, Object... objects) {
                return o.getClass().getSimpleName() + "_"
                        + method.getName() + "_"
                        + StringUtils.arrayToDelimitedString(objects, "_");
            }
        };
    ​
    }
    
  • 使用

    • key 属性和 keyGenerator 属性只能二选一

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

第 4 集 SpringCache 框架常用之 CachePut 实战

简介:SpringCache 框架常用注解 CachePut

  • CachePut

    • 根据方法的请求参数对其结果进行缓存,每次都会触发真实方法的调用
    • value 缓存名称,可以有多个
    • key 缓存的 key 规则,可以用 springEL 表达式,默认是方法参数组合
    • condition 缓存条件,使用 springEL 编写,返回 true 才缓存
  • 案例实战

    @CachePut(value = {"product"},key = "#productDO.id")
    

第 5 集 SpringCache 框架常用之 CacheEvict 实战

简介:SpringCache 框架常用注解 CacheEvict

  • CacheEvict

    • 从缓存中移除相应数据, 触发缓存删除的操作

    • value 缓存名称,可以有多个

    • key 缓存的 key 规则,可以用 springEL 表达式,默认是方法参数组合

    • beforeInvocation = false

      • 缓存的清除是否在方法之前执行 ,默认代表缓存清除操作是在方法执行之后执行;
      • 如果出现异常缓存就不会清除
    • beforeInvocation = true

      • 代表清除缓存操作是在方法运行之前执行,无论方法是否出现异常,缓存都清除
  • 案例实战

    @CacheEvict(value = {"product"},key = "#root.args[0]")
    

第 6 集 SpringCache 框架常用之多注解组合 Caching 实战

简介:SpringCache 框架多注解组合 Caching

  • Caching

    • 组合多个 Cache 注解使用
    • 允许在同一方法上使用多个嵌套的@Cacheable、@CachePut 和@CacheEvict 注释
  • 实战

    @Caching(
        cacheable = {
            @Cacheable(value = "product",keyGenerator = "xdclassKeyGenerator")
        },
        put = {
            @CachePut(value = "product",key = "#id"),
            @CachePut(value = "product",key = "'stock:'+#id")
        }
    )