rabbitmq
exchange-topic
主题交换机,直连交换机的升级版,可以通过*号或#号模糊匹配队列
如下图所示,队列绑定到交换机时指定的routingKey是带有*号或者#号的,表示接收类似的routingKey
如果有两条队列匹配上,两条队列都会收到
例如,下面的三条队列,分别为A->agreements.eu.berlin.#,B->agreements.# ,C->agreements.eu.*.headstore
假如生产者指定的routingKey为agreements.eu.berlin,那么会匹配上A和B
示例代码:
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
// Topic类型的exchange, 名称 agreements
channel.ExchangeDeclare(exchange: "agreements",
type: ExchangeType.Topic,
durable: true,
autoDelete: false,
arguments: null);
// 创建berlin_agreements队列
channel.QueueDeclare(queue: "berlin_agreements",
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);
//创建 all_agreements 队列
channel.QueueDeclare(queue: "all_agreements",
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);
//创建 headstore_agreements 队列
channel.QueueDeclare(queue: "headstore_agreements",
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);
//绑定 agreements --> berlin_agreements 使用routingkey:agreements.eu.berlin.#
channel.QueueBind(queue: "berlin_agreements",
exchange: "agreements",
routingKey: "agreements.eu.berlin.#",
arguments: null);
//绑定 agreements --> all_agreements 使用routingkey:agreements.#
channel.QueueBind(queue: "all_agreements",
exchange: "agreements",
routingKey: "agreements.#",
arguments: null);
//绑定 agreements --> headstore_agreements 使用routingkey:agreements.eu.*.headstore
channel.QueueBind(queue: "headstore_agreements",
exchange: "agreements",
routingKey: "agreements.eu.*.headstore",
arguments: null);
var message = "hello world";
var body = Encoding.UTF8.GetBytes(message);
var properties = channel.CreateBasicProperties();
properties.Persistent = true;
//发送消息到exchange :agreements ,使用routingkey: agreements.eu.berlin
//agreements.eu.berlin 匹配 agreements.eu.berlin.# 和agreements.#
//agreements.eu.berlin 不匹配 agreements.eu.*.headstore
//最终次消息会路由到队里:berlin_agreements(agreements.eu.berlin.#) 和 all_agreements(agreements.#)
channel.BasicPublish(exchange: "agreements",
routingKey: "agreements.eu.berlin",
basicProperties: properties,
body: body);
}