其他分享
首页 > 其他分享> > SpringCache框架常用注解

SpringCache框架常用注解

作者:互联网

目录

1.Cacheable使用缓存

2.CacheManager配置过期时间

// 配置文件 
/**
  * RedisCacheManager1小时过期
  * @param redisConnectionFactory
  * @return
  */
@Bean
@Primary
public RedisCacheManager cacheManager1Hour(RedisConnectionFactory redisConnectionFactory) {
    RedisCacheConfiguration config = instanceConfig(3600L);
    return RedisCacheManager.builder(redisConnectionFactory)
        .cacheDefaults(config)
        .transactionAware().build();
}

/**
  * RedisCacheManager1天过期
  * @param redisConnectionFactory
  * @return
  */
@Bean
public RedisCacheManager cacheManager1Day(RedisConnectionFactory redisConnectionFactory) {
    RedisCacheConfiguration config = instanceConfig(3600 * 24L);
    return RedisCacheManager.builder(redisConnectionFactory)
        .cacheDefaults(config)
        .transactionAware().build();
}

/**
  * 序列化配置
  * @param ttl
  * @return
  */
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));
}

// 使用
@Cacheable(value = {"product"}, key = "#root.methodName +':'+ #id", cacheManager = "cacheManager1Day")

3.KeyGenerator自定义缓存Key

4.CachePut更新使用缓存

// 使用场景:尽量保持修改和查询使用同一个key
@RequestMapping("update")
@CachePut(value = {"product"}, key = "#product.id")
public Product update(@RequestBody Product product){
    int i = this.productService.update(product);
    if (i > 0){
        return product;
    }
    return null;
}

@RequestMapping("selectById")
@Cacheable(value = {"product"}, key = "#id")
public Product selectById(Integer id){
    return this.productService.selectById(id);
}

5.CacheEvict删除缓存

6.Caching多注解组合使用缓存

@Caching(
    cacheable = {
    	@Cacheable(value = {"product"}, key = "#id")
    },
    put = {
    	@CachePut(value = {"product"}, key = "#id")
    }
)

标签:product,缓存,return,框架,value,SpringCache,key,注解,id
来源: https://www.cnblogs.com/Gen2021/p/15040880.html