java - Spring Boot 多个 CommandLineRunner 执行顺序和状态
问题描述
我有一些启动操作要一个接一个地执行。这两个运行器都执行一些繁重的数据库操作。
@Slf4j
@Data
@Component
@Order(1)
public class MyFailureHandlerA implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
some_io_calls_a();
}
}
@Slf4j
@Data
@Component
@Order(2)
public class MyFailureHandlerB implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
some_io_calls_b();
}
}
我需要确保@Order(2)
runner 仅在@Order(1)
完成处理后才开始。
有什么方法可以实现这一点,比如将跑步者注册到一些策略上,以便监控他们的完成情况。
我找到了一种方法,例如,我可以等到单例作用域 bean 变量的值变为 true,它仅在第一个运行者完成它的任务时设置。但我担心这是否被推荐。
或者,我可以依靠@DependsOn来完成任务吗?是否可以保证,通过使用@DependsOn("MyFailureHandlerA")
overMyFailureHandlerB
将保证 1st runner 完成了它的全部操作?
我尝试的另一种方法是,从一个运行器一个接一个地调用服务,如下所示:
@Slf4j
@Data
@Component
public class MyFailureHandler implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
some_io_calls_q();
some_io_calls_b();
}
}
这是否有意义并且会确保操作一个接一个地执行?
spring-boot-2.3.2
解决方案
some_io_calls_q();
some_io_calls_b();
If both your methods do synchronized tasks, then using order is enough.
Your command will be executed following the order annotation. You can print few logs to check about it.
Otherwise, it's not enough with async task. You have to control when/how the task is completed...
The most simple solutions as you describe is calling both method in one commandlinerunner in case you are not sure the internal process of spring.
@DependsOn: only working with process creating bean. It's not relative the execution of commands.
推荐阅读
- neo4j - Cypher:使用常用节点关系链接为医生推荐文章
- java - Navigableset vs Navigablemap
- google-cloud-platform - Google Compute Engine 写入/读取元数据
- scala - Scala:继承与高阶函数
- google-maps - Google Maps API 的服务帐户
- datagridview - 将kartik gridview导出到excel时前导零被截断
- jquery - Bootstrap手风琴动态创建不折叠
- c# - ASP.Net Core Web API - ICollection 未显示在 JSON 结果集中
- c - 为什么变量 i 没有在循环中递增?
- junit - Mockito 无法模拟此类:class javax.servlet.jsp.PageContext