事務模式
事務具有原子性,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裏面的內容,消費者代碼還是不變。