rabbitmq
exchange-direct
直连交换机,交换机根据生产者指定的key,直接投递到跟key完全匹配的队列
exchange在和queue进行binding时会设置routingkey
channel.QueueBind(queue: "create_pdf_queue",
exchange: "pdf_events",
routingKey: "pdf_create",
arguments: null);
然后我们在将消息发送到exchange时会设置对应的routingkey:
channel.BasicPublish(exchange: "pdf_events",
routingKey: "pdf_create",
basicProperties: properties,
body: body);
在direct类型的exchange中,只有这两个routingkey完全相同,exchange才会选择对应的binging进行消息路由。
代码示例:
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
// Direct类型的exchange, 名称 pdf_events
channel.ExchangeDeclare(exchange: "pdf_events",
type: ExchangeType.Direct,
durable: true,
autoDelete: false,
arguments: null);
// 创建create_pdf_queue队列
channel.QueueDeclare(queue: "create_pdf_queue",
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);
//创建 pdf_log_queue队列
channel.QueueDeclare(queue: "pdf_log_queue",
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);
//绑定 pdf_events --> create_pdf_queue 使用routingkey:pdf_create
channel.QueueBind(queue: "create_pdf_queue",
exchange: "pdf_events",
routingKey: "pdf_create",
arguments: null);
//绑定 pdf_events --> pdf_log_queue 使用routingkey:pdf_log
channel.QueueBind(queue: "pdf_log_queue",
exchange: "pdf_events",
routingKey: "pdf_log",
arguments: null);
var message = "Demo some pdf creating...";
var body = Encoding.UTF8.GetBytes(message);
var properties = channel.CreateBasicProperties();
properties.Persistent = true;
//发送消息到exchange :pdf_events ,使用routingkey: pdf_create
//通过binding routinekey的比较,次消息会路由到队列 create_pdf_queue
channel.BasicPublish(exchange: "pdf_events",
routingKey: "pdf_create",
basicProperties: properties,
body: body);
message = "pdf loging ...";
body = Encoding.UTF8.GetBytes(message);
properties = channel.CreateBasicProperties();
properties.Persistent = true;
//发送消息到exchange :pdf_events ,使用routingkey: pdf_log
//通过binding routinekey的比较,次消息会路由到队列 pdf_log_queue
channel.BasicPublish(exchange: "pdf_events",
routingKey: "pdf_log",
basicProperties: properties,
body: body);
}