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);
}
}
}
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;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…