1.概述
在rabbitmq中,我们可以通过持久化数据解决rabbitmq服务器异常的数据丢失问题。
生产者将消息发送出去后,消息到底有没有到达rabbitmq服务器,默认情况是不知道的。
这就涉及到了发布者的两种确认方式:
- AMQP实现的事务机制
- Confirm模式
2.事务机制
channel.txSelect() //用户将当前channel是设置成transaction模式
channel.txCommit() //提交事务
channel.txRollback() //回滚事务
2.1 生产者
public class TxSender {
private final static String queue_name = "test_queue_tx";
public static void main(String[] args) throws Exception {
Connection connection = ConnectionUtil.getConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(queue_name,false,false,false,null);
try {
String msg = "hello tx msg!";
channel.txSelect(); //将当前channel是设置成transaction模式
// int i = 1/0;
channel.basicPublish("",queue_name,null,msg.getBytes());
System.out.println("send to msg:"+msg);
channel.txCommit();//提交事务
} catch (Exception e) {
channel.txRollback(); //回滚事务
System.out.println("send to msg error rollback");
e.printStackTrace();
}finally {
channel.close();
connection.close();
}
}
}
2.2 消费者
public class TxRecv {
private final static String queue_name = "test_queue_tx";
public static void main(String[] args) throws Exception {
Connection connection = ConnectionUtil.getConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(queue_name,false,false,false,null);
channel.basicConsume(queue_name,new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("recv tx msg:"+new String(body,"utf-8"));
}
});
}
}
本文深入探讨了RabbitMQ中的事务机制,包括如何通过事务确保消息传递的可靠性,以及在生产者和消费者端的具体实现过程。通过示例代码展示了事务的开启、提交和回滚操作,帮助读者理解如何在RabbitMQ中使用事务来增强消息处理的安全性和一致性。
2674

被折叠的 条评论
为什么被折叠?



