Criando EventListener assíncrono com Kotlin e Spring Boot
O EventListener do Spring permite desacoplar funcionalidades da aplicação. Em vez de um serviço chamar outro diretamente, ele dispara um evento e um ou mais componentes ficam responsáveis por processá-lo.
Esse padrão é muito útil para:
- Atualizar estoque após uma compra
- Enviar e-mails
- Gerar logs
- Criar notificações
- Executar tarefas em background
Habilitando async:
KOTLIN
package mercado_livro
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.scheduling.annotation.EnableAsync
@EnableAsync
@SpringBootApplication
class DemoApplication
fun main(args: Array<String>) {
runApplication<DemoApplication>(*args)
}Criar o evento:
KOTLIN
import mercado_livro.model.PurchaseModel
import org.springframework.context.ApplicationEvent
class PurchaseEvent(
source: Any,
val purchaseModel: PurchaseModel
) : ApplicationEvent(source)Escutar o evento e fazer nossa tarefa:
KOTLIN
package mercado_livro.events.listener
import mercado_livro.events.PurchaseEvent
import mercado_livro.service.PurchaseService
import org.springframework.context.event.EventListener
import org.springframework.scheduling.annotation.Async
import org.springframework.stereotype.Component
import java.util.UUID
@Component
class GenerateNfeListener(
private val purchaseService: PurchaseService
) {
@Async
@EventListener
fun listener(purchaseEvent: PurchaseEvent){
val nfe = UUID.randomUUID().toString()
val purchaseModel=purchaseEvent.purchaseModel.copy(nfe=nfe)
purchaseService.update(purchaseModel)
}
}
0 comentários