【问题标题】:Spring boot webclient calling api which returns XML response having 2GB best way to callSpring boot webclient调用api返回具有2GB最佳调用方式的XML响应
【发布时间】:2021-06-29 16:34:09
【问题描述】:

我正在调用一个返回 xm 响应的 api,但该响应有大约 2GB 数据,请您帮忙我们应该如何以有效的方式调用它,现在它未能超过数据缓冲区限制

下面是 XML dto 类

    @XmlRootElement(name = "Result")
    @lombok.Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Result{
     private List<Data> dataLisst;
    
    }

@XmlRootElement(name = "Data")
@lombok.Data
@AllArgsConstructor
@NoArgsConstructor
public class Data {

    private Integer id;
    private String dataVersion;
    private String name;
}

以下是我将 Webclient 称为其单对象响应的方式

@Service
public class WebclientXML {

    public Result getXMLResult() {
        return  getWebClient()
                .get()
                .uri("/xml-resp/res")
                .retrieve()
                .bodyToMono(Result.class)
                .block();
    }

    private WebClient getWebClient() {
         return  WebClient.builder()
                .baseUrl("http://<host>:port")
                .build();
    }

}

【问题讨论】:

  • 由于您不想将 2GB 的数据编组到内存中,因此在处理响应正文时需要使用 streaming。您应该自己研究如何做到这一点:关键字streaming

标签: java xml spring-boot spring-webclient


【解决方案1】:

假设您的远程服务使用 Jackson 可以反序列化为 Something.class 的 POJO 集合进行响应,您可以执行以下操作:

@GetMapping(path = "/streaming", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
@ResponseBody
public Flux<Something> streamSomething() {
  return WebClient.create()
    .get().uri("http://example.org/resource")
    .retrieve().bodyToFlux(Something.class)
    .delaySubscription(Duration.ofSeconds(5))
    .repeat();
}

【讨论】:

  • 它不是 Pojo 的集合,它是简单的对象,如下面的示例响应 &lt;Result&gt; &lt;data&gt;agaga&lt;/data&gt; &lt;data&gt;ww&lt;/data&gt; &lt;/Result&gt;
猜你喜欢
  • 2020-05-20
  • 2021-09-19
  • 2022-07-24
  • 2022-01-23
  • 2016-07-23
  • 1970-01-01
  • 2020-04-29
  • 2020-07-11
  • 2014-04-30
相关资源
最近更新 更多