Java 如何在Spring Boot中管理无限进程?

Java 如何在Spring Boot中管理无限进程?,java,spring,spring-boot,Java,Spring,Spring Boot,我有一个无限循环的过程: public class MyProcess { public void start() { while (true) { //process } } } 当我开始使用Spring Boot时,我的第一种方法是在应用程序启动后从上下文中获取bean,然后手动启动流程: @SpringBootApplication public class MyApplication { public

我有一个无限循环的过程:

public class MyProcess {

    public void start() {
        while (true) {
            //process
        }
    }
}
当我开始使用Spring Boot时,我的第一种方法是在应用程序启动后从上下文中获取bean,然后手动启动流程:

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        ApplicationContext applicationContext = SpringApplication.run(MyApplication.class, args);

        MyProcess myProcess = applicationContext.getBean(MyProcess.class);
        myProcess.start();
    }
}
这很有效,但似乎不是正确的方法,因此我实现了一个
CommandLineRunner

@Component
public class MyRunner implements CommandLineRunner {

    @Autowired
    private MyProcess myProcess;

    @Override
    public void run(String... args) {
        this.myProcess.start();
    }
}
这与以前几乎相同,但这里的
SpringApplication#run
调用从未真正完成,这似乎也是错误的我这样想对吗?

然后,我尝试使用
执行器
自行管理此操作,但为了捕获任何
异常
,我必须调用
Future#get
,这导致了相同的阻塞状态

我现在在
CommandLineRunner#run
方法上使用了
@Async
注释,而不是这个注释

这似乎是最好的解决方案,因为应用程序在任务启动后完成启动。任何
异常
都将被拾取并记录,但Sprint创建的备份
执行器
会阻止应用程序关闭

我假设有一种方法可以要求Spring终止
执行器
,这样整个应用程序都可以退出,因为我正在与Supervisor进行外部管理


这是正确的方法还是我遗漏了一步?应用程序是否应该是独立的,并在出现故障后重新启动进程?

在主线程中执行一些工作。不使用
@Async
main()
调用
myProcess.start()
有什么问题?当您完成工作时,只需在
MyProcess#start

中留下循环,这是我首先做的,但我从未在任何示例中看到过,所以我不确定。那么,
CommandLineRunner
的目的是什么呢?@Djon我也有同样的问题。看起来这是一种通过注入bean(在应用程序启动后)在运行环境中访问命令行参数的方法。我使用命令行应用程序的
CommandLineRunner
界面