Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

refreshAfterWrite requires a LoadingCache in spring boot caffeine application

I am trying to write an application to cache which reloads every few seconds. I decided to use spring boot Caffeine and got a sample application too. But when I am specifying refreshAfterWrite property, it throws exception: refreshAfterWrite requires a LoadingCache

spring:
    cache:
        cache-names: instruments, directory
        caffeine:
            spec: maximumSize=500, expireAfterAccess=30s, refreshAfterWrite=30s

To resolve this I provide Loading Cache Bean, but cache stopped working altogether:

@Bean
    public CacheLoader<Object, Object> cacheLoader() {
        return string -> {
            System.out.println("string = " + string);
            return string;
        };
    }

    @Bean
    public LoadingCache<Object, Object> loader(CacheLoader<Object, Object> cacheLoader) {
        return Caffeine.newBuilder()
                .refreshAfterWrite(1, TimeUnit.SECONDS)
                .build(cacheLoader);
    }

Do we have some simple way for reload to work?

like image 815
krmanish007 Avatar asked Aug 10 '26 21:08

krmanish007


1 Answers

To conclude here, using the LoadingCache feature of Caffeine with Spring's cache abstraction does not make much sense since they share a lot of features.

@Cacheable typically provide a way to mark a method to retrieve an element that is not present in the cache yet. LoadingCache achieves the same scenario, requiring you to provide a handle that can load a missing element by id.

If you absolutely need to use a LoadingCache, I'd inject the Cache in your code and interact with it programmatically.

like image 125
Stephane Nicoll Avatar answered Aug 14 '26 10:08

Stephane Nicoll