同步使用

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 协程和 Spring WebFlux,只需在控制器方法中使用挂起函数或返回 Flow

© . This site is unofficial and not affiliated with VMware.