事务模式
事务具有原子性,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里面的内容,消费者代码还是不变。