且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在春季启动时加载@Cache?

更新时间:2023-12-05 16:45:22

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

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