I have a list of jobs that need to be cached (by id). In some cases however, it is important to have the latest version of a job, and the cache needs to be bypassed (force update). When that happens, the newly fetched job should be placed in the cache.
I implemented it like this:
@Cacheable(cacheNames = "jobs", key = "#id", condition = "!#forceRefresh", sync = true)
public Job getJob(String id, boolean forceRefresh) {
// expensive fetch
}
Desired behavior:
getJob("123", false)
=> job v1 is returned (fetched from the cache if present)getJob("123", true)
=> job v2 is returned (updated version, fetched from db)getJob("123", false)
=> job v2 is returned (updated version, fetched from cache)
In reality, the last call getJob("123", false)
returns job v1, the stale version. It seems like the second call (forced update) does not update the value in the cache.
How can I achieve the correct behavior here?
Cache config (using Caffeine):
CaffeineCache jobs = new CaffeineCache("jobs", Caffeine.newBuilder()
.expireAfterWrite(1, TimeUnit.MINUTES)
.maximumSize(100)
.build());