How to correctly read Flux and convert it to a single inputStream

前端 未结 6 419
旧巷少年郎
旧巷少年郎 2020-12-05 07:13

I\'m using WebClient and custom BodyExtractorclass for my spring-boot application

WebClient webLCient = WebClient.create();
webClie         


        
6条回答
  •  [愿得一人]
    2020-12-05 07:38

    You can use pipes.

    static  Mono pipeAndApply(
            final Publisher source, final Executor executor,
            final Function function) {
        return using(Pipe::open,
                     p -> {
                         executor.execute(() -> write(source, p.sink())
                                 .doFinally(s -> {
                                     try {
                                         p.sink().close();
                                     } catch (final IOException ioe) {
                                         log.error("failed to close pipe.sink", ioe);
                                         throw new RuntimeException(ioe);
                                     }
                                 })
                                 .subscribe(releaseConsumer()));
                         return just(function.apply(p.source()));
                     },
                     p -> {
                         try {
                             p.source().close();
                         } catch (final IOException ioe) {
                             log.error("failed to close pipe.source", ioe);
                             throw new RuntimeException(ioe);
                         }
                     });
    }
    

    Or using CompletableFuture,

    static  Mono pipeAndApply(
            final Publisher source,
            final Function function) {
        return using(Pipe::open,
                     p -> fromFuture(supplyAsync(() -> function.apply(p.source())))
                             .doFirst(() -> write(source, p.sink())
                                     .doFinally(s -> {
                                         try {
                                             p.sink().close();
                                         } catch (final IOException ioe) {
                                             log.error("failed to close pipe.sink", ioe);
                                             throw new RuntimeException(ioe);
                                         }
                                     })
                                     .subscribe(releaseConsumer())),
                     p -> {
                         try {
                             p.source().close();
                         } catch (final IOException ioe) {
                             log.error("failed to close pipe.source", ioe);
                             throw new RuntimeException(ioe);
                         }
                     });
    }
    

提交回复
热议问题