问题
I have a very small table which is not updated frequently. I want to add this to cache such that it updates every day. I am using spring and caffeine to implement this. I able to load a startup but don't how to refresh it. Please help.
@Bean
public CacheManager cacheManager() {
SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
Cache stringStringCache = new CaffeineCache("name", Caffeine.newBuilder()
.recordStats()
.maximumSize(100)
.expireAfterWrite(1, TimeUnit.DAYS)
.build());
simpleCacheManager.setCaches(Collections.singleton(stringStringCache));
return simpleCacheManager;
}
I can simply fetch all records from repository and put that in the cache using cache.put(). But how i refresh it again from table after specified time interval.
回答1:
found the answer.
It loads the table on first call.
After that we just to read from cache from subsequent calls
@Cacheable("name")
@Override
public Map<String,String> findNameById() {
log.info("db call");
return IteratorUtils.toList(bookRepository
.findAll()
.iterator())
.stream()
.collect(Collectors.toMap(Book::getId,Book::getName));
}
来源:https://stackoverflow.com/questions/53030289/how-to-add-entire-table-to-cache-in-spring