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

允我心安 提交于 2020-04-18 03:49:07

问题


I'm trying to add a conditional Retry for WebClient with Kotlin Coroutines + WebFlux.fn + reactor-addons:

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()

回答1:


This spring webclient: retry with backoff on specific error gave me the hint to answer the question:

.awaitExchange() returns the ClientResponse and not Mono<ClientReponse> This means my retry was acting on bodyToMono instead of the operation of 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)


来源:https://stackoverflow.com/questions/60827183/spring-webclient-retry-with-webflux-fn-reactor-addons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!