- 关键代码片段:
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
// 第二个参数durable设置为true表示队列持久化
channel.QueueDeclare(queue: "myQueue",
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);
var body = Encoding.UTF8.GetBytes("Hello, RabbitMQ!");
// 设置消息持久化,IBasicProperties.Persistent为true
var properties = channel.CreateBasicProperties();
properties.Persistent = true;
channel.BasicPublish(exchange: "",
routingKey: "myQueue",
basicProperties: properties,
body: body);
- RabbitMQ相关配置:
- 对于队列持久化,需要在声明队列时,将
durable
参数设置为true
。这会将队列的元数据持久化到磁盘,即使服务器重启,队列依然存在。
- 对于消息持久化,要通过设置消息的
BasicProperties
中的Persistent
属性为true
。这样消息会在被接收并确认后持久化到磁盘,保证服务器重启时消息不会丢失。同时,确保RabbitMQ服务器配置了足够的磁盘空间来存储持久化的消息和队列元数据。