RabbitMQ生产者消息确认Confirm模式,分为普通模式、批量模式和异步模式,本次举例为普通模式。

源码:

 package org.study.confirm4;

 import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import org.junit.Test;
import org.study.utils.ConnectionUtils; import java.io.IOException;
import java.util.concurrent.TimeoutException; /**
* 生产者消息确认(confirm)
*/
public class Sender {
public static final String QUEUE_NAME = "test_confirm_queue"; @Test
public void send() throws IOException, TimeoutException, InterruptedException {
// 获取连接
Connection conn = ConnectionUtils.getConnection();
// 获取通道
Channel channel = conn.createChannel();
//创建队列
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
//每个消费者发送确认消息前,只发送一条消息
channel.basicQos(1);
String msg = "hello rabbitmq!"; //开启confirm模式
channel.confirmSelect(); //发送消息
channel.basicPublish("", QUEUE_NAME, null, msg.getBytes());
System.out.println("[send] msg " + msg); //判断消息返回是否成功
if (channel.waitForConfirms()) {
System.out.println("发送成功!");
} else {
System.out.println("发送失败!");
} channel.close();
conn.close();
}
}