Spring @Cacheable default TTL

Viewed 52912

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 boot app that uses @Cacheable without explicitly stating a cache manager and ttl. I will be changing it to be explicit.

But I am not able to find out what are the defaults when there is nothing explicit.

I did look at the docs but found nothing there

5 Answers

With spring boot, I was able to achieve success with this:

First, you need to add spring-boot-starter-data-redis artifact to your POM file.

<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-data-redis</artifactId> 
</dependency>

After this, you need to add the required the following configurations in your application.properties files:

#------ Redis Properties -------------
spring.cache.type=redis
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.cache.redis.time-to-live=600000

The property to set is spring.cache.redis.time-to-live (value is in milliseconds. 10 mins was set in this case). With this, @Cacheable works with the set default TTL.

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<String, String> redisTemplate(RedisConnectionFactory cf) {
    RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
    redisTemplate.setConnectionFactory(cf);
    return redisTemplate;
}

@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
    RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
    cacheManager.setDefaultExpiration(DEFAULT_TTL);
    return cacheManager;
}
}

pom dependency :

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>1.4.7.RELEASE</version>
</dependency>

The cache will never expire by default. If we need to set expire time we have to use the below properites key. If the value will is the 10000ms, the cache will expire after 1 minute.

# Entry expiration. By default, the entries never expire.
spring.cache.redis.time-to-live=10000ms
Related