How to add entire table to cache in spring

我的未来我决定 提交于 2019-12-08 04:23:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!