Search code examples
javarabbitmqspring-rabbitaxon

Wait 10 seconds after send command in RabbitListener


I have my RabbitListener witch received results of calculations. This is the lot of data so i batched it and next send a command to axon commandGateway. I wonder if it is possible for the listener to wait a few seconds before sending next command. I note that i can't use threadSleep here. It could be work something like this method for every batch

private void myMethod() {
  commandGateway.send(batchedData) 
   //wait 10seconds

Solution

  • What is the reason for having a waiting period here?

    If the reason is to wait before Axon Framework has processed all data present in the command, you can use commandGateway.sendAndWait(Object command, ...) instead. This will make the current thread wait for the command to have been executed.

    If it is a mechanism to batch the data, I would suggest keeping an in-memory List to queue the items, and then sending a command every 10 seconds using the Spring scheduling mechanism. I created a small example in Kotlin to illustrate this:

    @Service
    class CalculationBatcher(
        private val commandGateway: CommandGateway
    ) {
        private val calculationQueue = LinkedList<Any>()
    
        fun queueCalculation(calculation: Any) {
            calculationQueue.add(calculation)
        }
    
        @Scheduled(fixedRate = 10000) // Send every 10 seconds
        @PreDestroy // When destroying the application, send remaining events
        fun sendCalculations() {
            // Use pop here on the LinkedList while having items to prevent threading issues
            val calculationsToSend = LinkedList<Any>()
            while (calculationQueue.isNotEmpty()) {
                calculationsToSend.push(calculationQueue.pop())
            }
            commandGateway.sendAndWait<Any>(MyEventsCommand(calculationsToSend), 10, TimeUnit.SECONDS)
        }
    
        data class MyEventsCommand(val events: List<Any>)
    }
    
    

    I hope this helps. If the reason was something else, let me know!