I. Introduction
In specific business, you may encounter some messages to be processed in advance. For example, the messages of ordinary customers are processed in the order of first-in first-out, and the messages of Vip customers are processed in advance. In RabbitMQ, the message priority is implemented by setting the x-max-priority attribute of the queue when the queue is declared, and then setting the message priority when publishing the message.
Notes on RabbitMQ priority queue:
1) Priority queues are only supported after RabbitMQ3.5.
2) The priority queue will take effect only when there are insufficient consumers and can't consume in time.
3) The priority ranges from 0 to 9. The larger the value, the higher the priority.
Second, the example
2.1. Sending end (production end)
Create a new console project Send and add a class RabbitMQConfig.
class RabbitMQConfig { public static string Host { get; set; } public static string VirtualHost { get; set; } public static string UserName { get; set; } public static string Password { get; set; } public static int Port { get; set; } static RabbitMQConfig() { Host = "192.168.2.242"; VirtualHost = "/"; UserName = "hello"; Password = "world"; Port = 5672; } }
class Program { static void Main(string[] args) { Console.WriteLine("按任意键开始生产。"); Console.ReadLine(); PriorityMessagePublish(); Console.ReadLine(); } private static void PriorityMessagePublish() { const string MessagePrefix = "message_"; const int PublishMessageCount = 6; byte messagePriority = 0; var factory = new ConnectionFactory() { HostName = RabbitMQConfig.Host, Port = RabbitMQConfig.Port, VirtualHost = RabbitMQConfig.VirtualHost, UserName = RabbitMQConfig.UserName, Password = RabbitMQConfig.Password, Protocol = Protocols.DefaultProtocol }; using (var connection =factory.CreateConnection ()) { using ( var channel = connection.CreateModel ()) { // Set the queue priority, the value range is 0 ~ 255. Dictionary < string , object > dict = new Dictionary < string , object > { { " x-max-priority " , 255 } }; // Declare queue channel.QueueDeclare (queue: " priority ", durable: true, exclusive: false, autoDelete: false, arguments: dict); //向该消息队列发送消息message Random random = new Random(); for (int i = 0; i < PublishMessageCount; i++) { var properties = channel.CreateBasicProperties(); messagePriority = (byte)random.Next(0, 9); properties.Priority = messagePriority;//Set the message priority, ranging from 0 to 9. var message = MessagePrefix + i.ToString (); var body = Encoding.UTF8.GetBytes (message); channel.BasicPublish (exchange: "" , routingKey: " priority " , basicProperties: properties, body: body); Console.WriteLine ($ " {DateTime.Now.ToString ()} Send {message}, Priority {messagePriority} " ); } } } } }
2.2. Receiver (consumer)
Create a new console project Receive, hold down the Alt key, and drag the RabbitMQConfig class on the sender a shortcut to the Receive project.
class Program { static void Main(string[] args) { Console.WriteLine("按任意键开始消费。"); Console.ReadLine(); PriorityMessageSubscribe(); } public static void PriorityMessageSubscribe() { var factory = new ConnectionFactory() { HostName = RabbitMQConfig.Host, UserName = RabbitMQConfig.UserName, Password = RabbitMQConfig.Password }; using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false); var consumer = new EventingBasicConsumer(channel); consumer.Received += async (model, ea) => { await Task.Run(() => { var message = Encoding.UTF8.GetString(ea.Body); Thread.Sleep(1000 * 2); channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);//手动消息确认 Console.WriteLine($"{DateTime.Now.ToString()} Received {message}"); }); }; channel.BasicConsume(queue: "priority", noAck: false, consumer: consumer);// The message response needs to be enabled, otherwise the priority is invalid. Console.ReadKey (); } } } }
2.3. Operation result
From the consumption situation, it can be seen that message_2 and message_3 have the highest priority of 7, so they will be consumed at the earliest, and message_5 has a priority of 0, so it will be consumed last.