07. RabbitMQ message success confirmation mechanism
-
In actual scenarios, the messages sent by some producers must be guaranteed to be successfully sent to the message queue, so how to ensure successful delivery?
-
- transaction mechanism
- Release confirmation mechanism
1. Transaction mechanism
-
A way to ensure the successful delivery of messages provided by the AMQP protocol, enabling transactional mode through the channel
-
And use the three methods of the channel to send messages in a transactional manner. If the sending fails, the transaction is rolled back through exception handling to ensure the successful delivery of the message.
-
- channel.txSelect(): open transaction
- channel.txCommit() : Commit the transaction
-
- channel.txRollback() : rollback the transaction
-
Spring has encapsulated the above three methods, so we can only use the original code demonstration
2. Producer code
package trascation;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import util.ConnectionUtil;
/**
* @author WeiHong
* @date 2021 - 09 - 15 19:59
*/
public class Sender {
public static void main(String[] args) throws Exception {
//1.获取连接
Connection connection = ConnectionUtil.getConnection();
//2.在连接中创建信道
Channel channel = connection.createChannel();
//3.声明路由
channel.exchangeDeclare("trascation_exchange_topic","topic");
//4.发送消息
channel.txSelect(); //开启事务
try {
channel.basicPublish("trascation_exchange_topic","user.weihong",null,"商品1-降价".getBytes());
System.out.println(3/0);//模拟异常
channel.basicPublish("trascation_exchange_topic","user.libai",null,"商品2-降价".getBytes());
channel.basicPublish("trascation_exchange_topic","users123.wangwu",null,"商品3-降价".getBytes());
System.out.println("生产者已发送!");
channel.txCommit();//事务提交
}catch(Exception e){
System.out.println("由于系统异常,消息全部撤回!");
channel.txRollback();//事务回滚
e.printStackTrace();
}finally {
channel.close();
connection.close();
}
}
}
3. Consumer Code
package trascation;
import com.rabbitmq.client.*;
import util.ConnectionUtil;
import java.io.IOException;
/**
* @author WeiHong
* @date 2021 - 09 - 15 20:10
*/
public class Recer1 {
public static void main(String[] args) throws Exception {
//1.创建连接
Connection connection = ConnectionUtil.getConnection();
//2.在连接中创建信道
Channel channel = connection.createChannel();
//3.声明队列
channel.queueDeclare("trscation_queue_topic1",false,false,false,null);
//4.绑定路由
channel.queueBind("trscation_queue_topic1","trascation_exchange_topic","user.#");
//5.定义内部类接收消息
DefaultConsumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String msg = new String(body);
System.out.println("消费者1="+msg);
}
};
channel.basicConsume("trscation_queue_topic1",true,consumer);
}
}