How to run a background task in Spring using coroutines in a reactive application while properly inheriting the reactor context

Viewed 471

I would like to perform an async task in Spring (similar to @Async) using coroutines.

I've tried the following:

@PostMapping("/async")
suspend fun post(): ResponseEntity<Unit> {
    logger.info { "Received request" }

    val context = coroutineContext
    logger.info { "coroutineContext=${context}" }

    CoroutineScope(Dispatchers.Default + coroutineContext).launch {
        delay(5000)
        logger.info { "io + context, 5000ms" }
    }

    CoroutineScope(Dispatchers.IO + coroutineContext).launch {
        delay(5000)
        logger.info { "default + context, 5000ms" }
    }

    logger.info { "Returning response" }
    return ResponseEntity.accepted()
            .build()
}

Spring seems to be waiting for the coroutine to finish before returning the response.

I would also like to inherit the context so I can inherit trace information while inside the coroutine (I am using sleuth).

0 Answers
Related