Search code examples
springcachingcaffeine-cache

Refresh Caffeine cache


I want to create a cache instance in in Spring using Caffeine cache. I need the cache to refresh all the keys async, fetching the data from external services and when the data is ready, interchange the old values with the new values without any downtime. The problem seems to be solved using the refresh mechanism that the cache provides

 @Bean
 public AsyncLoadingCache<Object, Object> myCache() {
        return Caffeine.newBuilder()
                .maximumSize(cacheProperties.getProp())
                .refreshAfterWrite(5, TimeUnit.MINUTES)
                .recordStats()
                .buildAsync(key -> cacheInitializer.fetchCacheValues());
    }

In my case fetchCacheValues() is a bean service that makes external calls to other services, but the method is never called, despite the cache being initialised succesfully.

Am I missing something regarding the .refreshAfterWrite() behaviour? Some better alternatives? (I also tried doing it using a scheduled job and CachePut, but got some downtime when refreshing)


Solution

  • In Caffein refreshing of a key works a bit differently then eviction. In case of eviction the value is evicted just because the configured time elapsed. In case of refreshing it will be only marked as "ready for refresh". The actually refreshing will only be triggered when (and if) the value is fetched. In other words if the value is not fetched then your service will never run.

    Hope it helps.