Can I set a TTL for @Cacheable

spring cache ttl
cacheable default ttl
spring boot redis cache ttl
spring cache refresh time
spring boot caffeine cache ttl
cacheable set ttl
redis cacheable ttl
spring set cache time

I am trying out the @Cacheable annotation support for Spring 3.1 and wondering if there is any way to make the cached data clear out after a time by setting a TTL? Right now from what I can see I need to clear it out myself by using the @CacheEvict, and by using that together with @Scheduled I can make a TTL implementation myself but it seems a bit much for such a simple task?

See http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#cache-specific-config:

How can I set the TTL/TTI/Eviction policy/XXX feature?

Directly through your cache provider. The cache abstraction is... well, an abstraction not a cache implementation

So, if you use EHCache, use EHCache's configuration to configure the TTL.

You could also use Guava's CacheBuilder to build a cache, and pass this cache's ConcurrentMap view to the setStore method of the ConcurrentMapCacheFactoryBean.

Can I set a TTL for @Cacheable, How can I set the TTL/TTI/Eviction policy/XXX feature? Directly through your cache provider. The cache abstraction is… well, an abstraction not  The cache abstraction is… well, an abstraction not a cache implementation So, if you use EHCache, use EHCache’s configuration to configure the TTL. You could also use Guava’s CacheBuilder to build a cache, and pass this cache’s ConcurrentMap view to the setStore method of the ConcurrentMapCacheFactoryBean.

Spring 3.1 and Guava 1.13.1:

@EnableCaching
@Configuration
public class CacheConfiguration implements CachingConfigurer {

    @Override
    public CacheManager cacheManager() {
        ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager() {

            @Override
            protected Cache createConcurrentMapCache(final String name) {
                return new ConcurrentMapCache(name,
                    CacheBuilder.newBuilder().expireAfterWrite(30, TimeUnit.MINUTES).maximumSize(100).build().asMap(), false);
            }
        };

        return cacheManager;
    }

    @Override
    public KeyGenerator keyGenerator() {
        return new DefaultKeyGenerator();
    }

}

Setting TTL for @Cacheable – Spring, Today I was asked to set the expiry time of cache for some of the keys Since Spring does not provide any configurable option to achieve it,  IMap::put(Key, Value, TTL, TimeUnit) But this has nothing to do with spring. With Spring means you can do the following: @Cacheable(name="floatingRates") List<Rate> floatingRates; @Cacheable(name="fixedRates") List<Rate> fixedRates; and then define TTL for each.

Here is a full example of setting up Guava Cache in Spring. I used Guava over Ehcache because it's a bit lighter weight and the config seemed more straight forward to me.

Import Maven Dependencies

Add these dependencies to your maven pom file and run clean and packages. These files are the Guava dep and Spring helper methods for use in the CacheBuilder.

    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>18.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>4.1.7.RELEASE</version>
    </dependency>

Configure the Cache

You need to create a CacheConfig file to configure the cache using Java config.

@Configuration
@EnableCaching
public class CacheConfig {

   public final static String CACHE_ONE = "cacheOne";
   public final static String CACHE_TWO = "cacheTwo";

   @Bean
   public Cache cacheOne() {
      return new GuavaCache(CACHE_ONE, CacheBuilder.newBuilder()
            .expireAfterWrite(60, TimeUnit.MINUTES)
            .build());
   }

   @Bean
   public Cache cacheTwo() {
      return new GuavaCache(CACHE_TWO, CacheBuilder.newBuilder()
            .expireAfterWrite(60, TimeUnit.SECONDS)
            .build());
   }
}

Annotate the method to be cached

Add the @Cacheable annotation and pass in the cache name.

@Service
public class CachedService extends WebServiceGatewaySupport implements CachedService {

    @Inject
    private RestTemplate restTemplate;


    @Cacheable(CacheConfig.CACHE_ONE)
    public String getCached() {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> reqEntity = new HttpEntity<>("url", headers);

        ResponseEntity<String> response;

        String url = "url";
        response = restTemplate.exchange(
                url,
                HttpMethod.GET, reqEntity, String.class);

        return response.getBody();
    }
}

You can see a more complete example here with annotated screenshots: Guava Cache in Spring

Multiple TTL caches in Spring Boot, But cache Time to Live can be achieved with timeout setup on Caffeine cache implementation. Learn by example how to configure TTL caches  If you have limited cache names, you can setting TTL for each cache name by configuring CacheManager bean. It would be great if SDR allows config TTL as property of @Cacheable – Mạnh Quyết Nguyễn Jun 17 '19 at 2:18

I use life hacking like this

@Configuration
@EnableCaching
@EnableScheduling
public class CachingConfig {
    public static final String GAMES = "GAMES";
    @Bean
    public CacheManager cacheManager() {
        ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager(GAMES);

        return cacheManager;
    }

@CacheEvict(allEntries = true, value = {GAMES})
@Scheduled(fixedDelay = 10 * 60 * 1000 ,  initialDelay = 500)
public void reportCacheEvict() {
    System.out.println("Flush Cache " + dateFormat.format(new Date()));
}

Configuring Multiple TTL Caches in Spring Boot dinamically, Now, what we need to do is externalize the settings of the caches… but what if we want to introduce a new cache later on, will we need to come back to this First, we'll set up the configuration class to be filled up with external  Any data stored in a cache requires a key for its speedy retrieval. Spring, by default, creates caching keys using the annotated method’s signature as demonstrated by the code above. You can override this using @Cacheable’s second parameter: key. To define a custom key you use a SpEL expression.

Springboot 1.3.8

import java.util.concurrent.TimeUnit;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.guava.GuavaCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.google.common.cache.CacheBuilder;

@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {

@Override
@Bean
public CacheManager cacheManager() {
    GuavaCacheManager cacheManager = new GuavaCacheManager();
    return cacheManager;
}

@Bean
public CacheManager timeoutCacheManager() {
    GuavaCacheManager cacheManager = new GuavaCacheManager();
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder()
            .maximumSize(100)
            .expireAfterWrite(5, TimeUnit.SECONDS);
    cacheManager.setCacheBuilder(cacheBuilder);
    return cacheManager;
}

}

and

@Cacheable(value="A", cacheManager="timeoutCacheManager")
public Object getA(){
...
}

What is Time to Live (TTL) | TTL Best Practices | CDN Guide, Learn about TTL best practices and how CDNs can manage your TTL policy. TTL is set via HTTP headers, such as the Cache-Control header, and is  While troubleshooting connectivity issues, we may need to change the default TTL value set on the Ping packets. It is because the TTL value (Time To Live) tells the life span of the ping packets. In simple words, it is the number of hops they can cross. When it reaches the hop count set by TTL, it expires.

Allow dynamic ttl in @Cacheable · Issue #23684 · spring-projects , I have a requirement to set TTL dynamically using the @Cacheable annotation. Of course, it can be handled with a custom RedisCacheWriter or  Like most Spring Getting Started guides, you can start from scratch and complete each step or you can bypass basic setup steps that are already familiar to you. Either way, you end up with working code.

30. Cache Abstraction, If you want to keep using the previous key strategy, you can configure the deprecated org.springframework.cache.interceptor.DefaultKeyGenerator class or create  You can usually set this to a 12 hour or 1 day TTL. If you want to ensure faster propagation times in the event of an emergency, a 1 to 4 hour TTL is a good compromise. TXT Records – Most commonly used for SPF or DKIM records. Usually safe to set in the 1 hour to 12 hour range since they rarely change.

Spring cache annotations: some tips & tricks, But you can put them to some good use. Consider the following traditional service/repository hierarchy: class UserService { @Cacheable(value =  It is possible to raise and lower the TTL (Time To Live) value for your domains hosted at (mt) Media Temple. TTL is the value that determines how long your current DNS settings are cached with Internet Service Providers. What that means for you: In practice, if your Internet Service Provider has the

Comments
  • For Spring 4.1 extend CachingConfigurerSupport and only overwrite cacheManager().
  • Note: Guava cache is now deprecated in Spring 5 (stackoverflow.com/questions/44175085/…)
  • Are you calling reportCacheEvict method from anywhere. How the cacheEvict happening??
  • Get it. We are not calling this method from anywhere. Its called after fixedDelay time interval. Thanks for the hint.
  • Clearing the entire cache on a schedule can be a handy hack to get things working, but this method can't be used to give items a TTL. Even the condition value can only declare whether to delete the entire cache. Underlying this is the fact that ConcurrentMapCache stores objects without any timestamp, so there's no way to evaluate a TTL as-is.
  • is code seat-of-the-pants (this method was scribbled down :) ).
  • Nice and clean approach
  • Amazing! This was exactly what i was looking for
  • question is for spring @Cacheable annotation