消息确认机制
1.消息的确认,是指生产者投递消息后,如果Broker接受到消息,则会给生产者一个应答。
2.生产者进行接受应答,用来确认这条消息是否正常的发送到Broker,这种方式也是消息的可靠性投递的核心保障。
image.png
消息确认实现
1.在channel上开启确认模式:channel.confirmSelect()。
2.在channel上添加监听,addConfirmListener,监听成功和失败的返回结果。根据具体的结果对消息进行重新发送或记录日子等后续处理。
public class Producer {
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.6.99");
factory.setPort(5672);
factory.setVirtualHost("/");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
//指定消息的确认模式
channel.confirmSelect();
channel.basicPublish("exchange2","",null,"hello world".getBytes());
//添加监听
channel.addConfirmListener(new ConfirmListener() {
@Override
public void handleAck(long deliveryTag, boolean multiple) throws IOException {
System.out.println("handleAck");
}
@Override
public void handleNack(long deliveryTag, boolean multiple) throws IOException {
System.out.println("handleNack");
}
});
}
}
public class Consumer1 {
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.6.99");
factory.setPort(5672);
factory.setVirtualHost("/");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare("exchange2","topic",true);
channel.queueDeclare("queueName2", true, false, false, null);
channel.queueBind("queueName2","exchange2","");
QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
channel.basicConsume("queueName2",true,queueingConsumer);
while (true){
QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" Received '" + message + "'");
}
}
}
网友评论