Spring @Cacheable default TTL

后端 未结 5 837
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-14 14:09

I generally use the @Cacheable with a cache config in my spring-boot app and set specific TTL (time to live) for each cache.

I recently inherited a spring b

5条回答
  •  情话喂你
    2021-02-14 14:50

    Actually, there is a better way than using @schedule, by extending the cacheManager which defines the ttl: Here is an example :

    @Configuration
    public class CacheConfig extends CachingConfigurerSupport {
    
    @Value( "${redis.hostname}" )
    private String redisHostName;
    
    @Value( "${redis.port}" )
    private int redisPort;
    
    @Value("#{${redis.ttl}}")
    private int DEFAULT_TTL;
    
    
    @Bean
    public JedisConnectionFactory redisConnectionFactory() {
        JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();
        redisConnectionFactory.setHostName(redisHostName);
        redisConnectionFactory.setPort(redisPort);
        return redisConnectionFactory;
    }
    
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory cf) {
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(cf);
        return redisTemplate;
    }
    
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        cacheManager.setDefaultExpiration(DEFAULT_TTL);
        return cacheManager;
    }
    }
    

    pom dependency :

    
        org.springframework.boot
        spring-boot-starter-data-redis
        1.4.7.RELEASE
    
    

提交回复
热议问题