2

I have to send a message to 2 different queues(queue1 and queue2). However, i want to rollback, if the send is failed for any of the queue(queue1 or queue2).

my source code looks as follows. can anyone through some inputs on this.

  public void sendMessage(final Map<String, String> mapMessage) {

    jmsTemplate.send(queue1, session -> {
      MapMessage message = session.createMapMessage();
      Iterator<Entry<String, String>> it = mapMessage.entrySet().iterator();
      while (it.hasNext()) {
        Map.Entry<String, String> pair = it.next();
        message.setStringProperty(pair.getKey(), pair.getValue());
      }
      message.setJMSRedelivered(true);
      message.setJMSCorrelationID(UUID.randomUUID().toString().replaceAll("-", ""));
      return message;
    });

    jmsTemplate.send(queue2, session -> {
      MapMessage message = session.createMapMessage();
      Iterator<Entry<String, String>> it = mapMessage.entrySet().iterator();
      while (it.hasNext()) {
        Map.Entry<String, String> pair = it.next();
        message.setStringProperty(pair.getKey(), pair.getValue());
      }
      message.setJMSRedelivered(true);
      message.setJMSCorrelationID(UUID.randomUUID().toString().replaceAll("-", ""));
      return message;
    });

    } 
Srinivas KK
  • 151
  • 3
  • 12

1 Answers1

3

Start a transaction before entering the sendMessage method, e.g. with @Transactional - see the Spring Framework Reference Manual.

Gary Russell
  • 166,535
  • 14
  • 146
  • 179
  • Hi Gary, i tried both javax and spring based @Transactional seperately. But, it didn't worked. I changed the code as below. It worked. However, i am wondering, how can we do this Declarative instead of programmatic rollback. Resource PlatformTransactionManager jmsTransactionManager; TransactionStatus status = jmsTransactionManager.getTransaction(new DefaultTransactionDefinition()); After the second jmsTemplate.send, i use commit. In exception block, i used rollback. jmsTransactionManager.commit(status); or jmsTransactionManager.rollback(status); – Srinivas KK Jun 14 '17 at 23:20
  • You must have misconfigured something. Declarative transactions should work fine. Don't try to put code in comments here; virtually unreadable. Edit the question instead. Read the reference manual carefully. If you still can't figure it out, show all of your config. – Gary Russell Jun 15 '17 at 01:38
  • I am able to resolve the issue by adding @Transactional of spring. The missing part was EnableTransactionManagement on the spring boot application class. Thanks Gary – Srinivas KK Jun 15 '17 at 03:26