RabbitMQ(十)——消息优先级
RabbitMQ系列
RabbitMQ(十)——消息优先级
前言
通过前面的学习我们将消息写入队列中都是按顺序写的,消费时也是按顺序进行消费,即队列queue是先进先出的(FIFO),在一些场景中我们需要将某些消息提前处理,首先定义队列时先设置队列为优先队列,然后设置优先等级。
channel.QueueDeclare("Priqueue", true, false, false, new Dictionary<string, object>() { { "x-max-priority",10} });
生产者:
//初始化工厂 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("Priqueue", true, false, false, new Dictionary<string, object>() { { "x-max-priority",10} }); //交换器绑定队列 channel.QueueBind("Priqueue", "exchange", "", null); //消息持久化 IBasicProperties basicProperties = channel.CreateBasicProperties(); basicProperties.Persistent = true; string msg = ""; for (int i = 0; i < 10; i++) { msg = $"发布消息{i}"; if (i % 2 == 0) { msg += "——vip用户消息(优先处理)"; basicProperties.Priority = 9; } else { msg += "——普通用户消息"; basicProperties.Priority = 1; } var body = Encoding.UTF8.GetBytes(msg); channel.BasicPublish("exchange", "", basicProperties, body); Console.WriteLine($"发布成功:{msg}"); Thread.Sleep(1000); } Console.ReadKey(); }
消费者:
//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); //5.创建匿名队列,绑定交换器 durable:true 持久化 没有被消费不会丢失 var queueName = channel.QueueDeclare("Priqueue", true, false, false, new Dictionary<string, object>() { { "x-max-priority", 10 } }); channel.QueueBind(queueName, "exchange", "",null); //6.创建消费者 var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { //接收消息 var body = Encoding.UTF8.GetString(ea.Body.ToArray()); Console.WriteLine($"接收消息:{body.ToString()}"); }; //7.消费消息 channel.BasicConsume(queueName, true, consumer); Console.ReadKey(); } }
总结:
开始生产消息,生产完成后启动消费者控制台,出现以下的效果,消费者会优先消费优先级别高的消息,也就是生产者中定义的vip消息,消费完优先级高的vip消息才去消费优先级低的普通用户的消息。