如何使用 Spring WebClient 编译来自多个请求的答案

How to compile answer from multiple requests with Spring WebClient

我想做一个代理控制器。我收到一个 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));
    }

你可以尝试这样的事情。我在这里使用了'block',因为你想直接return 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();

相反,您可以通过将 return 类型更改为 Mono<ResponseEntity>

来删除 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());