生产端Confirm消息确认机制
什么是消息确认
消息确认,是指生产者投递消息后,如果Broker收到消息,则会给我们生产者一个应答。生产者进行接受应答,用来确认消息这条是否正常发送到Broker,这种方式也是消息的可靠性投递的核心保障!
如何实现Confirm确认消息
- 在channel上开启确认模式:
channel.confirmSelect()
; - 在channel上添加监听:
addConfirmListener
,监听成功和失败返回的结果,根据结果对消息重发送或记录日志等后续处理。
代码实现
producer
package com.wyg.rabbitmq.javaclient.confirm;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
/**
* confirm消息确认机制
*
* @author wyg0405@gmail.com
* @date 2019-11-22 13:25
* @since JDK1.8
* @version V1.0
*/
public class Producer {
private static final String HOST = "localhost";
private static final int PORT = 5672;
private static final String USERNAME = "guest";
private static final String PASSWORD = "guest";
private static final String EXCHANGE = "test_confirm_exchange";
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(HOST);
factory.setVirtualHost("/");
factory.setPort(PORT);
factory.setUsername(USERNAME);
factory.setPassword(PASSWORD);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE, "topic");
// 开启confirm确认模式
channel.confirmSelect();
// 添加监听
channel.addConfirmListener(new ConfirmListener() {
@Override
public void handleAck(long deliveryTag, boolean multiple) throws IOException {
System.out.println("---消息投递成功,deliveryTag:" + deliveryTag);
}
@Override
public void handleNack(long deliveryTag, boolean multiple) throws IOException {
System.out.println("---消息投递失败,deliveryTag:" + deliveryTag);
}
});
String msg1 = "这是一条confirm确认消息save";
channel.basicPublish(EXCHANGE, "confirm.save", null, msg1.getBytes("UTF-8"));
String msg2 = "这是一条confirm确认消息abc";
channel.basicPublish(EXCHANGE, "confirm.abc", null, msg2.getBytes("UTF-8"));
}
// 注意,因为要等待broker的confirm消息,暂时不关闭channel和connection
}
运行结果