同步使用

WebClient 可以透過在末尾阻塞以等待結果來同步使用

  • Java

  • Kotlin

Person person = client.get().uri("/person/{id}", i).retrieve()
	.bodyToMono(Person.class)
	.block();

List<Person> persons = client.get().uri("/persons").retrieve()
	.bodyToFlux(Person.class)
	.collectList()
	.block();
val person = runBlocking {
	client.get().uri("/person/{id}", i).retrieve()
			.awaitBody<Person>()
}

val persons = runBlocking {
	client.get().uri("/persons").retrieve()
			.bodyToFlow<Person>()
			.toList()
}

然而,如果需要進行多次呼叫,更有效的方法是避免單獨阻塞每個響應,而是等待組合結果。

  • Java

  • Kotlin

Mono<Person> personMono = client.get().uri("/person/{id}", personId)
		.retrieve().bodyToMono(Person.class);

Mono<List<Hobby>> hobbiesMono = client.get().uri("/person/{id}/hobbies", personId)
		.retrieve().bodyToFlux(Hobby.class).collectList();

Map<String, Object> data = Mono.zip(personMono, hobbiesMono, (person, hobbies) -> {
			Map<String, String> map = new LinkedHashMap<>();
			map.put("person", person);
			map.put("hobbies", hobbies);
			return map;
		})
		.block();
val data = runBlocking {
		val personDeferred = async {
			client.get().uri("/person/{id}", personId)
					.retrieve().awaitBody<Person>()
		}

		val hobbiesDeferred = async {
			client.get().uri("/person/{id}/hobbies", personId)
					.retrieve().bodyToFlow<Hobby>().toList()
		}

		mapOf("person" to personDeferred.await(), "hobbies" to hobbiesDeferred.await())
	}

上述只是一個示例。還有許多其他模式和運算子可用於構建響應式管道,該管道可以進行許多遠端呼叫,其中一些呼叫可能是巢狀的、相互依賴的,並且在完成之前不會發生阻塞。

使用 FluxMono,您永遠不應該在 Spring MVC 或 Spring WebFlux 控制器中阻塞。只需從控制器方法返回結果響應式型別即可。同樣的原則也適用於 Kotlin Coroutines 和 Spring WebFlux,只需在控制器方法中使用掛起函式 (suspending function) 或返回 Flow