Johan
Johan

Reputation: 40500

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)?

Upvotes: 3

Views: 1836

Answers (1)

Gary Russell
Gary Russell

Reputation: 174504

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.

Upvotes: 2

Related Questions