如何在春季启动时加载@Cache? [英] How to load @Cache on startup in spring?

查看:91
本文介绍了如何在春季启动时加载@Cache?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用spring-cache来改进数据库查询,其工作正常如下:

I'm using spring-cache to improve database queries, which works fine as follows:

@Bean
public CacheManager cacheManager() {
    return new ConcurrentMapCacheManager("books");
}

@Cacheable("books")
public Book getByIsbn(String isbn) {
    return dao.findByIsbn(isbn);
}

但是现在我想在启动时预先填充完整的书籍缓存。这意味着我想调用 dao.findAll()并将所有值放入缓存中。这个例程不仅要定期安排。

But now I want to prepopulate the full book-cache on startup. Which means I want to call dao.findAll() and put all values into the cache. This routine shall than only be scheduled periodically.

但是如何在使用 @Cacheable 时显式填充缓存?

But how can I explicit populate a cache when using @Cacheable?

推荐答案

只需像以前一样使用缓存,添加一个调度程序来更新缓存,代码片段在下面。

Just use the cache as before, add a scheduler to update cache, code snippet is below.

@Service
public class CacheScheduler {
    @Autowired
    BookDao bookDao;
    @Autowired
    CacheManager cacheManager;

    @PostConstruct
    public void init() {
        update();
        scheduleUpdateAsync();
    }

    public void update() {
        for (Book book : bookDao.findAll()) {
            cacheManager.getCache("books").put(book.getIsbn(), book);
        }
    }
}

确保你的 KeyGenerator 将返回一个参数的对象(默认情况下)。或者,在 BookService 中公开 putToCache 方法,以避免直接使用cacheManager。

Make sure your KeyGenerator will return the object for one parameter (as default). Or else, expose the putToCache method in BookService to avoid using cacheManager directly.

@CachePut(value = "books", key = "#book.isbn")
public Book putToCache(Book book) {
    return book;
}

这篇关于如何在春季启动时加载@Cache?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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