如何在Spring中将整个表添加到缓存 [英] How to add entire table to cache in spring

查看:124
本文介绍了如何在Spring中将整个表添加到缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很小的表,它不经常更新. 我想将其添加到缓存中,以便每天更新. 我正在使用spring和caffeine来实现这一点. 我可以加载启动程序,但不刷新它. 请帮忙.

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;
}

我可以简单地从存储库中获取所有记录,然后使用 cache.put(). 但是如何在指定的时间间隔后再次从表中刷新它.

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.

推荐答案

找到了答案.
它在第一次调用时加载表.
之后,我们只是从后续调用的缓存中读取

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));
}

这篇关于如何在Spring中将整个表添加到缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆