我有这个实用方法来加载我的网络应用程序的内容
@Cacheable(value="dataStrore" )
public MarketJson retrieveMarketJson(DataRequest request) throws Exception{
try {
......
当通过正常的 Web 请求调用此缓存时,缓存工作正常,但第一个请求确实需要很长时间,因为这涉及大量处理。
所以我添加了一个组件,尝试在服务器启动时加载它。
@EventListener(ContextRefreshedEvent.class)
public void contextRefreshedEvent() {
//call retrieveMarketJson method for all possible requests
}
这表明在日志文件中工作正常,但当网络请求进入时,似乎缓存尚未发生,并且它在那时加载并缓存,然后继续工作正常。
我正在使用 EHCache。
最佳答案
您可以尝试以下操作。方法 initialize()
将在应用程序初始化时运行。
@Component
public class InitializeCachedData {
@Autowired
private SampleService sampleService;
@PostConstruct
public void initialize() {
// Call retrieveMarketJson method for all possible requests
sampleService.callMethod();
}
}
更新
您可以尝试使用 ContextRefreshedEvent
修改代码,以避免运行根上下文。
@EventListener(ContextRefreshedEvent.class)
public void contextRefreshedEvent(ContextRefreshedEvent e) {
if (e.getApplicationContext().getParent() != null) {
//call retrieveMarketJson method for all possible requests
}
}
关于java - @Cacheable 无法按预期在启动时加载内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46058074/