【问题标题】:spring webflux stream Completion Consumerspring webflux流完成消费者
【发布时间】:2019-12-15 00:34:50
【问题描述】:

我有 spring webflux 流消费者,它调用 REST 端点并使用接收到的消息并保存到 RDBMS。我正在尝试找到一种批处理它的方法。我看到 subscribe() 有一个在完成时调用的重载方法。我试图找到在调用此完成使用者时如何获取数据,因为我正在调用 Runnable 类型的 CompletionConsumer 并且我所拥有的只是不带任何参数的 run() 方法。

**CLIENT**

       WebClient.create("http://localhost:8080")
                .get()
                .uri("/objects")
                .accept(MediaType.TEXT_EVENT_STREAM)
                .exchange()
                .flatMapMany(clientResponse ->clientResponse.bodyToFlux(MyObject.class))
               .subscribe(null,null,completionProcessorSubscriber);


**COMPLETION SUBSCRIBER**


@Service
public class CompletionProcessorSubscriber implements  Runnable{

    @Autowired
    LegacyDAOImpl dao;

    Logger logger = LoggerFactory.getLogger(CompletionProcessorSubscriber.class);


    public void run() {

        logger.info("\ninside RUNNNNNNNNN\n\n");
// here how to get hold of the data stream ?
    }

Below is the  Documentation from the Flux API

 */
    public final Disposable subscribe(
            @Nullable Consumer<? super T> consumer,
            @Nullable Consumer<? super Throwable> errorConsumer,
            @Nullable Runnable completeConsumer) {
        return subscribe(consumer, errorConsumer, completeConsumer, null);
    }

【问题讨论】:

    标签: rest spring-boot spring-mvc spring-data spring-webflux


    【解决方案1】:

    您应该避免向订阅者方法添加太多逻辑。相反,您应该利用 Flux API 提供的丰富的运算符集。

    在这种情况下,您需要的操作员是 buffer 来收集批次,concatMap 来顺序执行批次。

    在下面的示例中,我假设 LegacyDAOImpl 是一个阻塞服务,其工作应该分配给适当的线程池。

    public static void main(String[] args) throws InterruptedException
    {
        webClient.get()
                 .uri("/objects")
                 .accept(MediaType.TEXT_EVENT_STREAM)
                 .exchange()
                 .flatMapMany(clientResponse -> clientResponse.bodyToFlux(MyObject.class))
                 .buffer(100) // batch size
                 .concatMap(batchOfMyObjects -> Mono.fromRunnable(() -> legacyDAOImpl.saveAll(batchOfMyObjects))
                                                    .subscribeOn(Schedulers.elastic())) // blocking IO goes to elastic thread pool
                 .subscribe();
    }
    
    private static class LegacyDAOImpl
    {
        public void saveAll(List<MyObject> myObjects)
        {
            // save here
        }
    }
    
    private static class MyObject
    {
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-17
      • 1970-01-01
      • 2020-11-02
      • 2016-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-14
      • 1970-01-01
      相关资源
      最近更新 更多