2017-04-21 14:19:33
0
I need some basic understanding of spring cache function. I want to build a cache warmer and resyncer as scheduled bean, in order to renew the cache on demand, when changes happen.
Let say, I have an AccountClient with a getAccount(String id), which fetches an Account from a very slow API. So basically I can do
@Cachable(cacheNames = "account", key = "#id", sync = true)
public Account getAccount(String id) {
//...
}
and everything works fine. Now I want to warm up the cache, and furthermore, I got a getNewOrChangedAccounts(), which retrieves IDs of changed accounts from my slow datastore.
so here is my approach:
public class AccountCacheManager {
//...
@Scheduled(initialDelay = 3000L, fixedRate = 10000L)
public void sync() {
List modifiedAccounts = accountClient.getNewOrChangedAccounts();
modifiedAccounts.getAccounts().parallelStream()
.forEach(account -> {
//delete old entry
evictAccount(account.getId());
//store new entry
putAccount(account.getId());
});
log.info("finished resync");
}
@CacheEvict(cacheNames = "account", key = "#id")
public void evictAccount(String id) {
log.debug("evicting account {}", id);
}
@CachePut(cacheNames = "account", key = "#id")
public void putAccount(String id) {
log.debug("storing account {}", id);
accountService.getAccount(id);
}
}
So I can proof, this process gets started and does something. However, when I hit my API, I see the first hit going to the slow backend, even if my sync goes over all entries from the backend.
I feel I misunderstood some details of spring caching API, so how can I achieve this?