Java 在现有的spring引导应用程序中,在单独的线程中运行无限循环

Java 在现有的spring引导应用程序中,在单独的线程中运行无限循环,java,multithreading,spring-boot,asynchronous,executorservice,Java,Multithreading,Spring Boot,Asynchronous,Executorservice,我有一个现有的spring引导服务(托管许多API),其中包含以下主类 @SpringBootApplication public class BusinessRules { public static void main(String[] args) { SpringApplication.run(BusinessRules.class, args); } } 作为一个新的需求,我需要在同一个服务中的不同线程(通过无限循环)中使用来自两个不同SQS队列的SQ

我有一个现有的spring引导服务(托管许多API),其中包含以下主类

@SpringBootApplication
public class BusinessRules {

    public static void main(String[] args) {
        SpringApplication.run(BusinessRules.class, args);
    }
}
作为一个新的需求,我需要在同一个服务中的不同线程(通过无限循环)中使用来自两个不同SQS队列的SQS消息。我可以简单地使用ExecutorService添加两个新线程吗。大概是这样的:

@SpringBootApplication
public class BusinessRules {

    public static void main(String[] args) {
        SpringApplication.run(BusinessRules.class, args);
        //new code
        ExecutorService executor = Executors.newFixedThreadPool(2);
        Runnable runnable1 = new SQSMessageProcessor1(); //infinite loop in run method
        Runnable runnable2 = new SQSMessageProcessor2(); //infinite loop in run method
        executor.execute(runnable1);
        executor.execute(runnable2);
    }
}

上述代码或其他更好的替代方案是否存在任何问题。

通常,spring支持异步作业(完整文档):

对于您的特定用例,您可能应该使用spring内置消息:


您当前代码的主要问题是它将失去spring的控制:上下文重启/停止、监视、依赖项注入等等。只是一个问题:难道不可能只使用一些JMS侦听器就可以立即将新消息转发给您的消费者吗?那么您就不需要轮询了:-)轮询是当前上下文中的一种核心需求。因此,我将有三个主要类(一个现有类和两个)带有
@SpringBootApplication
注释,新的将
@enablesync
@EnableScheduling
注释?我还有一个问题。新的异步应用程序和旧的非异步应用程序(带有主应用程序)之间的顺序是什么。这应该是同一个spring boot应用程序,不需要拆分它
@SpringBootApplication
@EnableAsync
@EnableScheduling
public class MyApp {

    public MyBean myBean() {
        return new MyBean();
    }

}

public class MyBean { 

    @Scheduled(fixedDelay=5000)
    public void doSomething() {
        // something that should execute periodically
    }

}