RabbitMQ——事務

事務模式

事務具有原子性,MQ發送消息也應當具有原子性,下面介紹一下事務模式:

send

public class Send {

    private static final String QUEUE_NAME = "simple_mq";

    public static void main(String[] args) throws IOException, TimeoutException {

        Connection connection = RabbitConnection.getConnection();

        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        String message = "hello simple_mq";

        try {
            channel.txSelect();
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
            channel.txCommit();
        } catch (IOException e) {
            channel.txRollback();
            System.out.println("回滾~~");
        }
        System.out.println(" [x] Sent.......... '" + message + "'");
        channel.close();
        connection.close();
    }
}

和我們最初寫的簡單隊列相比,就加了try裏面的內容,消費者代碼還是不變。


confirm模式

發佈了138 篇原創文章 · 獲贊 42 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章