一、介绍
二、事务机制
三、案例
(1)生产者
package cn.qqqking.rabbitmq.tx;
import cn.qqqking.rabbitmq.util.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class TxSend {
public 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 msgString = "hello tx message";
try {
channel.txSelect();
int x = 1/0;
channel.basicPublish("", QUEUE_NAME, null, msgString.getBytes());
channel.txCommit();
System.out.println("send message !" + msgString);
} catch (Exception e) {
channel.txRollback();
System.out.println("send message rollback!");
}
channel.close();
connection.close();
}
}
(2)消费者
package cn.qqqking.rabbitmq.tx;
import cn.qqqking.rabbitmq.util.ConnectionUtils;
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class TxRecv {
public 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);
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String msg = new String(body, "utf-8");
System.out.println("recv :" + new String (body,"utf-8"));
}
};
channel.basicConsume(QUEUE_NAME, true, consumer);
}
}