消息中间件--RabbitMQ学习(十一)---高级特性之Confirm确认消息
Confirm消息确认机制
- 消息的确认,是指生产者投递消息后,如果 Broker收到消息,则会给我们生产者一个应答
- 生产者进行接收应答,用来确定这条消息是否正常的发送到 Broker,这种方式也是消息的可靠性投递的核心保障
确认消息流程图
代码实现:
消费端代码
public class Consumer {
public static void main(String[] args) throws Exception{
//1 创建一个connectionFactory
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("192.168.0.159");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
//2通过连接工场创建连接
Connection connection = connectionFactory.newConnection();
//3通过connection创建channel
Channel channel = connection.createChannel();
String exchangeName = "test_confirm_exchange";
String routingKey = "confirm.#";
channel.exchangeDeclare(exchangeName,"topic",true);
channel.queueDeclare("test_confirm_queue",true,false,false,null);
channel.queueBind("test_confirm_queue",exchangeName,routingKey);
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume("test_confirm_queue",true,consumer);
while (true){
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String msg = new String(delivery.getBody());
System.out.println("消费者:" + msg);
}
}
}
生产端代码
public class Producter {
public static void main(String[] args) throws Exception{
//1 创建一个connectionFactory
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("192.168.0.159");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
//2通过连接工场创建连接
Connection connection = connectionFactory.newConnection();
//3通过connection创建channel
Channel channel = connection.createChannel();
//开启消息的确认模式
channel.confirmSelect();
String exchangeName = "test_confirm_exchange";
String routingKey = "confirm.save";
//发送消息
String msg = "hello";
channel.basicPublish(exchangeName,routingKey,null,msg.getBytes());
//添加确认监听
channel.addConfirmListener(new ConfirmListener() {
@Override
public void handleAck(long l, boolean b) throws IOException {
System.out.println("**success**");
}
@Override
public void handleNack(long l, boolean b) throws IOException {
System.err.println("**error**");
}
});
}
}