Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用WebClient使用反应式Spring Rest API_Spring_Rest_Spring Mvc_Reactive Programming_Spring Webflux - Fatal编程技术网

如何使用WebClient使用反应式Spring Rest API

如何使用WebClient使用反应式Spring Rest API,spring,rest,spring-mvc,reactive-programming,spring-webflux,Spring,Rest,Spring Mvc,Reactive Programming,Spring Webflux,我需要在后端作业(可执行jar)上使用反应式RESTAPI(使用SpringWebFlux构建) 我已经读过SpringWebClient,但我不理解其中的一些要点 例如: WebClient webClient = WebClient.create("http://localhost:8080"); Mono<Person> person = webClient.get() .uri("/persons/{id}", 42) .accept(Med

我需要在后端作业(可执行jar)上使用反应式RESTAPI(使用SpringWebFlux构建)

我已经读过SpringWebClient,但我不理解其中的一些要点

例如:

WebClient webClient = WebClient.create("http://localhost:8080");

Mono<Person> person = webClient.get()
        .uri("/persons/{id}", 42)
        .accept(MediaType.APPLICATION_JSON)
        .exchange()
        .then(response -> response.bodyToMono(Person.class));
WebClient-WebClient=WebClient.create(“http://localhost:8080");
Mono person=webClient.get()
.uri(“/persons/{id}”,42)
.accept(MediaType.APPLICATION_JSON)
.exchange()
.then(response->response.bodytomino(Person.class));
在最后一行,有一个“bodyToMono”。这就是我的问题:

如果调用的RESTAPI已经是一个反应式服务,我是否需要将响应转换为mono?有什么我遗漏的吗

从我的角度来看,我认为可以有一种方法在代码中明确表示我的Rest API是反应式的,但这可能是我不知道的。

是的,这是必需的。 被动的整个想法是确保没有线程被IO阻塞

您可能已经使您的服务器端服务成为反应式服务,但当您使用该服务时,当您的客户端被阻止直到服务器做出响应时,您会得到什么好处。客户端线程一直等待,直到服务器响应。这是不可取的

webClient.get()
        .uri("/persons/{id}", 42)
        .accept(MediaType.APPLICATION_JSON)
        .exchange().block()
将阻止当前客户端线程,直到服务器响应。这可能会阻止客户端线程

webClient.get()
        .uri("/persons/{id}", 42)
        .accept(MediaType.APPLICATION_JSON)
        .exchange()
        .then(response -> response.bodyToMono(Person.class));
为您提供一个Mono,该Mono是对将来可以发出单个值的发布者的引用。因此,客户端线程是非阻塞的

我已经在博客上详细解释了这一点。

谢谢您的详细解释。我现有的RESTAPI正在返回一个ResponseBodyMitter,我正在尝试编写一个客户端来获取异步响应。我可以为此使用此被动网络客户端吗?