RabbitMQ(七)发布者确认机制--事务

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

}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值