RabbitMQ优先级队列的使用
生产者文章来源:https://www.toymoban.com/news/detail-602790.html
public class PriorityQueue
{
public static void Send()
{
string path = AppDomain.CurrentDomain.BaseDirectory;
string tag = path.Split('/', '\\').Last(s => !string.IsNullOrEmpty(s));
Console.WriteLine($"这里是 {tag} 启动了。。");
ConnectionFactory factory = new ConnectionFactory();
factory.HostName = "localhost";//RabbitMQ服务在本地运行
factory.UserName = "guest";//用户名
factory.Password = "guest";//密码
using (IConnection connection = factory.CreateConnection())
{
using (IModel channel = connection.CreateModel())
{
//创建队列的时候,指定队列的优先级;x-max-priority:最大的优先级是10
channel.QueueDeclare(queue: "PriorityQueue", durable: true, exclusive: false, autoDelete: false, arguments: new Dictionary<string, object>() {
{"x-max-priority",10 } //指定队列要支持优先级设置;
});
channel.ExchangeDeclare(exchange: "PriorityQueueExchange", type: ExchangeType.Direct, durable: true, autoDelete: false, arguments: null);
channel.QueueBind(queue: "PriorityQueue", exchange: "PriorityQueueExchange", routingKey: "PriorityKey");
string[] questionList = { "vip学员1 来请教", "甲 同学来请教问题",
"乙 同学来请教问题", "丙 同学来请教问题",
"丁 同学来请教问题", "vip学员2 来请教" };
//设置消息优先级
//VIP学员和公开课学员同时来请教问题解答,当然是优先VIP学员;
IBasicProperties props = channel.CreateBasicProperties();
foreach (string questionMsg in questionList)
{
if (questionMsg.StartsWith("vip"))
{
props.Priority = 9;
channel.BasicPublish(exchange: "PriorityQueueExchange",
routingKey: "PriorityKey",
basicProperties: props,
body: Encoding.UTF8.GetBytes(questionMsg));
}
else
{
props.Priority = 1;
channel.BasicPublish(exchange: "PriorityQueueExchange",
routingKey: "PriorityKey",
basicProperties: props,
body: Encoding.UTF8.GetBytes(questionMsg));
}
Console.WriteLine($"{questionMsg} 已发送~~");
}
Console.Read();
}
}
}
}
消费者文章来源地址https://www.toymoban.com/news/detail-602790.html
public class PriorityQueue
{
public static void Consumption()
{
var factory = new ConnectionFactory();
factory.HostName = "localhost";//RabbitMQ服务在本地运行
factory.UserName = "guest";//用户名
factory.Password = "guest";//密码
using (var connection = factory.CreateConnection())
{
using (IModel channel = connection.CreateModel())
{
//定义消费者
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
string msg = Encoding.UTF8.GetString(ea.Body.ToArray());
Console.WriteLine(msg);
channel.BasicReject(deliveryTag: ea.DeliveryTag, requeue: false);
};
Console.WriteLine("消费者准备就绪....");
//处理消息
channel.BasicConsume(queue: "PriorityQueue", autoAck: false, consumer: consumer);
Console.ReadKey();
}
}
}
}
到了这里,关于RabbitMQ优先级队列的使用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!