【问题标题】:How to access response body in spring WebClient Retry?如何在 Spring WebClient Retry 中访问响应正文?
【发布时间】:2021-06-02 23:53:03
【问题描述】:

我有一个使用重试的WebClient

webClient.retryWhen(
   Retry.backoff(3, Duration.ofSeconds(3)).filter(this::isRetryable)
)

private boolean isRetryable(Throwable throwable) {
    //TODO how access the json body?
}

问题:如何在重试期间评估 json 响应正文?因为我不仅要根据状态码,还要根据返回的错误内容做出决定。

【问题讨论】:

    标签: java spring spring-webflux project-reactor spring-webclient


    【解决方案1】:

    我假设您正在使用 webclient 的 retrieve() 方法,如果状态代码发出错误信号,它将始终抛出异常。您可能想改用exchangeToMono(),它不会在非 2xx 状态代码上引发异常,而是为您提供随心所欲的响应:

    WebClient.create("http://my-endpoint.abc/endpoint")
            .get()
            .exchangeToMono(cr -> cr.bodyToMono(String.class).map(body -> {
                //return `Mono.error()` here if invalid - you have access to both body + statuscode (via cr.statusCode())
            })).retryWhen(
                Retry.backoff(3, Duration.ofSeconds(3)).filter(e -> e instanceof ExceptionThrownAbove)
            );
    

    【讨论】:

      猜你喜欢
      • 2020-06-29
      • 2020-08-26
      • 1970-01-01
      • 2021-07-01
      • 2018-10-17
      • 2020-07-10
      • 2022-07-06
      • 2020-10-30
      相关资源
      最近更新 更多