Spring WebClient:如何将大byte []流式传输到文件? [英] Spring WebClient: How to stream large byte[] to file?

查看:468
本文介绍了Spring WebClient:如何将大byte []流式传输到文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

对我来说,不明显的部分是bodyToFlux(DataBuffer.class),因为它在

I see people have found a few workarounds/hacks to this issue with RestTemplate, but I am more interested in doing it the proper way with the WebClient.

There are many examples of using RestTemplate to download binary data but almost all of them load the byte[] into memory.

解决方案

With recent stable Spring WebFlux (5.2.4.RELEASE as of writing):

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

For me the non-obvious part was the 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.

这篇关于Spring WebClient:如何将大byte []流式传输到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆