一、介绍:二、实现方式
一、介绍:持久化是提高RabbitMQ可靠性的基础,否则当RabbitMQ遇到异常时(如:重启、断电、停机等)数据将会丢失。主要从以下几个方面来保障消息的持久性:
- Exchange的持久化。通过定义时设置durable 参数为ture来保证Exchange相关的元数据不不
丢失。Queue的持久化。也是通过定义时设置durable 参数为ture来保证Queue相关的元数据不不
丢失。消息的持久化。通过将消息的投递模式 (BasicProperties 中的 deliveryMode 属性)设置为 2
即可实现消息的持久化,保证消息自身不丢失。
public class Producer {
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setUri("amqp://root:123456@node1:5672/%2f");
final Connection connection = factory.newConnection();
final Channel channel = connection.createChannel();
//1、队列持久化 durable:true表示是持久化消息队列
channel.queueDeclare("queue.persistent", true, false, false, null);
// 2、交换器持久化
channel.exchangeDeclare("ex.persistent", "direct", true, false, null);
channel.queueBind("queue.persistent", "ex.persistent", "key.persistent");
//3、消息持久化 deliveryMode:2 表示是持久化消息
final AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder().deliveryMode(2).build();
// 设置消息的属性,此时消息是持久化消息
channel.basicPublish("ex.persistent", "key.persistent", properties, "hello world".getBytes());
channel.close();
connection.close();
}
}
说明:
RabbitMQ中的持久化消息都需要写入磁盘(当系统内存不不足时,非持久化的消息也会被刷盘处理),这些处理理动作都是在“持久层”中完成的。持久层是一个逻辑上的概念,实际包含两个部分:
- 队列索引(rabbit_queue_index),rabbit_queue_index 负责维护Queue中消息的信息,包括消息的存储位置、是否已交给消费者、是否已被消费及Ack确认等,每个Queue都有与之对应的rabbit_queue_index。消息存储(rabbit_msg_store),rabbit_msg_store 以键值对的形式存储消息,它被所有队列列 共享,在每个节点中有且只有一个



