开启事务:
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. 声明队列; channel.queueDeclare(QUEUE_NAME,true,false,false,null); // 5. 创建消费者(接收消息并处理消息); String msg = "我是一个消息。。。。。"; // 6. 监听队列 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(); } }三、结果
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)