RabbitMQ入门教程——路由(Routing)
绑定的时候需要带上一个额外的参数routingKey,为避免与BasicPublish中的路由键(routing key)参数混淆,我们称之为绑定键(binding key),以下是如何创建一个绑定。
channel.QueueBind(queue: queue, exchange: EXCHANGE_NAME, routingKey: "error", arguments: null);
这样以来,当路由键为orange的消息发送到交换机,就会被路由到队列Q1,路由键为black和green的下拍戏就会被路由到Q2,其它的消息将会被丢弃。
多重绑定即使用一个绑定键(binding key)绑定到多个队列,这是完全合法的,而且每个队列都能得到完全相同的信息。
接下来我们就使用direct exchange完善之前的日志功能
using System.Collections.Generic;
const string EXCHANGE_NAME = "ROUTING_EXCHANGE";
static readonly List<string> LEVELS = new List<string>() { "error", "log" };
ConnectionFactory factory = new ConnectionFactory() { HostName = "localhost" };
using (IConnection connection = factory.CreateConnection())
using (IModel channel = connection.CreateModel())
channel.ExchangeDeclare(exchange: EXCHANGE_NAME, type: ExchangeType.Direct);
string message = $"日志信息:{i}——日志等级:{level}";
Console.WriteLine(" Press [enter] to exit.");
private static string GetLevels()
return LEVELS[new Random().Next(0, 2)];
using System.Collections.Generic;
const string EXCHANGE_NAME = "ROUTING_EXCHANGE";
/// <param name="all"></param>
public static void Log(bool all = false)
var factory = new ConnectionFactory()
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
channel.ExchangeDeclare(exchange: EXCHANGE_NAME, type: ExchangeType.Direct);
//每次运行consumer客户端都创建一个新的queue,并且绑定到对应的exchange,这样使每次发送消息到exchange时就能把消息由exchange传递到所绑定的queue
QueueDeclareOk queue = channel.QueueDeclare();
string queueName = queue.QueueName;
channel.QueueBind(queue: queueName, exchange: EXCHANGE_NAME, routingKey: "log", arguments: null);
channel.QueueBind(queue: queueName, exchange: EXCHANGE_NAME, routingKey: "error", arguments: null);
EventingBasicConsumer consumer = new EventingBasicConsumer(channel);
consumer.Received += (sender, e) =>
string message = Encoding.UTF8.GetString(e.Body);
Console.WriteLine($"LOG——日志信息:{message}");
channel.BasicConsume(queueName, noAck: true, consumer: consumer);
Console.WriteLine(" Press [enter] to exit.");
var factory = new ConnectionFactory() { HostName = "127.0.0.1" };
using (IConnection connection = factory.CreateConnection())
using (IModel channel = connection.CreateModel())
channel.ExchangeDeclare(exchange: EXCHANGE_NAME, type: ExchangeType.Direct);
//创建一个未命名的新的消息队列,该队列名称有系统自动分配,并且为非持久化,在该队列没有订阅时自动删除的排它队列
QueueDeclareOk queue = channel.QueueDeclare();
string queueName = queue.QueueName;
//绑定exchange 与 queue 并设置路由键为日志级别error
channel.QueueBind(queue: queue, exchange: EXCHANGE_NAME, routingKey: "error", arguments: null);
EventingBasicConsumer consumer = new EventingBasicConsumer(channel);
consumer.Received += (sender, arg) =>
string message = Encoding.UTF8.GetString(arg.Body);
using (StreamWriter writer = new StreamWriter(@"c:\log\log.txt", true, Encoding.UTF8))
channel.BasicConsume(queue: queueName, noAck: true, consumer: consumer);