1

We are using Spring cache for Caching few elements. So whenever user requests same key of element, it goes to cache and check if it is available or not. If it is available it fetches from cache otherwise it executes the method. But before all this I want to implement one more functionality in my cache.

Requirement : On hourly basis my spring cache will check, if any element in the cache exists for more than an hour, it will remove it.

I searched on google but did not find any satisfactory link. Can someone help me or provide me a link for same ?

1 Answers1

1

You need to set the time to live(TTL) for your cache. How you do this depends on your cash provider. A couple examples can be found here:

Can I set a TTL for @Cacheable

@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();
    }

}
mad_fox
  • 3,030
  • 5
  • 31
  • 43
  • Thanks a lot buddy. So I was using SImpleCacheManager and setting ConcurrentMapCache inside it. I was only putting name of the cache in the COncurrentMapCache with default setting. But chaing to the above setting CacheBuilder.newBuilder().expireAfterWrite(30, TimeUnit.MINUTES). working well. –  Oct 02 '17 at 19:32