How to add entire table to cache in spring
Asked Answered
N

1

1

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.

Nightjar answered 28/10, 2018 at 10:0 Comment(2)
show your code and what is not workingParthen
@user7294900 added in desciptionNightjar
N
0

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));
}
Nightjar answered 29/10, 2018 at 15:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.