开启事务:
channel.txSelect();
提交事务:
channel.txCommit();
回滚事务:
channel.txRollback();
缺点:会影响消息处理性能。。。。
二、代码
package com.xiaoxu.simple;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
* 入门工程
*/
public class Producter {
//定义一个消息队列
static final String QUEUE_NAME = "tx";
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = null;
Channel channel = null;
try {
//1、创建连接工厂
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("39.101.204.74");//设置主机地址
connectionFactory.setPort(5672);//端口号
connectionFactory.setUsername("guest");
connectionFactory.setPassword("guest");
//2. 创建连接;(抽取一个获取连接的工具类)
connection = connectionFactory.newConnection();
// 3. 创建频道;
channel = connection.createChannel();
//开启事务
channel.txSelect();
//4. 声明队列;
/**
* 参数1:队列名称
* 参数2:是否定义持久化队列
* 参数3:是否独占本次连接
* 参数4:是否在不使用的时候自动删除队列
* 参数5:队列其它参数
*/
channel.queueDeclare(QUEUE_NAME,true,false,false,null);
// 5. 创建消费者(接收消息并处理消息);
String msg = "我是一个消息。。。。。";
// 6. 监听队列
/**
* 参数1:交换机名称,如果没有指定则使用默认Default Exchage
* 参数2:路由key,简单模式可以传递队列名称
* 参数3:消息其它属性
* 参数4:消息内容
*/
channel.basicPublish("",QUEUE_NAME,null,msg.getBytes());
System.out.println(msg);
int i = 1/0;
channel.txCommit();
} catch (TimeoutException | IOException e) {
e.printStackTrace();
channel.txRollback();
}
//7、关闭资源
channel.close();
connection.close();
}
}
三、结果