java - 在现有的 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);
}
}
上述代码或任何其他更好的替代方案是否存在任何问题。
解决方案
一般来说,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:上下文重启/停止、监控、依赖注入等
推荐阅读
- c++ - 如何将字符从 int 转换为“出现”在控制台中?
- jmeter - 如何在 JMeter 中模拟新用户和现有用户的负载?
- prometheus - 是否有监控 apache carbondata 的方法?
- c# - 如何从自动生成的类(xsd)中实现 xml 序列化
- python - 通过 Windows 操作系统上的 PyQT5 QTBluetooth 模块通过 UUID 发现特定的 GATT 服务
- asp.net - 尝试将角色分配给 asp.net 成员资格 CreateUserWizard 上的已创建用户时出现 System.NullReferenceException
- c# - 在异步 EF 核心拦截器中获取堆栈跟踪
- reactjs - 我对 npx create react app 有一些问题,可以 sbd 告诉我如何解决它,请
- python - 尝试在 WSL 2(Ubuntu 20.04 LTS 和 Windows 10)中使用 PyGame 检测 MIDI 输入时出现 Alsa 错误
- javascript - 在移动浏览器中隐藏两个文本选择助手