RabbitMQ系列

RabbitMQ(一)——简介

RabbitMQ(二)——模式类型

RabbitMQ(三)——简单模式

RabbitMQ(四)——工作队列模式

RabbitMQ(五)——发布订阅模式

RabbitMQ(六)——路由模式

RabbitMQ(七)——主题模式

RabbitMQ(八)——消息确认

RabbitMQ(九)——消息持久化

RabbitMQ(十)——消息优先级

 

  通过前面的学习我们将消息写入队列中都是按顺序写的,消费时也是按顺序进行消费,即队列queue是先进先出的(FIFO),在一些场景中我们需要将某些消息提前处理,首先定义队列时先设置队列为优先队列,然后设置优先等级。

channel.QueueDeclare("Priqueue", true, false, false, new Dictionary<string, object>() { { "x-max-priority",10} });

RabbitMQ(十)——消息优先级

 

生产者:

        //初始化工厂
            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();
            }    
View Code

相关文章:

  • 2019-01-09
  • 2021-09-01
  • 2022-02-08
  • 2021-10-27
  • 2021-11-29
  • 2022-12-23
  • 2022-01-05
猜你喜欢
  • 2021-09-16
  • 2022-12-23
  • 2021-06-17
  • 2021-09-26
  • 2021-11-05
  • 2021-08-17
  • 2022-12-23
相关资源
相似解决方案