【问题标题】:Multiple Mono and common subscriber多个 Mono 和普通订户
【发布时间】:2020-04-08 07:42:55
【问题描述】:

我是 Java 反应式编程的新手。我计划使用 spring-webclient 而不是 restclient,因为后者正在退役。当我向不同的端点发出多个 http post 请求并且响应结构相同时,我遇到了一种情况。使用如下 webclient 代码,

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);
}

每个请求我都会得到一个单声道。由于响应很常见,我希望每个单声道都订阅一个通用方法,但是假设响应数据没有帮助,我该如何区分端点。 我可以在订阅时向方法传递额外的参数吗?

【问题讨论】:

    标签: spring java-8 project-reactor rest-client spring-webclient


    【解决方案1】:

    您可以通过以下方式执行此操作。如果你有很多单声道,你可以将团队视为通量,这实际上意味着你有很多单声道。然后,您可以使用单一方法订阅所有这些。要将一些额外的参数传递给订阅方法,例如有关端点的信息,您可以使用其他信息创建额外的对象。

    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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-25
      • 1970-01-01
      • 2020-01-30
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      • 2016-11-26
      相关资源
      最近更新 更多