Spring Cache redis自定义缓存时间&修改默认缓存key拼接方式

200 阅读1分钟

Spring Cache redis自定义缓存时间&修改默认缓存key拼接方式

spring cache 基础文档

spring文档

相关注解

  • @Cacheable: Triggers cache population.
  • @CacheEvict: Triggers cache eviction.
  • @CachePut: Updates the cache without interfering with the method execution.
  • @Caching: Regroups multiple cache operations to be applied on a method.
  • @CacheConfig: Shares some common cache-related settings at class-level.

自定义RedisCacheManager 实现缓存时间&key前缀

public class CustomRedisCacheManager extends RedisCacheManager{
    public CustomRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration, DEFAULT_ALLOW_RUNTIME_CACHE_CREATION);
    }

    @Override
    protected org.springframework.data.redis.cache.RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfiguration) {
        //名称中存在##标记进行到期时间配置
        if (!name.isEmpty() && name.contains("##")) {
            String[] SPEL = name.split("##");
            if (SPEL != null && SPEL.length > 1) {
                //配置缓存到期时间
                try {
                    int cycle = Integer.parseInt(SPEL[1]);
                    return super.createRedisCache(SPEL[0], cacheConfiguration.entryTtl(Duration.ofSeconds(cycle)));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }
        return super.createRedisCache(name, cacheConfiguration);
    }
}

@Configuration
@EnableCaching
public class RedisConfiguration {
@Bean
public RedisCacheManager redisCacheManager(RedisTemplate redisTemplate) {
    RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());
    RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer()))
            .entryTtl(Duration.ofSeconds(3600))//默认缓存一个小时
            .prefixCacheNameWith("test");//key默认拼上test前缀
    return new CustomRedisCacheManager(redisCacheWriter, redisCacheConfiguration);
}
}
//key1缓存60s配置示例
@Cacheable(value="key1##60",key="testa")
完整key: testkey1::testa