RabbitMQ(九)——消息持久化
RabbitMQ系列
RabbitMQ(九)——消息持久化
前言
对于交换机(exchange)与队列(queue)的持久化只需要将durable属性设置为true即可,当重启RabbitMQ服务后,交换机和队列都会恢复,但是当只有队列的durable属性设置为true时,重启后会造成消息丢失。
实现
首先是设置生产者的交换机和队列的持久化属性durable为true,再设置IBasicProperties.Persistent为true,发布时带上BasicProperties
//1.创建连接工厂 ConnectionFactory factory = new ConnectionFactory() { HostName = "127.0.0.1", UserName = "guest", Password = "guest" }; //2.创建连接 using (var connection = factory.CreateConnection()) //3.创建管道 using (var channel = connection.CreateModel()) { //4.创建交换器 channel.ExchangeDeclare("exchange", "fanout"); channel.QueueDeclare("SMSqueue",true,false,false,null); channel.QueueDeclare("SMAILqueue", true, false, false, null); channel.QueueBind("SMSqueue", "exchange","",null); channel.QueueBind("SMAILqueue", "exchange","",null); //消息持久化 //IBasicProperties basicProperties = channel.CreateBasicProperties(); //basicProperties.Persistent = true; string msg = ""; for (int i = 0; i < 10; i++) { msg = $"发布消息{i}"; var body = Encoding.UTF8.GetBytes(msg); channel.BasicPublish("exchange", "", null, body); Console.WriteLine($"发布成功:{msg}"); Thread.Sleep(1000); } Console.ReadKey(); }
可以看到10条消息写入成功
现在重启下RabbitMQ服务
可以看到上图中的消息在重启后没有消费就丢失了,下面进行消息的持久化,交换机和队列的durable都设置为true。
修改创建交换机代码,将默认的false设置为true,basicProperties.Persistent设置为true
//1.创建连接工厂 ConnectionFactory factory = new ConnectionFactory() { HostName = "127.0.0.1", UserName = "guest", Password = "guest" }; //2.创建连接 using (var connection = factory.CreateConnection()) //3.创建管道 using (var channel = connection.CreateModel()) { //4.创建交换器 channel.ExchangeDeclare("exchange", "fanout",true); channel.QueueDeclare("SMSqueue",true,false,false,null); channel.QueueDeclare("SMAILqueue", true, false, false, null); channel.QueueBind("SMSqueue", "exchange","",null); channel.QueueBind("SMAILqueue", "exchange","",null); IBasicProperties basicProperties = channel.CreateBasicProperties(); basicProperties.Persistent = true; string msg = ""; for (int i = 0; i < 10; i++) { msg = $"发布消息{i}"; var body = Encoding.UTF8.GetBytes(msg); channel.BasicPublish("exchange", "", basicProperties, body); Console.WriteLine($"发布成功:{msg}"); Thread.Sleep(1000); } Console.ReadKey(); }
发布消息和重启之后都是是10条消息。
这样就完成了消息持久的设置了