我是一个用Java进行反应式编程的新手。我计划使用spring-webclient而不是restclient,因为后者正在退役。当我向不同的端点发出几个http post请求,并且响应结构相同时,我会遇到这种情况。使用如下所示的With客户端代码,
List<Mono<CommonResponse>> monolist = new ArrayList<>();
for(String endpoint : endpoints) {
Mono<CommonResponse> mono = webClient.post()
.uri(URI.create(endPoint))
.body(Mono.just(requestData), RequestData.class)
.retrieve()
.bodyToMono(CommonResponse.class);
monolist.add(mono);
}每次请求我都会得到一个单声道。由于响应是常见的,我希望每个单声道都订阅一个公共方法,但假设响应数据没有帮助,我如何区分端点。我可以在订阅时向该方法传递额外的参数吗?
发布于 2020-04-08 16:31:20
您可以通过以下方式完成此操作。如果你有很多Mono,你可以把team看作flux,这实际上意味着你有很多Mono。然后你可以用一种方法订阅所有的内容。要向订阅方法传递一些额外的参数,比如有关端点的信息,您可以创建带有额外信息的额外对象。
Flux<ResponseWithEndpoint> commonResponseFlux = Flux.fromIterable(endpoints)
.flatMap(endpoint -> webClient.post()
.uri(URI.create(endpoint))
.body(Mono.just(requestData), RequestData.class)
.retrieve()
.bodyToMono(CommonResponse.class)
.map(response -> new ResponseWithEndpoint(response, endpoint)));
...
class ResponseWithEndpoint {
CommonResponse commonResponse;
String endpoint;
public ResponseWithEndpoint(CommonResponse commonResponse, String endpoint) {
this.commonResponse = commonResponse;
this.endpoint = endpoint;
}
}https://stackoverflow.com/questions/61095613
复制相似问题