Spring web 运行 启动后
Spring web run after startup
我 运行 一个 spring
网络应用程序(不是 spring boot
)。
在启动时,应用程序从另一台服务器请求数据集。处理此数据集大约需要一分钟。当我将此应用程序部署到 tomcat 时,需要一分钟。在完全处理数据集请求之前,网站本身将不可用。但实际上我希望看到,用户已经能够登录并处理数据集,而不会停止应用程序的其余部分工作。
目前我有一项服务 class 并使用 @PostConstruct
-Annotation。
@Service
public class StartupService {
@PostConstruct
public void load() {
//perform the dataset request
...
}
}
我在 Whosebug 上找到了类似的文章,建议尝试使用 ApplicationListener。但这具有相同的效果。除非数据集请求已完成,否则不会回答对网站的 HTTP 请求。
@Service
public class StartupService implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(final ContextRefreshedEvent event) {
//perform the dataset request
...
}
}
当然有可能开始一个新的 Thread
,但我想知道解决这个问题的最佳方法是什么。
来自 PostConstruct 文档:
... This method MUST be invoked before the class is put into service...
因此 Spring 在 @PostContruct 方法完成之前无法为请求提供服务。
按照您的建议,手动启动一个新线程,或者:
- 从@PostConstruct 方法中调用另一个用@Async 注释的bean 中的public 方法,Spring 将异步调用允许@PostConstruct 方法立即完成并开始服务的方法请求
- 来自@PostConstruct 方法,@Schedule 一次性任务 - 例如从现在开始 1 分钟
另请参阅:@EnableAsync and/or @EnableScheduling
我 运行 一个 spring
网络应用程序(不是 spring boot
)。
在启动时,应用程序从另一台服务器请求数据集。处理此数据集大约需要一分钟。当我将此应用程序部署到 tomcat 时,需要一分钟。在完全处理数据集请求之前,网站本身将不可用。但实际上我希望看到,用户已经能够登录并处理数据集,而不会停止应用程序的其余部分工作。
目前我有一项服务 class 并使用 @PostConstruct
-Annotation。
@Service
public class StartupService {
@PostConstruct
public void load() {
//perform the dataset request
...
}
}
我在 Whosebug 上找到了类似的文章,建议尝试使用 ApplicationListener。但这具有相同的效果。除非数据集请求已完成,否则不会回答对网站的 HTTP 请求。
@Service
public class StartupService implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(final ContextRefreshedEvent event) {
//perform the dataset request
...
}
}
当然有可能开始一个新的 Thread
,但我想知道解决这个问题的最佳方法是什么。
来自 PostConstruct 文档:
... This method MUST be invoked before the class is put into service...
因此 Spring 在 @PostContruct 方法完成之前无法为请求提供服务。
按照您的建议,手动启动一个新线程,或者:
- 从@PostConstruct 方法中调用另一个用@Async 注释的bean 中的public 方法,Spring 将异步调用允许@PostConstruct 方法立即完成并开始服务的方法请求
- 来自@PostConstruct 方法,@Schedule 一次性任务 - 例如从现在开始 1 分钟
另请参阅:@EnableAsync and/or @EnableScheduling