【问题标题】:Spring Webflux : How to return HTTP 200 response with body when the called service returns HTTP 201 without body with WebClient?Spring Webflux:当被调用的服务使用WebClient返回没有正文的HTTP 201时,如何返回带有正文的HTTP 200响应?
【发布时间】:2021-11-26 11:41:11
【问题描述】:

我有一个接收 HTTP 请求的微服务 (Java+Spring Boot),然后我通过 HTTP 调用另一个服务的 REST API 调用。被调用的服务返回 HTTP 状态 201(无响应体),但我需要返回 HTTP 200 和响应体。

我正在使用 WebClient 调用其他服务,对于 201 状态,我正在使用 bodyToMono(Void.class)。 那么如何为我的微服务客户端返回 HTTP 200 响应正文?最佳做法是什么?另外如何为调用返回 HTTP 201 的外部服务的服务编写组件测试?

更新:当前代码如下:

webClient.builder())
        .post()
        .uri("/employee")
        .body(Mono.just(employee), Employee.class)
        .retrieve()
        .onStatus(status -> status.equals(HttpStatus.NOT_FOUND), response -> Mono.just(new NotFoundException("404 occurred", HttpStatus.NOT_FOUND.name())))
        .bodyToMono(Void.class)
        .block();

谢谢

【问题讨论】:

  • 请分享您的代码。
  • ` webClient.builder()) .post() .uri("/employee") .body(Mono.just(employee), Employee.class) .retrieve() .onStatus(status - > status.equals(HttpStatus.NOT_FOUND),响应 -> Mono.just(new NotFoundException("404 发生",HttpStatus.NOT_FOUND.name()))) .bodyToMono(Void.class) .block(); `
  • 请不要在反应式堆栈中使用.block(),除非您有充分的理由。
  • @JoãoDias,正确
  • 请不要在 cmets 中编写代码,您会看到它完全不可读。编辑您的问题以包含代码。

标签: spring-boot spring-webflux spring-webclient


【解决方案1】:

如果我了解您的问题。我想这样解决。

           WebClient
            .builder()
            .build()
            .post()
            .uri("/employee")
            .exchange()
            .flatMap(response -> {
                return response
                        .mutate()
                        .body("success")
                        .build()
                        .bodyToMono(String.class);
            });

【讨论】:

  • 感谢代码 sn-p。在 404 的情况下我也会抛出异常。另外我需要返回一个自定义对象而不是字符串。
  • 请不要在“你去”时加入新的要求,因为这会导致无法回答问题。你问一个问题,得到一个答案。通过包含新要求,可以告诉我们您在提问之前没有进行适当的研究,没有考虑过您的问题,并且您想要的只是“复制粘贴解决方案”
  • @Diego Rocha,感谢代码 sn-p,但是如果我想返回的正文不是字符串类,而是像 MyResponse 这样的自定义类?
猜你喜欢
  • 2017-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-06
  • 1970-01-01
  • 1970-01-01
  • 2017-01-11
  • 1970-01-01
相关资源
最近更新 更多