0

Instead of sending single message in a transaction:

jmsTemplate.convertAndSend(message);

How can I send multiple jms messages in a single transaction?

Is there an example I can loot at?

breaktop
  • 1,899
  • 4
  • 37
  • 58
  • Do you mean "transaction" instead of "translation"? – luk2302 Mar 28 '18 at 14:59
  • Have you read through https://docs.spring.io/spring/docs/5.0.0.BUILD-SNAPSHOT/spring-framework-reference/html/jms.html#jms-tx ? – luk2302 Mar 28 '18 at 15:00
  • @luk2302 I've read that link but couldn't understand how I can use I can send multiple messages in a single transaction. It would be good to see an example of how to send send multiple messages in a single transaction and how to see if the transaction is working – breaktop Mar 28 '18 at 15:22

1 Answers1

2

Start the transaction before calling the template

@Transactional
public void doSends() {
    template.convertAndSend(...)
    ...
    template.convertAndSend(...)
}

The transaction commits when the method exits. See the Spring documentation about transactions.

Or, use one the of the template's execute() methods and do the sends in the callback.

Gary Russell
  • 166,535
  • 14
  • 146
  • 179
  • Ho would you test that multiple messages is being sent in a single transaction? – breaktop Mar 28 '18 at 15:39
  • Test in what way? – Gary Russell Mar 28 '18 at 15:47
  • I have two classes, one with annotation ```@Configuration``` and ```@EnableTransactionManagement``` which defines all the config. The other class has a method that is annotated ```@Transactional``` and has the transaction code ```template.convertAndSend(...)```. Is it worth testing to see if it works i.e. multiple messages are send in a single transaction – breaktop Mar 29 '18 at 07:58
  • `>is it worth...` - only you can decide that. There's a spectrum; at the very least, to verify your configuration, you can turn on trace logging for `org.springframework` and look at the transaction activity. Or, you can do the whole monty and write a test that mocks or spies on the JMS `Session` and `verify()` that the `commit()` was called only once. – Gary Russell Mar 29 '18 at 12:46
  • For Testing, you can send two message to two different queue. On the receiver side create two message listener with setSessionTransacted(true). In one of the receiver throw RunTimeException. This should cause the transaction to rollback. Now go to your JMS Provider console and check both the messages should be in queue due to transaction rollback. – Mahesh Bhuva Jun 22 '20 at 06:35
  • No; the producer and consumer transactions are independent; only the failed message will be rolled back. – Gary Russell Jun 22 '20 at 14:01