我的目标是使用 Bitronix 交易,我应该使用两种资源:
- 数据库
- 管理系统
我有以下java代码:
package com.mycompany.app;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Enumeration;
import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.QueueBrowser;
import javax.jms.QueueReceiver;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.transaction.TransactionManager;
import javax.transaction.UserTransaction;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerFactory;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.transaction.Transaction;
import org.apache.xbean.spring.context.ClassPathXmlApplicationContext;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.jta.JtaTransactionManager;
import bitronix.tm.BitronixTransactionManager;
import bitronix.tm.TransactionManagerServices;
public class JMSExample {
static String serverUrl = "tcp://localhost:61616"; // values changed
static String userName = "admin";
static String password = "admin";
static TextMessage message;
public static void sendTopicMessage(String topicName, String messageStr) {
Connection connection = null;
try {
BitronixTransactionManager btm = TransactionManagerServices.getTransactionManager();
btm.begin();
System.out.println("Publishing to destination '" + topicName + "'\n");
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(serverUrl);
connection = connectionFactory.createConnection();
Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
Queue queue = session.createQueue(topicName);
Message msg = session.createTextMessage(messageStr);
msg.setJMSCorrelationID("correlationID1");
MessageProducer producer = session.createProducer(queue);
producer.send(msg);
System.out.println("Published message: " + messageStr);
session.commit();
session.close();
connection.close();
btm.rollback();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
JMSExample.sendTopicMessage("test", "Hi");
}
}
当我运行上述程序时,我能够看到队列中的消息。但我希望 JMS 事务与 Bitronix 事务一起嵌套。换句话说,如果 Bitronix 回滚,队列中也不应该有任何消息。