Spring WebClient:如何将大byte []流式传输到文件? [英] Spring WebClient: How to stream large byte[] to file?
问题描述
Spring RestTemplate
似乎无法在不将所有响应都缓存在内存中的情况下直接将响应流传输到文件.使用较新的Spring 5 WebClient
实现此目标的合适方法是什么?
WebClient client = WebClient.create("https://example.com");
client.get().uri(".../{name}", name).accept(MediaType.APPLICATION_OCTET_STREAM)
....?
我看到人们发现了使用RestTemplate
来解决此问题的一些变通方法/黑客,但我对使用WebClient
的正确方法更感兴趣.
有许多使用RestTemplate
下载二进制数据的示例,但是几乎所有示例都将byte[]
加载到内存中.
使用最近稳定的Spring WebFlux(撰写本文时为5.2.4.RELEASE):
final WebClient client = WebClient.create("https://example.com");
final Flux<DataBuffer> dataBufferFlux = client.get()
.accept(MediaType.TEXT_HTML)
.retrieve()
.bodyToFlux(DataBuffer.class); // the magic happens here
final Path path = FileSystems.getDefault().getPath("target/example.html");
DataBufferUtils
.write(dataBufferFlux, path, CREATE_NEW)
.block(); // only block here if the rest of your code is synchronous
对我来说,不明显的部分是 I see people have found a few workarounds/hacks to this issue with There are many examples of using With recent stable Spring WebFlux (5.2.4.RELEASE as of writing): For me the non-obvious part was the 这篇关于Spring WebClient:如何将大byte []流式传输到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!bodyToFlux(DataBuffer.class)
,因为它在RestTemplate
, but I am more interested in doing it the proper way with the WebClient
.RestTemplate
to download binary data but almost all of them load the byte[]
into memory.final WebClient client = WebClient.create("https://example.com");
final Flux<DataBuffer> dataBufferFlux = client.get()
.accept(MediaType.TEXT_HTML)
.retrieve()
.bodyToFlux(DataBuffer.class); // the magic happens here
final Path path = FileSystems.getDefault().getPath("target/example.html");
DataBufferUtils
.write(dataBufferFlux, path, CREATE_NEW)
.block(); // only block here if the rest of your code is synchronous
bodyToFlux(DataBuffer.class)
, as it is currently mentioned within a generic section about streaming of Spring's documentation, there is no direct reference to it in the WebClient section.