首页 > 解决方案 > 在现有的 spring-boot 应用程序中,在单独的线程中运行无限循环

问题描述

我有一个现有的 spring-boot 服务(托管许多 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);
    }
}

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

标签: javamultithreadingspring-bootasynchronousexecutorservice

解决方案


一般来说,spring 提供对异步作业的支持(完整文档在这里):

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

}

对于您的特定用例,您可能应该使用 spring 内置消息传递:https ://cloud.spring.io/spring-cloud-aws/1.2.x/multi/multi__messaging.html

您当前代码的主要问题是它将无法控制 spring:上下文重启/停止、监控、依赖注入等


推荐阅读