How to load @Cache on startup in spring?
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;
}
I have encountered the following problem when using @PostConstruct: - even though the method I wanted to be cached was called, after calling it from swagger, it still didn't use the cached value. Only after called it once more.
That was because @PostConstruct is too early for caching something. (At least I think that was the issue)
Now I'm using it more late in the startup process and it works without problems:
@Component
public class CacheInit implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
//call service method
}
}