Message driven beans and transactions

166 Views Asked by At

I know there are a lot a of questions about message driven beans and transactions, however I've not been able to find the answer to (what I think) must be a common scenario.

I have a service that can be called to send emails. When it's called, it creates the email record in a table and then pushes the ID to ActiveMQ for processing. All good so far, however the queue picks the ID up and tries to send the email before the transaction is committed and the email is not the in database.

The service itself is transactional, but it may also be part of a a larger transaction.

What is the best way to handle this scenario? I'm using a Thread.sleep at the moment in the Consumer which works; however this feels dirty...

(I'm not using Spring)

2

There are 2 best solutions below

5
On BEST ANSWER

You can have a transaction that does the usual stuff plus inserts emails in a table. Don't send the mails in the transction.

Then afterward (the transaction succeeds) have a process clear the email table by forwarding to the queueing service.

1
On

Maybe doing a flush right after persisting the mail would help ?

I'm actually curious to see how this could be fixed, since we have a similar problem in our application at work.