RabbitMQ中的消息确认模式有哪几种,它们有什么区别?

RabbitMQ中的消息确认模式有3种:

  1. 自动确认:在RabbitMQ将消息发送给消费者后立即确认消息。
  2. 手动确认:需要消费者在消费完成后手动确认消息。
  3. 批量确认:可以一次性确认多条消息。

Java代码演示如下:
自动确认:

channel.basicConsume(QUEUE_NAME, true, consumer);

手动确认:

channel.basicConsume(QUEUE_NAME, false, new DefaultConsumer(channel) {
    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
        channel.basicAck(envelope.getDeliveryTag(), false);
    }
});

批量确认:

long deliveryTag;

channel.basicConsume(QUEUE_NAME, false, new DefaultConsumer(channel) {
    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
        deliveryTags.add(envelope.getDeliveryTag());
    }
});

channel.basicAck(deliveryTags.toArray(new Long[deliveryTags.size()]), false);

所以,RabbitMQ消息确认机制的主要区别在于:

  • 自动确认:消息一旦被消费者接收到就确认。
  • 手动确认:需要消费者调用确认方法确认消息。
  • 批量确认:可以确认多条消息。