Exchange

exchangeToMono()exchangeToFlux() 方法(或 Kotlin 中的 awaitExchange { }exchangeToFlow { }) 适用于需要更多控制的更高级别案例中,例如根据响应状态不同对响应进行解码:

The exchangeToMono() and exchangeToFlux() methods (or awaitExchange { } and exchangeToFlow { } in Kotlin) are useful for more advanced cases that require more control, such as to decode the response differently depending on the response status:

  • Java

  • Kotlin

Mono<Person> entityMono = client.get()
		.uri("/persons/1")
		.accept(MediaType.APPLICATION_JSON)
		.exchangeToMono(response -> {
			if (response.statusCode().equals(HttpStatus.OK)) {
				return response.bodyToMono(Person.class);
			}
			else {
				// Turn to error
				return response.createError();
			}
		});
val entity = client.get()
  .uri("/persons/1")
  .accept(MediaType.APPLICATION_JSON)
  .awaitExchange {
		if (response.statusCode() == HttpStatus.OK) {
			 return response.awaitBody<Person>()
		}
		else {
			 throw response.createExceptionAndAwait()
		}
  }

在使用上述内容时,在返回的 MonoFlux 完成后,将检查响应正文,如果未消费则释放以防止内存和连接泄漏。因此,无法进一步解码响应。由提供的函数来声明如何根据需要解码响应。

When using the above, after the returned Mono or Flux completes, the response body is checked and if not consumed it is released to prevent memory and connection leaks. Therefore the response cannot be decoded further downstream. It is up to the provided function to declare how to decode the response if needed.