1 year ago

#331820

test-img

Renata

Kotlin JobCancellationException in Spring REST Client with async call

From time to time Spring REST function fails with: "kotlinx.coroutines.JobCancellationException: MonoCoroutine was cancelled". It is suspend function which calls another service using spring-webflux client. There are multiple suspend functions in my rest class. Looks like this problem occurs when multiple requests arrive to the same time. But may be not :-) Application runs on Netty server.

Example:

@GetMapping("/customer/{id}")
suspend fun getCustomer(@PathVariable @NotBlank id: String): ResponseEntity<CustomerResponse> =
    withContext(MDCContext()) {
        ResponseEntity.status(HttpStatus.OK)
            .body(customerService.aggregateCustomer(id))
    }

Service call:

suspend fun executeServiceCall(vararg urlData: Input) = webClient
        .get()
        .uri(properties.url, *urlData)
        .retrieve()
        .bodyToMono(responseTypeRef)
        .retryWhen(
            Retry.fixedDelay(properties.retryCount, properties.retryBackoff)
                .onRetryExhaustedThrow { _, retrySignal ->
                    handleRetryException(retrySignal)
                }
                .filter { it is ReadTimeoutException || it is ConnectTimeoutException }
        )
        .onErrorMap {
            // throw exception
        }
        .awaitFirstOrNull()

Part of Stack Trace:

Caused by: kotlinx.coroutines.JobCancellationException: MonoCoroutine was cancelled; job="coroutine#1":MonoCoroutine{Cancelling}@650774ce
    at kotlinx.coroutines.JobSupport.cancel(JobSupport.kt:1578)
    at kotlinx.coroutines.Job$DefaultImpls.cancel$default(Job.kt:183)
    at kotlinx.coroutines.reactor.MonoCoroutine.dispose(Mono.kt:122)
    at reactor.core.publisher.FluxCreate$SinkDisposable.dispose(FluxCreate.java:1033)
    at reactor.core.publisher.MonoCreate$DefaultMonoSink.disposeResource(MonoCreate.java:313)
    at reactor.core.publisher.MonoCreate$DefaultMonoSink.cancel(MonoCreate.java:300)

spring

kotlin

spring-webflux

kotlin-coroutines

reactor-netty

0 Answers

Your Answer

Accepted video resources