【发布时间】:2020-02-15 01:28:59
【问题描述】:
TLDR:我希望我的 Spring Boot 应用程序在启动时运行一些初始化代码。代码需要访问 Spring bean 和值。
我正在编写一个 Spring Boot 应用程序,它将同时使用队列中的多条消息。为此,它需要实例化多个消费者对象。 Spring 是否有很好的方法来实例化同一类的可配置数量的实例?
我必须使用的队列客户端充当线程池。它为我给它的每个消费者对象创建一个线程。消费者对象一次只接收一条消息,它们必须完全处理并确认该消息,然后才能接收另一条消息。消费者不是线程安全的,所以我不能只使用单例实例。
我考虑了以下方法,但我觉得它不合适。这似乎是对 @Component 注释的滥用,因为 Initializer 实例在构造后未使用。有什么更好的方法?
@Component
public class Initializer {
public Initializer(ConsumerRegistry registry, @Value("${consumerCount}") int consumerCount) {
for (int i = 0; i < consumerCount; i++) {
// Each registered consumer results in a thread that consumes messages.
// Incoming messages will be delivered to any consumer thread that's not busy.
registry.registerConsumer(new Consumer());
}
}
}
【问题讨论】:
-
你想用这个实现什么
-
可能是线程池?
-
我在问题中添加了更多细节。
-
同时来自队列的消息?你使用的是哪个队列,rabbitmq、activemq 还是 kafka Streams?
标签: java spring spring-boot