如何在 Spring Boot 中管理无限进程? [英] How do I manage an infinite process in Spring Boot?

查看:34
本文介绍了如何在 Spring Boot 中管理无限进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a process which is an infinite loop:

public class MyProcess {

    public void start() {
        while (true) {
            //process
        }
    }
}

当我开始使用 Spring Boot 时,我的第一种方法是在应用程序启动后从上下文中获取 bean 并手动启动进程:

When I started using Spring Boot, my first approach was to get the bean from the context after the application had started and manually start the process:

@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:

This worked but did not seem like the right way of doing it, so I implemented a CommandLineRunner:

@Component
public class MyRunner implements CommandLineRunner {

    @Autowired
    private MyProcess myProcess;

    @Override
    public void run(String... args) {
        this.myProcess.start();
    }
}

这与之前几乎相同,但这里的 SpringApplication#run 调用从未真正完成,这似乎也是错误的.我这样认为正确吗?

This is almost the same as before, but here the SpringApplication#run call never actually finishes, which seems also wrong. Am I correct to think that?

然后我尝试使用 Executor 自己管理它,但是为了捕获任何 Exception 我不得不调用 Future#get 导致相同的阻塞状态.

I then tried to manage this on my own with an Executor, but in order to catch any Exception I had to call Future#get which resulted in the same blocking state.

代替这个,我现在在 CommandLineRunner#run 方法上使用 @Async 注释.

Instead of this, I am now using an @Async annotation on the CommandLineRunner#run method.

这似乎是最好的解决方案,因为应用程序在任务也启动后完成启动.任何 Exception 都将被拾取并记录,但 Sprint 创建的支持 Executor 会阻止应用程序关闭.

This seems to be the best solution as the application finishes starting after the task has also been started. Any Exception will be picked up and logged, but the backing Executor created by Sprint prevents the application from shutting down.

我假设有一种方法可以要求 Spring 终止 Executor 以便整个应用程序可以退出,因为我使用 Supervisor 在外部对其进行管理.

I assume there is a way of asking Spring to terminate the Executor so that the entire application can exit since I am managing it externally with Supervisor.

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

Is this the correct approach or am I missing a step? Should the application be independent and restart the process after a failure?

推荐答案

在主线程中做一些工作.在没有 @Async 的情况下从 main() 调用 myProcess.start() 有什么问题?当你完成你的工作时,只需在 MyProcess#start

Do some work in the main thread. What is wrong with calling myProcess.start() from main() without @Async? When you finish your job just leave loop in MyProcess#start

这篇关于如何在 Spring Boot 中管理无限进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆