[英]Is there an out-of-the-box thread pool with multiple queues (that ensure serial processing of each queue)?
[英]Spring concurrent processing multiple queues with single thread pool
我有一个应该处理和存储套接字传入数据的 spring 应用程序,因为瓶颈问题,这应该用多线程来完成。
传入的数据属于许多实体,每个实体任务应该串行处理,但我认为为每个实体分配一个线程并不是一个好的解决方案(数千个单线程来处理每个实体的队列)
那么如何定义一个公共ThreadPool
来使用票价算法处理所有实体的队列呢?
您已经描述了使用消息驱动架构解决的完美问题。
Spring Integration 是为您提供此功能的模块。
您可以构建您的任务服务并使用 @ServiceActivator 进行注释,并使用 Channels 创建您的链。
通道可以选择在不同的线程池上执行,并且可以通过通道上的队列设置来克服由于尖峰负载引起的瓶颈。
绝对值得一试查看 Spring Integration 的文档。
您可以使用Project reactor或RxJava按组拆分传入的消息流,并按顺序处理每个组中的事件。
使用 Project Reactor,您的代码可能如下所示:
Scheduler groupScheduler = Schedulers.newParallel("groupByPool", 16);
Flux.fromStream(incomingMessages()) // stream of new data from socket
.groupBy(Message::getEntityId) // split incoming messages by groups, which should be processed serially
.map(g -> g.publishOn(groupScheduler)) //create new publisher for groups of messages
.subscribe( //create consumer for main stream
stream ->
stream.subscribe(this::processMessage) // create consumer for group stream and process messagaes
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.