spring 如何使用onRetryExhaustedThrow返回原始HttpStatusCode和消息?

zyfwsgd6  于 2023-04-28  发布在  Spring
关注(0)|答案(1)|浏览(144)

我试图创建一个自定义重试方法,但我不明白它是如何工作的。
事实上,我只想再试几次,然后,如果所有尝试都失败了,返回一个异常,其中包含最后一个http状态代码、http状态消息和响应正文。
Webflux可以做到这一点吗?
下面是我的代码:

private RetryBackoffSpec retryServerError() {
        return Retry.backoff(3, Duration.of(100, ChronoUnit.MILLIS))
                    .filter(this::isServerError)
                    .onRetryExhaustedThrow((retryBackoffSpec, retrySignal) -> new HttpServerErrorException(HttpStatus.SERVICE_UNAVAILABLE, "an error message"));
    }

    private boolean isServerError(Throwable throwable) {
        return throwable instanceof HttpServerErrorException;
    }

    public void ResponseEntity<U> post(Class<Void> responseClass, Function<UriBuilder, URI> uri, MyBodyObject body) throws WebClientException, RestClientResponseException {
        return this.getWebClientBuilder()
                   .build()
                   .post()
                   .uri(uri)
                   .body(BodyInserters.fromValue(body))
                   .retrieve()
                   .toEntity(responseClass)
                   .retryWhen(retryServerError())
                   .block();
    }

谢谢你的帮助!

e3bfsja2

e3bfsja21#

retrySignal允许您获取导致重试的异常。

private RetryBackoffSpec retryServerError() {
    return Retry.backoff(3, Duration.of(100, ChronoUnit.MILLIS))
        .filter(this::isServerError)
        .onRetryExhaustedThrow((retryBackoffSpec, retrySignal) -> {
          HttpServerErrorException ex = (HttpServerErrorException) retrySignal.failure();
            HttpStatus statusCode = webException.getStatusCode();
            String responseBodyAsString = webException.getResponseBodyAsString();
            //whatever you want to do with it
          
        });
  }

相关问题