全书目录

第二十一篇:RabbitMQ 完全指南 —— 城市智能快递调度中心宇宙

第四章:三种最重要的交换机,分别像什么分拣策略

1 分钟 386 字 第 386 / 962 个阅读单元
#1. direct:按“精确标签”分拣

direct 最像快递中心里“按明确分区编号投放”。

只有标签完全匹配,才会进入对应队列。

text
routing_key = "parcel.create"

direct exchange
   ├── binding key = "parcel.create"   -> 命中
   ├── binding key = "parcel.cancel"   -> 不命中
   └── binding key = "order.paid"      -> 不命中

代码片段:

python
channel.exchange_declare(exchange="parcel.dispatch", exchange_type="direct", durable=True)

channel.queue_bind(queue="parcel.create.q", exchange="parcel.dispatch", routing_key="parcel.create")
channel.queue_bind(queue="parcel.cancel.q", exchange="parcel.dispatch", routing_key="parcel.cancel")

适合:

  • 明确任务类型分发
  • 订单创建、发货、退款这类离散命令
  • 不需要模糊匹配的业务路由

#2. fanout:无脑全城广播

fanout 最像“全城广播喇叭”。

它不看 routing key,来一票包裹,就复制给所有已绑定队列。

text
Producer
   |
   v
fanout exchange
   ├── audit.q
   ├── monitor.q
   └── notify.q

结果:每个队列都拿到一份

代码片段:

python
channel.exchange_declare(exchange="city.broadcast", exchange_type="fanout", durable=True)

channel.queue_bind(queue="audit.q", exchange="city.broadcast")
channel.queue_bind(queue="monitor.q", exchange="city.broadcast")
channel.queue_bind(queue="notify.q", exchange="city.broadcast")

适合:

  • 广播通知
  • 日志复制
  • 多系统同时订阅同一事件

不适合:

  • 只想让一个处理者接单
  • 需要精确筛选的路由

#3. topic:按“标签模式”分拣

topic 最像“多段式标签匹配”。

比如标签写成:

text
业务域.动作.地区
parcel.created.shanghai
parcel.created.beijing
parcel.failed.hangzhou

绑定规则不是写死一个字符串,而是写模式:

  • *:匹配一个单词
  • #:匹配零个或多个单词

例如:

text
binding key = parcel.*
不合法心智:以为能匹配 parcel.created.shanghai
实际:只能匹配两段,不会命中三段

binding key = parcel.created.*
可以匹配:
- parcel.created.shanghai
- parcel.created.beijing

binding key = parcel.#
可以匹配所有 parcel 开头的标签

代码片段:

python
channel.exchange_declare(exchange="parcel.topic", exchange_type="topic", durable=True)

channel.queue_bind(queue="created.all.q", exchange="parcel.topic", routing_key="parcel.created.*")
channel.queue_bind(queue="parcel.all.q", exchange="parcel.topic", routing_key="parcel.#")

适合:

  • 事件类别较多
  • 希望按“领域.动作.来源”组织消息
  • 多团队共享同一总线,但订阅粒度不同