RabbitMQ的事务机制

 

RabbitMQ基于AMQP协议。该协议实现了事务机制。其事务主要由三部分组成

txSelect:用户将当前的channel设置为transaction模式

txCommit:用于提交事务

txRollback:用于回滚事务

 

生产者代码演示

public class TxSend {
    private static final String QUEUE_NAME = "test_queue_tx";
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectionUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        String msg = "hello tx message!";

        try {
            channel.txSelect();
            channel.basicPublish("", QUEUE_NAME, null, msg.getBytes());
            // 出错测试
            int xx = 1 / 0;
            System.out.println("send: " + msg);
            channel.txCommit();
        } catch (Exception e) {
            channel.txRollback();
            System.out.println("send message rollback.");
        }

        channel.close();
        connection.close();
    }
}

 

消费者代码演示

public class TxRecv {
    private static final String QUEUE_NAME = "test_queue_tx";
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectionUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        channel.basicConsume(QUEUE_NAME, true, 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])