简体   繁体   中英

How to convert Flux of DataBuffer to Mono of byte array in Project Reactor?

There is a Flux<DataBuffer> . What is the natural way of converting it to Mono<byte[]> ?

Mono<byte[]> mergeDataBuffers(Flux<DataBuffer> flux){
  // ?
}

Use org.springframework.core.io.buffer.DataBufferUtils to join the DataBuffers from the Flux<DataBuffer> into a single DataBuffer , and then read that buffer into a byte array.


    Mono<byte[]> mergeDataBuffers(Flux<DataBuffer> dataBufferFlux) {
        return DataBufferUtils.join(dataBufferFlux)
                .map(dataBuffer -> {
                    byte[] bytes = new byte[dataBuffer.readableByteCount()];
                    dataBuffer.read(bytes);
                    DataBufferUtils.release(dataBuffer);
                    return bytes;
                });
    }

Be sure to take memory usage into consideration when doing so, since this approach will load all of the data into memory twice (once in the DataBuffers, and then again when copied into the byte[] ).

    try {
        PipedOutputStream osPipe = new PipedOutputStream();
        PipedInputStream isPipe = new PipedInputStream(osPipe);
        DataBufferUtils.write(data, osPipe)
                .subscribeOn(Schedulers.elastic())
                .doOnComplete(() -> {
                    try {
                        osPipe.close();
                    } catch (IOException ignored) {
                    }
                })
                .subscribe(DataBufferUtils.releaseConsumer());
        return IOUtils.toString(isPipe, StandardCharsets.UTF_8);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

subscribe is async, this may not get data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM