【发布时间】: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