繁体   English   中英

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

[英]In a existing spring-boot application, run a infinite loop in a seperate thread

我有一个现有的 spring-boot 服务(托管许多 api),主要有以下 class。

@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 提供对异步作业的支持(完整文档在这里):

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

}

For your particular use case, you should probably use spring built-in messaging: https://cloud.spring.io/spring-cloud-aws/1.2.x/multi/multi__messaging.html

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM