2

Spring Cache @Cacheable本身不支持key expiration的设置,以下代码可自定义实现Spring Cache的expiration,针对Redis、SpringBoot2.0。

直接上代码:

@Service
@Configuration
public class CustomCacheMng{
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    // 指明自定义cacheManager的bean name
    @Cacheable(value = "test",key = "'obj1'",cacheManager = "customCacheManager")
    public User cache1(){
        User user = new User().setId(1);
        logger.info("1");
        return user;
    }

    @Cacheable(value = "test",key = "'obj2'")
    public User cache2(){
        User user = new User().setId(1);
        logger.info("2");
        return user;
    }
    
    // 自定义的cacheManager,实现存活2天
    @Bean(name = "customCacheManager")
    public CacheManager cacheManager(
            RedisTemplate<?, ?> redisTemplate) {
        RedisCacheWriter writer = RedisCacheWriter.lockingRedisCacheWriter(redisTemplate.getConnectionFactory());
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofDays(2));
        return new RedisCacheManager(writer, config);
    }
    
    // 提供默认的cacheManager,应用于全局
    @Bean
    @Primary
    public CacheManager defaultCacheManager(
            RedisTemplate<?, ?> redisTemplate) {
        RedisCacheWriter writer = RedisCacheWriter.lockingRedisCacheWriter(redisTemplate.getConnectionFactory());
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        return new RedisCacheManager(writer, config);
    }
}

水木酱
398 声望7 粉丝

戒骄戒躁,勿忘初心