目录
一、发布确认原理
二、发布确认的策略
(一)开启发布确认的方法
(二)单个确认模式
(三)批量确认模式
(四)异步确认模式
(五)如何处理异步未确认消息
(六)总结
Channel channel = connection.createChannel();
channel.confirmSelect();
public static void publishMessageIndividually() throws Exception {
Channel channel = RabbitMqUtils.getChannel();
channel.confirmSelect();
String queue_name = UUID.randomUUID().toString();
channel.queueDeclare(queue_name, false, false, false, null);
long begin = System.currentTimeMillis();
for (Integer i = 0; i < MESSAGE_COUNT; i++) {
String message = "消息" + i;
channel.basicPublish("", queue_name,null, message.getBytes());
channel.waitForConfirms();
}
long end = System.currentTimeMillis();
System.out.println("发送1000条消息成功,耗时为:" + (end - begin) + "ms");
}
public static void publishMessageBatch() throws Exception {
Channel channel = RabbitMqUtils.getChannel();
channel.confirmSelect();
String queue_name = UUID.randomUUID().toString();
channel.queueDeclare(queue_name, false, false, false, null);
long begin = System.currentTimeMillis();
for (Integer i = 0; i < MESSAGE_COUNT; i++) {
if(i % 100 == 0) channel.waitForConfirms();
String message = "消息" + i;
channel.basicPublish("", queue_name,null, message.getBytes());
}
long end = System.currentTimeMillis();
System.out.println("发送1000条消息成功,耗时为:" + (end - begin) + "ms");
}
public static void publishMessageAsync() throws Exception {
Channel channel = RabbitMqUtils.getChannel();
channel.confirmSelect();
String queue_name = UUID.randomUUID().toString();
channel.queueDeclare(queue_name, false, false, false, null);
ConcurrentSkipListMap outstandingConfirms = new ConcurrentSkipListMap<>();
// 异步监听broker传递过来的消息确认回调通知
// 确认回调消息
ConfirmCallback ackCallback = (deliveryTag, multiple) -> {
if(multiple) {
// 找出该序号前面所有的消息进行清空
ConcurrentNavigableMap confirmed =
outstandingConfirms.headMap(deliveryTag, true);
//清除该部分未确认消息
confirmed.clear();
} else {
// 不是批量的话就清除单条消息
outstandingConfirms.remove(deliveryTag);
}
System.out.println(deliveryTag + "消息发送成功");
};
// 失败回调消息
ConfirmCallback nackCallback = (deliveryTag, multiple) -> {
// 获取序列号并输出
String message = outstandingConfirms.get(deliveryTag);
System.out.println("发布的消息"+message+"未被确认,序列号"+deliveryTag);
};
// 设置确认监听器,两个,一个监听成功的,一个监听失败的
channel.addConfirmListener(ackCallback, nackCallback);
long begin = System.currentTimeMillis();
for (Integer i = 0; i < MESSAGE_COUNT; i++) {
String message = "消息" + i;
channel.basicPublish("", queue_name,null, message.getBytes());
// 获取序列号和消息内容,并且把消息放入队列
outstandingConfirms.put(channel.getNextPublishSeqNo(), message);
}
long end = System.currentTimeMillis();
System.out.println("发送1000条消息成功,耗时为:" + (end - begin) + "ms");
}
单独发布消息同步等待确认,简单,但吞吐量非常有限。批量发布消息批量同步等待确认,简单,合理的吞吐量,一旦出现问题但很难推断出是哪条消息出现了问题。异步处理:最佳性能和资源使用,在出现错误的情况下可以很好地控制,但是实现起来稍微难些
public static void main(String[] args) throws Exception {
// publishMessageIndividually(); // 同步确认发送消息, 耗时为:769ms
// publishMessageBatch(); // 批量确认发送消息,耗时为:84ms
publishMessageAsync(); // 异步确认发送消息, 耗时为:43ms
}