gpt4 book ai didi

spring-webflux - 将对 OutputStream 的写入转换为 ServerResponse 可用的 Flux

转载 作者:行者123 更新时间:2023-12-02 01:02:45 30 4
gpt4 key购买 nike

我有一个遗留库,我必须使用它来检索文件。这个遗留库不会返回 InputStream,正如您通常期望的那样读取内容,但它期望它传递一个开放的 OutputStream,它可以写入。

我必须编写一个 Webflux REST 服务,将此 OutputStream 写入 org.springframework.web.reactive.function.server.ServerResponse 主体。

legacyLib.BlobRead(outputStream); // writes the stream to an outputstream, that has to be provided by me, and somehow has to end up in the ServerResponse

因为我想将 Stream 直接传递给 ServerResponse,我可能必须做这样的事情,对吧?

ServerResponse.ok().body(magicOutpuStreamToFluxConverter(), DataBuffer.class);

最佳答案

这是 RequestHandler 的重要部分。我遗漏了一些通常不需要的错误处理/异常捕获。请注意,我为读取publishedOn 一个不同的Scheduler(或者至少,这是我想做的),这样阻塞读取就不会干扰我的主要事件主题:

    private Mono<ServerResponse> writeToServerResponse(@NotNull FPTag tag) {
final long blobSize = tag.getBlobSize();
return ServerResponse.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(Flux.<DataBuffer>create((FluxSink<DataBuffer> emitter) -> {
// for a really big blob I want to read it in chunks, so that my server doesn't use too much memory
for(int i = 0; i < blobSize; i+= tagChunkSize) {
// new DataBuffer that is written to, then emitted later
DefaultDataBuffer dataBuffer = new DefaultDataBufferFactory().allocateBuffer();
try (OutputStream outputStream = dataBuffer.asOutputStream()) {
// write to the outputstream of DataBuffer
tag.BlobReadPartial(outputStream, i, tagChunkSize, FPLibraryConstants.FP_OPTION_DEFAULT_OPTIONS);
// don't know if flushing is strictly neccessary
outputStream.flush();
} catch (IOException | FPLibraryException e) {
log.error("Error reading + writing from tag to http outputstream", e);
emitter.error(e);
}
emitter.next(dataBuffer);
}
// if blob is finished, send "complete" to my flux of DataBuffers
emitter.complete();
}, FluxSink.OverflowStrategy.BUFFER).publishOn(Schedulers.newElastic("centera")).doOnComplete(() -> closeQuietly(tag)), DataBuffer.class);

}

关于spring-webflux - 将对 OutputStream 的写入转换为 ServerResponse 可用的 Flux<DataBuffer>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49426304/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com