发布确认
发布确认原理
开启发布确认的方法
发布确认默认是没有开启的,如果要开启需要调用方法 confirmSelect,每当你要想使用发布确认,都需要在channel 上调用该方法
Connection connection = RabbitmqUtil.getConnection();
Channel channel = connection.createChannel();
channel.confirmSelect();
单个发布确认
这是一种简单的确认方式,它是一种同步确认发布的方式,也就是发布一个消息之后只有它被确认发布,后续的消息才能继续发布, waitForConfirmsOrDie(long)这个方法只有在消息被确认的时候才返回,如果在指定时间范围内这个消息没有被确认那么它将抛出异常。
这种确认方式有一个最大的缺点就是:发布速度特别的慢,因为如果没有确认发布的消息就会阻塞所有后续消息的发布,这种方式最多提供每秒不超过数百条发布消息的吞吐量。当然对于某些应用程序来说这可能已经足够了。
public static void publicMessageSingle() throws IOException, InterruptedException {
Connection connection = RabbitmqUtil.getConnection();
Channel channel = connection.createChannel();
String queueName = UUID.randomUUID().toString();
channel.queueDeclare(queueName,true,false,false,null);
channel.confirmSelect();
long begin = System.currentTimeMillis();
for (int i = 0; i < 1000; 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("发布1000条单独确认消息,耗时"+(end - begin)+"ms");
}
批量确认发布
上面那种方式非常慢,与单个等待确认消息相比,先发布一批消息然后一起确认可以极大地提高吞吐量,当然这种方式的缺点就是:当发生故障导致发布出现问题时,不知道是哪个消息出现问题了,我们必须将整个批处理保存在内存中,以记录重要的信息而后重新发布消息。当然这种方案仍然是同步的,也一样阻塞消息的发布。
public static void publicMessageBatch() throws IOException, InterruptedException {
Connection connection = RabbitmqUtil.getConnection();
Channel channel = connection.createChannel();
String queueName = UUID.randomUUID().toString();
channel.queueDeclare(queueName,true,false,false,null);
channel.confirmSelect();
long begin = System.currentTimeMillis();
int batchSize = 100;
for (int i = 1; i <= 1000; i++) {
String message = i+"";
channel.basicPublish("",queueName,null,message.getBytes());
if (i % batchSize == 0) {
channel.waitForConfirms();
}
}
long end = System.currentTimeMillis();
System.out.println("发布1000条批量确认消息,耗时"+(end - begin)+"ms");
RabbitmqUtil.closeConnectionAndChannel(channel,connection);
}
异步发布确认
异步确认虽然编程逻辑比上两个要复杂,但是性价比最高,无论是可靠性还是效率都没得说,他是利用回调函数来达到消息可靠性传递的,这个中间件也是通过函数回调来保证是否投递成功,下面就让我们来详细讲解异步确认是怎么实现的。
public static void publicMessageAsync() throws IOException, InterruptedException {
Connection connection = RabbitmqUtil.getConnection();
Channel channel = connection.createChannel();
String queueName = UUID.randomUUID().toString();
channel.queueDeclare(queueName,true,false,false,null);
channel.confirmSelect();
long begin = System.currentTimeMillis();
ConfirmCallback ackCallBack = (deliveryTag,multiple)->{
System.out.println("确认的消息"+deliveryTag);
};
ConfirmCallback nackCallBack = (deliveryTag,multiple)->{
System.out.println("未确认的消息"+deliveryTag);
};
channel.addConfirmListener(ackCallBack,nackCallBack);
for (int i = 1; i <= 1000; i++) {
String message = i+"";
channel.basicPublish("",queueName,null,message.getBytes());
}
long end = System.currentTimeMillis();
System.out.println("发布1000条批量确认消息,耗时"+(end - begin)+"ms");
}
如何处理异步未确认的消息
最好的解决的解决方案就是把未确认的消息放到一个基于内存的能被发布线程访问的队列,比如说用ConcurrentLinkedQueue这个队列在confirm callbacks与发布线程之间进行消息的传递。
public static void publicMessageAsync() throws IOException, InterruptedException {
Connection connection = RabbitmqUtil.getConnection();
Channel channel = connection.createChannel();
String queueName = UUID.randomUUID().toString();
channel.queueDeclare(queueName,true,false,false,null);
channel.confirmSelect();
ConcurrentSkipListMap<Long,Object> outStandingConfirms = new ConcurrentSkipListMap<>();
ConfirmCallback ackCallBack = (deliveryTag,multiple)->{
if (multiple) {
ConcurrentNavigableMap<Long, Object> confirmed =
outStandingConfirms.headMap(deliveryTag);
confirmed.clear();
} else {
outStandingConfirms.remove(deliveryTag);
}
System.out.println("确认的消息"+deliveryTag);
};
ConfirmCallback nackCallBack = (deliveryTag,multiple)->{
String msg = outStandingConfirms.get(deliveryTag).toString();
System.out.println("未确认的消息"+msg);
};
channel.addConfirmListener(ackCallBack,nackCallBack);
long begin = System.currentTimeMillis();
for (int i = 1; i <= 1000; i++) {
String message = i+"";
channel.basicPublish("",queueName,null,message.getBytes());
outStandingConfirms.put(channel.getNextPublishSeqNo(),message);
}
long end = System.currentTimeMillis();
System.out.println("发布1000条批量确认消息,耗时"+(end - begin)+"ms");
}
死信队列
死信的概念
先从概念解释上搞清楚这个定义,死信,顾名思义就是无法被消费的消息,字面意思可以这样理解,一般来说,producer将消息投递到 broker或者直接到queue里了,consumer 从 queue取出消息进行消费,但某些时候由于特定的原因导致queue中的某些消息无法被消费,这样的消息如果没有后续的处理,就变成了死信,有死信自然就有了死信队列。
应用场景:为了保证订单业务的消息数据不丢失,需要使用到RabbitMQ的死信队列机制,当消息消费发生异常时,将消息投入死信队列中.还有比如说:用户在商城下单成功并点击去支付后在指定时间未支付时自动失效
死信的来源
- 消息TIL过期
- 队列达到最大长度(队列满了,无法再添加数据到mq.中)
- 消息被拒绝(basic.reject或 basic.nack)并且requeue=false.
死信实战
消息TTL过期
消息过期后满足死信要求,消费者1若在10s内未能接受消息,则会将消息转移到死信队列,由消费者2来消费。
生产者
public class Producer {
private static final String NORMAL_EXCHANGE = "normal_exchange";
public static void main(String[] args) throws IOException {
Connection connection = RabbitmqUtil.getConnection();
Channel channel = connection.createChannel();
AMQP.BasicProperties properties = new AMQP.BasicProperties().builder().expiration("10000").build();
for (int i = 1; i <= 10; i++) {
String message = "info" + i;
channel.basicPublish(NORMAL_EXCHANGE,"zhangsan",properties,message.getBytes());
}
RabbitmqUtil.closeConnectionAndChannel(channel,connection);
}
}
消费者1
public class Consumer1 {
public static final String NORMAL_EXCHANGE = "normal_exchange";
public static final String DEAD_EXCHANGE = "dead_exchange";
public static final String NORMAL_QUEUE = "normal_queue";
public static final String DEAD_QUEUE = "dead_queue";
public static void main(String[] args) throws IOException {
Connection connection = RabbitmqUtil.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
channel.exchangeDeclare(DEAD_EXCHANGE,BuiltinExchangeType.DIRECT);
Map<String,Object> arguments = new HashMap<>();
arguments.put("x-dead-letter-exchange",DEAD_EXCHANGE);
arguments.put("x-dead-letter-routing-key","lisi");
channel.queueDeclare(NORMAL_QUEUE,false,false,false,arguments);
channel.queueDeclare(DEAD_QUEUE,false,false,false,null);
channel.queueBind(NORMAL_QUEUE,NORMAL_EXCHANGE,"zhangsan");
channel.queueBind(DEAD_QUEUE,DEAD_EXCHANGE,"lisi");
System.out.println("等待接受消息...");
DeliverCallback deliverCallback = (consumerTag, message) -> {
System.out.println("consumer1接受的消息是"+new String(message.getBody(),"UTF-8"));
};
channel.basicConsume(NORMAL_QUEUE, true, deliverCallback,consumerTag -> {});
}
}
消费者2
public class Consumer2 {
public static final String DEAD_QUEUE = "dead_queue";
public static void main(String[] args) throws IOException {
Connection connection = RabbitmqUtil.getConnection();
Channel channel = connection.createChannel();
System.out.println("等待接受消息...");
DeliverCallback deliverCallback = (consumerTag, message) -> {
System.out.println("consumer2接受的消息是"+new String(message.getBody(),"UTF-8"));
};
channel.basicConsume(DEAD_QUEUE, true, deliverCallback,consumerTag -> { });
}
}
队列达到最大长度
c1消费者修改如下代码
arguments.put("x-dead-letter-exchange",DEAD_EXCHANGE);
arguments.put("x-dead-letter-routing-key","lisi");
arguments.put("x-max-length",6);
生产者修改代码 去掉TTL限制
channel.basicPublish(NORMAL_EXCHANGE,"zhangsan",null,message.getBytes());
|