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

时间:2020-03-16 10:44:33

标签: spring webclient spring-webflux project-reactor

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

1 个答案:

答案 0 :(得分:1)

您可以尝试类似的方法。我在这里使用了'block',因为您想直接返回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();

相反,您可以通过将返回类型更改为block

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