简体   繁体   English

Spring WebClient:使用 WebFlux.fn + reactor-addons 重试

[英]Spring WebClient: Retry with WebFlux.fn + reactor-addons

I'm trying to add a conditional Retry for WebClient with Kotlin Coroutines + WebFlux.fn + reactor-addons:我正在尝试使用 Kotlin Coroutines + WebFlux.fn + reactor-addons 为WebClient添加条件重试:

suspend fun ClientResponse.asResponse(): ServerResponse =
    status(statusCode())
        .headers { headerConsumer -> headerConsumer.addAll(headers().asHttpHeaders()) }
        .body(bodyToMono(DataBuffer::class.java), DataBuffer::class.java)
        .retryWhen { 
            Retry.onlyIf { ctx: RetryContext<Throwable> -> (ctx.exception() as? WebClientResponseException)?.statusCode in retryableErrorCodes }
                .exponentialBackoff(ofSeconds(1), ofSeconds(5))
                .retryMax(3)
                .doOnRetry { log.error("Retry for {}", it.exception()) }
        )
        .awaitSingle()

also adding a condition before the retry在重试之前还添加了一个条件

if (statusCode().isError) {
        body(
            BodyInserters.fromPublisher(
                Mono.error(StatusCodeError(status = statusCode())),
                StatusCodeException::class.java
            )
        )
    } else {
        body(bodyToMono(DataBuffer::class.java), DataBuffer::class.java)
    }

Call looks like:呼叫看起来像:

suspend fun request(): ServerResponse =
           webClient/*...*/
                    .awaitExchange()
                    .asResponse()

This spring webclient: retry with backoff on specific error gave me the hint to answer the question: This spring webclient: retry with backoff on specific error给了我回答问题的提示:

.awaitExchange() returns the ClientResponse and not Mono<ClientReponse> This means my retry was acting on bodyToMono instead of the operation of exchange() . .awaitExchange()返回ClientResponse而不是Mono<ClientReponse>这意味着我的重试作用于bodyToMono而不是exchange()的操作。

The solution now looks like解决方案现在看起来像

suspend fun Mono<ClientResponse>.asResponse(): ServerResponse =
    flatMap {
        if (it.statusCode().isError) {
            Mono.error(StatusCodeException(status = it.statusCode()))
        } else {
            it.asResponse()
        }
    }.retryWhen(
        Retry.onlyIf { ctx: RetryContext<Throwable> ->
            (ctx.exception() as? StatusCodeException)?.shouldRetry() ?: false
        }
            .exponentialBackoff(ofSeconds(1), ofSeconds(5))
            .retryMax(3)
            .doOnRetry { log.error { it.exception() } }
    ).awaitSingle()

private fun ClientResponse.asResponse(): Mono<ServerResponse> =
    status(statusCode())
        .headers { headerConsumer -> headerConsumer.addAll(headers().asHttpHeaders()) }
        .body(bodyToMono(DataBuffer::class.java), DataBuffer::class.java)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM