【问题标题】:How to compile answer from multiple requests with Spring WebClient如何使用 Spring WebClient 编译来自多个请求的答案
【发布时间】:2020-06-27 11:27:05
【问题描述】:

我想做一个代理控制器。我收到一个 HTTP 请求,我需要将其代理到其他服务,然后将响应中的答案编译成一个并将其发回。如果一个响应包含异常,则 ResponseEntity 不应使用代码 200(OK)。

@PostMapping("**")
public ResponseEntity<String> processIn(@RequestHeader HttpHeaders headers, @RequestBody String body,  ServerHttpRequest request) {

    Mono<String> firstAnswer = sendRequest(headers, body, "https://localhost:1443");
    Mono<String> secondAnswer = sendRequest(headers, body, "http://localhost:8080");

    return ResponseEntity.ok().body(format("1: %s \n 2: %s", firstAnswer, secondAnswer));
}

private Mono<String> sendRequest(HttpHeaders headers, String body, String url) {
        return webClient.post()
                .uri(new URI(url))
                .headers(httpHeaders -> new HttpHeaders(headers))
                .bodyValue(body)
                .retrieve()
                .bodyToMono(String.class)
                .doOnNext(ans -> log.info(">>>>request to {} : {}", url, ans))
                .doOnError(err -> log.error(">>>>error sending to {}", url));
    }

【问题讨论】:

    标签: spring webclient spring-webflux project-reactor


    【解决方案1】:

    你可以试试这样的。我在这里使用了“阻止”,因为您想直接返回 ResponseEntity

    firstAnswer.zipWith(secondAnswer)
            .map(tuple -> String.format("1: %s \n 2: %s", tuple.getT1(), tuple.getT2()))
            .map(ResponseEntity::ok)
            .onErrorReturn(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build())
            .block();
    

    相反,您可以通过将返回类型更改为 Mono&lt;ResponseEntity&gt; 来删除 block

    firstAnswer.zipWith(secondAnswer)
            .map(tuple -> String.format("1: %s \n 2: %s", tuple.getT1(), tuple.getT2()))
            .map(ResponseEntity::ok)
            .onErrorReturn(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-30
      • 2019-09-19
      • 2020-05-04
      • 1970-01-01
      • 2019-01-14
      • 2018-04-14
      • 1970-01-01
      • 2021-07-15
      相关资源
      最近更新 更多