这是我第一次使用webClient,我想知道如何等待列表
List<Address> addresses = collectAllAddresses(someObject);
List<Mono<List<AnotherAddress>>> monoResponses =
addresses.stream()
.map(address -> webClientGateway.findAddresses(userData, address.getFullAddress()))
.collect(Collectors.toList());
Mono.when(monoResponses).block();
log.info("mono responses");
monoResponses.stream()
.flatMap(it -> Objects.requireNonNull(it.block()).stream()).forEach(it -> log.info("mono responses + {}", it));
以及以下findAddresses
方法:
public Mono<List<AnotherAddress>> findAddresses(UserData userData, String fullAddress) {
if (StringUtils.isEmpty(fullAddress)) {
log.info("Address is empty that why we return Mono.just(Collections.emptyList()");
return Mono.just(Collections.emptyList());
}
return webClient.get()
.uri(path, uri -> uri.queryParam("query", fullAddress).queryParam("count", 1).build())
.header("someHeader", someHeader)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<List<AnotherAddress>>() {
})
.doOnError(e -> log.error("Error occurred!", e));
}
但每次我执行它时,我总是得到一个空对象的列表,我的意思是我得到一个列表,但是列表中的每个对象都是空的(另一个类的每个字段都是空的)。有什么不对劲?
UDP:更多解释:我有两个微服务。在一个微服务(返回另一个地址)中,有一个RestController发送另一个地址。在另一个微服务中,我想使用WebClient(而不是使用线程池)从以前的微服务调用RestController。当我有以前的实现函数webClientGateway.find地址(userData,address.get全地址()),它返回Mono
使用助焊剂代替单声道,例如(未测试):
public Flux<AnotherAddress> findAddresses(UserData userData, String fullAddress) {
if (StringUtils.isEmpty(fullAddress)) {
log.info("Address is empty that why we return Mono.just(Collections.emptyList()");
return Flux.empty();
}
return webClient.get()
.uri(path, uri -> uri.queryParam("query", fullAddress).queryParam("count", 1).build())
.header("someHeader", someHeader)
.retrieve()
.bodyToFlux(AnotherAddress.class)
.doOnError(e -> log.error("Error occurred!", e));
}
如果你不需要按地址分组的另一个地址列表,你可以使用这样的东西(未经测试):
Flux<AnotherAddress> anotherAddressFlux= Flux.fromIterable(addresses)
.flatMap(address -> webClientGateway.findAddresses(userData, address.getFullAddress()));
如果你想阻止你可以使用:
List<AnotherAddress> anotherAddressList = anotherAddressFlux.collectList().block();