发布确认

This commit is contained in:
2021-11-30 12:17:05 +08:00
parent 8e0f4a9a9b
commit 605eeb95d2
4 changed files with 359 additions and 2 deletions

View File

@@ -0,0 +1,143 @@
package io.jiulinxiri.rabbitmq.four;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmCallback;
import io.jiulinxiri.rabbitmq.utils.RabbitMqUtils;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.TimeoutException;
/**
* 发布确认模式
* 1. 单个确认发布
* 2. 批量确认发布
* 3. 异步确认发布
*/
public class ConfirmMessage {
public static final int MESSAGE_COUNT = 1000;
public static void main(String[] args) throws Exception {
// 发布1000个单独消息耗时45591ms
// ConfirmMessage.publicMessageIndividually();
// ConfirmMessage.publicMessageBatch();
ConfirmMessage.publicMessageAsync();
}
/**
* 发送单个消息
*
* @throws IOException
* @throws TimeoutException
* @throws InterruptedException
*/
public static void publicMessageIndividually() throws IOException, TimeoutException, InterruptedException {
Channel channel = RabbitMqUtils.getChannel();
// Queue Name
String queueName = UUID.randomUUID().toString();
channel.queueDeclare(queueName, true, false,false, null);
// 开启发布确认
channel.confirmSelect();
// 开始时间
long begin = System.currentTimeMillis();
// 批量发送消息
for (int i = 0; i < MESSAGE_COUNT; i++) {
String message = i + "";
channel.basicPublish("", queueName, null, message.getBytes());
// 单个消息马上发布确认
boolean flag = channel.waitForConfirms();
if (flag) {
System.out.println("消息发动成功");
}
}
// 结束时间
long end = System.currentTimeMillis();
System.out.println("发布" + MESSAGE_COUNT + "个单独消息,耗时:" + (end - begin) + "ms");
}
/**
* 批量发布确认
*/
public static void publicMessageBatch() throws Exception {
Channel channel = RabbitMqUtils.getChannel();
// Queue Name
String queueName = UUID.randomUUID().toString();
channel.queueDeclare(queueName, true, false,false, null);
// 开启发布确认
channel.confirmSelect();
// 开始时间
long begin = System.currentTimeMillis();
// 批量确认长度
int batchSize = 1000;
for (int i = 0; i < MESSAGE_COUNT; i++) {
String message = i + "";
channel.basicPublish("", queueName, null, message.getBytes());
if (i % batchSize == 0) {
// 确认
channel.waitForConfirms();
}
}
// 结束时间
long end = System.currentTimeMillis();
System.out.println("发布" + MESSAGE_COUNT + "个消息每 100 次确认一次,耗时:" + (end - begin) + "ms");
}
/**
* 异步确认
* 耗时33ms
* @throws Exception
*/
public static void publicMessageAsync() throws Exception {
Channel channel = RabbitMqUtils.getChannel();
// Queue Name
String queueName = UUID.randomUUID().toString();
channel.queueDeclare(queueName, true, false,false, null);
// 开启发布确认
channel.confirmSelect();
// 线程安全的哈希表,适用于高并发的场景
/**
* 将序号与消息关联
* 轻松批量删除确认消息
* 支持高并发
*/
ConcurrentSkipListMap<Long, String> map = new ConcurrentSkipListMap<Long, String>();
// 开始时间
long begin = System.currentTimeMillis();
// 消息确认成功
ConfirmCallback ackConfirm = (deliveryTag, multiple) -> {
if (multiple) {
// 2.删除已确认的消息,剩下的就是未确认的
ConcurrentNavigableMap<Long, String> confirmed = map.headMap(deliveryTag);
} else {
map.remove(deliveryTag);
}
System.out.println("确认的消息:" + deliveryTag);
};
// 消息确认失败
ConfirmCallback nackConfirm = (deliveryTag, multiple) -> {
String s = map.get(deliveryTag);
System.out.println("未确认的消息: " + s + " 消息Tag: " + deliveryTag);
};
// 消息监听器,检测消息的成功与失败
channel.addConfirmListener(ackConfirm, nackConfirm);
for (int i = 0; i < MESSAGE_COUNT; i++) {
String message = "消息:" + i;
channel.basicPublish("", queueName, null, message.getBytes());
// 1.记录发送的所有消息
map.put(channel.getNextPublishSeqNo(), message);
}
// 结束时间
long end = System.currentTimeMillis();
System.out.println("发布" + MESSAGE_COUNT + "个消息异步确认,耗时:" + (end - begin) + "ms");
}
}

View File

@@ -0,0 +1,206 @@
### 发布确认
生产者将信道设置成 confirm 模式,一旦信道进入 confirm 模式,所有在该信道上面发布的
消息都将会被指派一个唯一的 ID(从 1 开始)一旦消息被投递到所有匹配的队列之后broker
就会发送一个确认给生产者(包含消息的唯一 ID),这就使得生产者知道消息已经正确到达目的队
列了如果消息和队列是可持久化的那么确认消息会在将消息写入磁盘之后发出broker 回传
给生产者的确认消息中 delivery-tag 域包含了确认消息的序列号,此外 broker 也可以设置
basic.ack 的 multiple 域,表示到这个序列号之前的所有消息都已经得到了处理。
confirm 模式最大的好处在于他是异步的,一旦发布一条消息,生产者应用程序就可以在等信
道返回确认的同时继续发送下一条消息,当消息最终得到确认之后,生产者应用便可以通过回调
方法来处理该确认消息,如果 RabbitMQ 因为自身内部错误导致消息丢失,就会发送一条 nack消
息,生产者应用程序同样可以在回调方法中处理该 nack 消息。
### 发布确认策略
#### 开启发布确认
发布确认默认是没有开启的,如果要开启需要调用方法 confirmSelect每当你要想使用发布
确认,都需要在 channel上调用该方法
```java
// 开启发布确认
channel.confirmSelect();
```
#### 单个确认发布
这是一种简单的确认方式,它是一种同步确认发布的方式,也就是发布一个消息之后只有它
被确认发布,后续的消息才能继续发布,waitForConfirmsOrDie(long)这个方法只有在消息被确认
的时候才返回,如果在指定时间范围内这个消息没有被确认那么它将抛出异常。
这种确认方式有一个最大的缺点就是:发布速度特别的慢,因为如果没有确认发布的消息就会
阻塞所有后续消息的发布,这种方式最多提供每秒不超过数百条发布消息的吞吐量。
```java
// 发布1000个单独消息耗时45591ms
public static void publicMessageIndividually() throws IOException, TimeoutException, InterruptedException {
Channel channel = RabbitMqUtils.getChannel();
// Queue Name
String queueName = UUID.randomUUID().toString();
channel.queueDeclare(queueName, true, false,false, null);
// 开启发布确认
channel.confirmSelect();
// 开始时间
long begin = System.currentTimeMillis();
// 批量发送消息
for (int i = 0; i < MESSAGE_COUNT; i++) {
String message = i + "";
channel.basicPublish("", queueName, null, message.getBytes());
// 单个消息马上发布确认
boolean flag = channel.waitForConfirms();
if (flag) {
System.out.println("消息发动成功");
}
}
// 结束时间
long end = System.currentTimeMillis();
System.out.println("发布" + MESSAGE_COUNT + "个单独消息,耗时:" + (end - begin) + "ms");
}
```
#### 批量发布确认
与单个等待确认消息相比,先发布一批消息然后一起确认可以极大地
提高吞吐量,当然这种方式的缺点就是:当发生故障导致发布出现问题时,不知道是哪个消息出现
问题了,我们必须将整个批处理保存在内存中,以记录重要的信息而后重新发布消息。当然这种
方案仍然是同步的,也一样阻塞消息的发布。
```java
// 耗时 77ms
public static void publicMessageBatch() throws Exception {
Channel channel = RabbitMqUtils.getChannel();
// Queue Name
String queueName = UUID.randomUUID().toString();
channel.queueDeclare(queueName, true, false,false, null);
// 开启发布确认
channel.confirmSelect();
// 开始时间
long begin = System.currentTimeMillis();
// 批量确认长度
int batchSize = 1000;
for (int i = 0; i < MESSAGE_COUNT; i++) {
String message = i + "";
channel.basicPublish("", queueName, null, message.getBytes());
if (i % batchSize == 0) {
// 确认
channel.waitForConfirms();
}
}
// 结束时间
long end = System.currentTimeMillis();
System.out.println("发布" + MESSAGE_COUNT + "个消息每 100 次确认一次,耗时:" + (end - begin) + "ms");
}
```
#### 异步确认发布
异步确认虽然编程逻辑比上两个要复杂,但是性价比最高,无论是可靠性还是效率都没得说,
他是利用回调函数来达到消息可靠性传递的,这个中间件也是通过函数回调来保证是否投递成功,
下面就让我们来详细讲解异步确认是怎么实现的。
![uZsF49CBznPtGAI](https://vip2.loli.io/2021/11/30/uZsF49CBznPtGAI.png)
```java
/**
* 异步确认
* 耗时33ms
* @throws Exception
*/
public static void publicMessageAsync() throws Exception {
Channel channel = RabbitMqUtils.getChannel();
// Queue Name
String queueName = UUID.randomUUID().toString();
channel.queueDeclare(queueName, true, false,false, null);
// 开启发布确认
channel.confirmSelect();
// 开始时间
long begin = System.currentTimeMillis();
// 消息确认成功
ConfirmCallback ackConfirm = (deliveryTag, multiple) -> {
System.out.println("确认的消息:" + deliveryTag);
};
// 消息确认失败
ConfirmCallback nackConfirm = (deliveryTag, multiple) -> {
System.out.println("未确认的消息:" + deliveryTag);
};
// 消息监听器,检测消息的成功与失败
channel.addConfirmListener(ackConfirm, nackConfirm);
for (int i = 0; i < MESSAGE_COUNT; i++) {
String message = "消息:" + i;
channel.basicPublish("", queueName, null, message.getBytes());
}
// 结束时间
long end = System.currentTimeMillis();
System.out.println("发布" + MESSAGE_COUNT + "个消息异步确认,耗时:" + (end - begin) + "ms");
}
```
#### 异步处理未确认消息
```java
/**
* 异步确认
* 耗时33ms
* @throws Exception
*/
public static void publicMessageAsync() throws Exception {
Channel channel = RabbitMqUtils.getChannel();
// Queue Name
String queueName = UUID.randomUUID().toString();
channel.queueDeclare(queueName, true, false,false, null);
// 开启发布确认
channel.confirmSelect();
// 线程安全的哈希表,适用于高并发的场景
/**
* 将序号与消息关联
* 轻松批量删除确认消息
* 支持高并发
*/
ConcurrentSkipListMap<Long, String> map = new ConcurrentSkipListMap<Long, String>();
// 开始时间
long begin = System.currentTimeMillis();
// 消息确认成功
ConfirmCallback ackConfirm = (deliveryTag, multiple) -> {
if (multiple) {
// 2.删除已确认的消息,剩下的就是未确认的
ConcurrentNavigableMap<Long, String> confirmed = map.headMap(deliveryTag);
} else {
map.remove(deliveryTag);
}
System.out.println("确认的消息:" + deliveryTag);
};
// 消息确认失败
ConfirmCallback nackConfirm = (deliveryTag, multiple) -> {
String s = map.get(deliveryTag);
System.out.println("未确认的消息: " + s + " 消息Tag: " + deliveryTag);
};
// 消息监听器,检测消息的成功与失败
channel.addConfirmListener(ackConfirm, nackConfirm);
for (int i = 0; i < MESSAGE_COUNT; i++) {
String message = "消息:" + i;
channel.basicPublish("", queueName, null, message.getBytes());
// 1.记录发送的所有消息
map.put(channel.getNextPublishSeqNo(), message);
}
// 结束时间
long end = System.currentTimeMillis();
System.out.println("发布" + MESSAGE_COUNT + "个消息异步确认,耗时:" + (end - begin) + "ms");
}
```
#### 三种发布确认的对比
| 名称 | 优缺点 |
|----------------|-----------------------------------------------------------------------------------|
| 单独发布消息 | 同步等待确认,简单,但吞吐量非常有限。 |
| 批量发布消息 | 批量同步等待确认,简单,合理的吞吐量,一旦出现问题但很难推断出是那条消息出现了问题。 |
| 异步处理(推荐) | 最佳性能和资源使用,在出现错误的情况下可以很好地控制,但是实现起来稍微难些 |

View File

@@ -28,7 +28,11 @@ public class Worker03 {
System.out.println("Worker03 等待接收消息...");
// 设置不公平分发
int prefetchCount = 1;
// int prefetchCount = 1;
// channel.basicQos(prefetchCount);
// 设置预取值
int prefetchCount = 2;
channel.basicQos(prefetchCount);
boolean autoAck = false;

View File

@@ -28,7 +28,11 @@ public class Worker04 {
System.out.println("Worker04 等待接收消息...");
// 设置不公平分发
int prefetchCount = 1;
// int prefetchCount = 1;
// channel.basicQos(prefetchCount);
// 设置预取值
int prefetchCount = 5;
channel.basicQos(prefetchCount);
boolean autoAck = false;