Search code examples
springrabbitmqspring-transactionsspring-amqp

Only publish messages to RabbitMQ if database transaction is successful using Spring AMQP


Let's say I have a method that looks something like this:

@Transactional
public void x(Entity entity) {
    // do something
    myRepository.save(entity);
    rabbitTemplate.convertAndSend(new Event1());
    rabbitTemplate.convertAndSend(new Event2());
}

myRepository is using a transaction manager of type org.springframework.orm.jpa.JpaTransactionManager. What I want to do is to make sure that the sending of Event1 and Event2 only happens if myRepository.save(entity) is successful. Does RabbitTransactionManager help here or do I have to implement this myself (for example using a TransactionSynchronizationManager)?


Solution

  • What calls x() ?

    If it's a RabbitMQ listener container thread after receiving some message from rabbit, add the JpaTransactionManager to the container and the rabbit transaction will be synchronized for you.

    If it's some arbitrary thread then you'll need to start a rabbit transaction before calling x and commit it afterwards.

    In either case, your rabbit channel needs to be transactional.