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"));
}
});
}
}