Spring Boot Webclient 的检索与交换 [英] Spring boot Webclient's retrieve vs exchange

查看:119
本文介绍了Spring Boot Webclient 的检索与交换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始在我的 Spring boot 项目中使用 WebClient.有人可以对 WebClient 中的 exchangeretrieve 方法之间的差异/用法有所了解吗?

I have started using WebClient in my Spring boot project recently. Can somebody throw some light on the differences/usages between exchange and retrieve method in WebClient.

我明白 exchange 返回 Mono 并且 retrieve 返回 ResponseSpec,我只想知道何时/为什么我应该使用它们中的每一个.

I undertand that exchange returns Mono<ClientResponse> and retrieve returns ResponseSpec, I just want to know when/why I should use each one of them.

非常感谢.

推荐答案

添加到 @JArgente 的 答案中.

根据官方文档retrieve() 方法:

According to the official documentation of the retrieve() method:

执行 HTTP 请求并检索响应正文.

Perform the HTTP request and retrieve the response body.

...

这个方法是使用exchange()和解码响应体的捷径客户响应.

This method is a shortcut to using exchange() and decoding the response body through ClientResponse.

exchange() 方法

执行 HTTP 请求并返回带有响应状态和标头的 ClientResponse.然后,您可以使用响应的方法来消耗主体:

Perform the HTTP request and return a ClientResponse with the response status and headers. You can then use methods of the response to consume the body:


retrieve() 方法对 ClientResponse 对象进行解码,并将现成的对象交给您使用.它没有一个很好的 api 来处理异常.


The retrieve() method decodes the ClientResponse object and hands you the ready-made object for your use. It doesn't have a very nice api for handling exceptions.

然而,另一方面,exchange() 方法将 ClientResponse 对象本身连同响应状态和标头交给您.使用交换方法,您可以对响应对象进行细粒度控制,并以更好的方式处理响应对象和异常.

However on the other hand the exchange() method hands you the ClientResponse object itself along with the response status and headers. With exchange method you get fine grained control over your response objects and a better way to handle the response object and the exceptions.

如果您只想使用一些 API,请使用 retrieve().

如果您想更好地控制响应对象、标头和异常,请使用 exchange().

更新 1

Spring 5.3 开始,exchange() 方法已弃用 由于可能的内存/连接泄漏.exchangeToMono()exchangeToFlux() 可以代替.

Starting from Spring 5.3, the exchange() method is deprecated due to possible memory/connection leaks. exchangeToMono() or exchangeToFlux() can be used instead.

感谢 @rhubarb 的更新.

这篇关于Spring Boot Webclient 的检索与交换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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