在本文中,你将了解如何选择性地使用 JMS 事务。在 JMS 中,你可以选择控制一个会话的原子操作。每个会话都支持一系列事务。每个事务将一组生成或使用的消息分组为一个原子工作单元。确保你已经理解了 JMS 中的消息确认

事务提交时 - (jmsContext.commit())

  • 其产生的消息被发送。
  • 对于消费者来说,其消费的消息被确认(从 JMS 服务器中删除)。

如果事务回滚 - (jmsContext.rollback())

  • 其产生的消息被销毁。
  • 其消费的消息被恢复(不会从 JMS 服务器中删除)。

让我们看一下代码示例,以更好地理解其功能。链接到 GitHub 代码库

package lab07.transactons.example;
import labxx.common.settings.CommonSettings;
import javax.jms.*;
public class TransactionExample {
public static void main(String[] args) {
ConnectionFactory connectionFactory = CommonSettings.getConnectionFactory();
Queue queue = CommonSettings.getDefaultQueue();
Thread messageProducer = new Thread() {
public void run() {
try (JMSContext jmsContext = connectionFactory.createContext(JMSContext.SESSION_TRANSACTED)) {
JMSProducer producer = jmsContext.createProducer();
producer.send(queue, "This is a SESSION_TRANSACTED message");
producer.send(queue, "Sending another message");
// Try commenting out commit(); the message will not be delivered before the transaction commits
Thread.sleep(5000);
jmsContext.commit(); // Important
// The next message is never delivered because rollback() is called
producer.send(queue, "This message will not be delivered");
jmsContext.rollback();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread messageConsumer = new Thread() {
public void run() {
try (JMSContext jmsContext = connectionFactory.createContext(JMSContext.SESSION_TRANSACTED)) {
JMSConsumer consumer = jmsContext.createConsumer(queue);
consumer.setMessageListener(msg -> {
try {
System.out.println(msg.getBody(String.class));
} catch (JMSException e) {
e.printStackTrace();
}
});
jmsContext.commit();
Thread.sleep(6000);
consumer.close();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
messageProducer.start();
messageConsumer.start();
}
}

输出

This is a SESSION_TRANSACTED message
Sending another message

当你在 IDE 中运行代码时,你会注意到 5 秒后终端上只打印了 2 条消息,如上所示。在消息生产者的事务提交之前,消费者不会收到任何消息。由于调用了事务回滚,消费者永远不会收到第 3 条消息(第 24 行)。

正如你注意到的,JMS 会话是使用 JMSContext.SESSION_TRANSACTED 进行事务处理的。

当你想要控制发送的消息和传递到的消息时,可以使用 JMS 事务。

本文为学习目的的个人翻译,译文仅供参考。

原文链接:JMS Transactions in Action

版权归原作者或原刊登方所有。本文为非官方译本;如有不妥,请联系删除。