Home > Blockchain >  How to run EventListener in background in a Spring/Kotlin Coroutines project
How to run EventListener in background in a Spring/Kotlin Coroutines project

Time:05-13

Currently I am using Spring 2.6.7 WebFlux/Kotlin Coroutines stack in a project.

In a Java project, it is easy to run the EventListener in an async thread like this.

@Component
class MyEventListener{
   
   @EventListener
   @Async
   void onOrderPlaced(event) {
   }
}

But in the Kotlin Coroutines, the @Async does not work, and the EventListener dose not accept a suspend fun.

@Component
class MyEventListener{
   
   @EventListener
   @Async //does not work
   fun onOrderPlaced(event) {
   }

   @EventListener
   suspend fun onOrderPlaced(event) { // `suspend` does not work
   }

   @EventListener
   fun onOrderPlaced(event) = runBlocking { // works, but did not run this continuation in background like `@Async`
   }
}

CodePudding user response:

One way I can think is to use application specific coroutine context in your application configuration.

@Configuration
class ApplicationConfiguration {

    private val applicationCoroutineScope = CoroutineScope(SupervisorJob()   Dispatchers.IO)

    @Bean
    fun applicationScope(): CoroutineScope = applicationCoroutineScope
}

and then

@Component
class MyEventListener(private val applicationScope: CoroutineScope) {
   
    @EventListener
    fun onOrderPlaced(event) {

        applicationScope.launch {

            // Do something with the event.
        }
    }
}

Something around that line should work for your use case.

  • Related