消息的确认是指生产者投递消息后,如果Broker收到消息,则会给我们生产者一个应答。生产者进行接受应答,用来确认这条消息是否正常的发送到Broker,这种方式也是消息投靠信投递的核心保障!
如何实现Confirm确认消息?
第一步:在channel上开启确认模式:channel.confirmSelect()
第二部:在channel上添加监听:addConfirmListener,监听成功和失败的返回结果,根据具体的结果对消息进行重新发送、或记录日志等后续处理!
生产者代码
package com.star.movie.confirm;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.star.movie.common.Constant;
import java.io.IOException;
/**
* @Description:生产者
* @author:kaili
* @Date: 2019-04-22 17:23
**/
public class ConfirmProducer {
public static void main(String[] args) throws Exception{
//2获取Connection
Connection connection = Constant.getConnection();
//3 通过Connection创建一个新的Channel
Channel channel = connection.createChannel();
//4 指定我们的消息投递模式: 消息的确认模式
channel.confirmSelect();
//5 发送一条消息
String exchangeName = "test_confirm_exchange";
String routingKey = "confirm.save";
String msg = "Hello RabbitMQ Send confirm message!";
channel.basicPublish(exchangeName,routingKey,null,msg.getBytes());
//6 添加一个确认监听
channel.addConfirmListener(new ConfirmListener() {
@Override
public void handleAck(long deliveryTag, boolean multiple) throws IOException {
System.err.println("-------ack!-----------");
}
@Override
public void handleNack(long deliveryTag, boolean multiple) throws IOException {
System.err.println("-------no ack!-----------");
}
});
}
}
生产者代码
package com.star.movie.confirm;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.QueueingConsumer;
import com.star.movie.common.Constant;
import com.rabbitmq.client.QueueingConsumer.Delivery;
/**
* @Description:消费者
* @author:kaili
* @Date: 2019-04-22 17:28
**/
public class ConfirmConsumer {
public static void main(String[] args) throws Exception{
//2 获取Connection
Connection connection = Constant.getConnection();
//3 通过Connection创建一个新的Channel
Channel channel = connection.createChannel();
String exchangeName = "test_confirm_exchange";
String routingKey = "confirm.#";
String queueName = "test_confirm_queue";
//4 声明交换机和队列 然后进行绑定设置, 最后制定路由Key
channel.exchangeDeclare(exchangeName, "topic", true);
channel.queueDeclare(queueName, true, false, false, null);
channel.queueBind(queueName, exchangeName, routingKey);
//5 创建消费者
QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
channel.basicConsume(queueName, true, queueingConsumer);
while(true){
Delivery delivery = queueingConsumer.nextDelivery();
String msg = new String(delivery.getBody());
System.err.println("消费端: " + msg);
}
}
}
step 1 启动消费者代码
生成test_confirm_exchange交换机绑定test_confirm_queue队列
step 2 启动生产者代码
观察生产者控制台,打印了投递消息成功的ack消息
观察消费者控制台
消费者将队列的消息消费完成