Skip to content

How to customize expireAfterWrite for concrete cache if I use cacheBuilder?

Based on this answer I try to use customized expireAfterWrite for “customCache”

So my config look like this:

@Configuration
@EnableCaching
public class CaffeineCacheConfig {

    ...

    @Bean
    public CaffeineCacheManager cacheManager(Caffeine<Object, Object> caffeineCacheBuilder) {
        CaffeineCacheManager result = new CaffeineCacheManager();
        result.setCaffeine(caffeineCacheBuilder);
        return result;
    }

    @Bean
    public Caffeine<Object, Object> caffeineCacheBuilder() {
        return Caffeine.newBuilder()
                .maximumSize(10000)
                .expireAfterWrite(60, TimeUnit.SECONDS)
                .recordStats();
    }

    @Bean
    public CaffeineCache customCache() {
        return new CaffeineCache("customCache",
                Caffeine.newBuilder()
                        .maximumSize(10000)
                        .expireAfterWrite(60, TimeUnit.MINUTES)
                        .recordStats()
                        .build());
    }
}

Then in codeBase I use:

“customCache”

Cache cache = cacheManager.getCache("customCache")
String result = cache.get("myKey", () -> "cachedValue")

And based on my experiments it keeps values on cache pnly 60 seconds by I expect 60 minutes.

How to achieve desired result ?

Answer

I think a better way to do this is as follows.

@Configuration
@EnableCaching
public class CaffeineCacheConfig
{
    @Bean
    public CacheManager cacheManager(
            @Qualifier("oneMinuteCache") final Cache<Object, Object> oneMinuteCache,
            @Qualifier("oneHourCache") final Cache<Object, Object> oneHourCache)
    {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        cacheManager.setCaches(Arrays.asList(
                new CaffeineCache("oneMinuteCache", oneMinuteCache),
                new CaffeineCache("oneHourCache", oneHourCache)));
        return cacheManager;
    }

    @Bean
    public Cache<Object, Object> oneMinuteCache()
    {
        return Caffeine.newBuilder()
                .maximumSize(10000)
                .expireAfterWrite(1, TimeUnit.MINUTES)
                .recordStats()
                .build();
    }

    @Bean
    public Cache<Object, Object> oneHourCache()
    {
        return Caffeine.newBuilder()
                .maximumSize(10000)
                .expireAfterWrite(1, TimeUnit.HOURS)
                .recordStats()
                .build();
    }
}