Exchange
Producer 将消息发送到 Exchange ,由 Exchange 将消息路由到一个或多个 Queue 中(或者丢弃)。Exchange 根据 Routing Key 和 Binding Key 将消息路由到 Queue。不同类型的 Exchange 的路由规则不同。消息队列 AMQP 版目前支持三种类型的 Exchange:
- Direct Exchange
- Topic Exchange
- Fanout Exchange
Direct Exchange
- 路由模式根据 Binding Key = Routing Key 的规则路由消息。
- 使用场景区分发往同一个 Exchange 的消息。
- 示例图 1. Direct Exchange
Direct Exchange 分别与 Queue A 和 Queue B 绑定。Consumer 可以从 Queue A 中拉取所有图片(img)创建(create)消息,从 Queue B 中拉取所有图片(img)日志(log)消息。
- Direct Exchange 绑定 Queue:
- Direct Exchange 和 Queue A 的 Binding Key 为 img.create。
- Direct Exchange 和 Queue B 的 Binding Key 为 img.log。
- Producer 向 Direct Exchange 发送消息:
- 消息 A 的 Routing Key 为 img.create。
- 消息 B 的 Routing Key 为 img.log。
- Direct Exchange 根据 Binding Key = Routing Key 的规则路由消息:
- Routing Key 为 img.create 的消息 A 路由至 Binding Key 为 img.create 的 Queue A。
- Routing Key 为 img.log 的消息 B 路由至 Binding Key 为 img.log 的 Queue B。
Topic Exchange
- 路由规则根据通配符匹配路由消息。
- 星号(*)代表一个单词(例如:cn)。
- 井号(#)代表零个、一个或多个单词,单词间通过英文句号(.)分隔(例如:cn.zj.hz)。
- 使用场景通过 Topic 对消息进行区分。
- 示例图 2. Topic Exchange
Topic Exchange 分别与 Queue A 和 Queue B 绑定。Consumer 可以从 Queue A 中拉取所有中国(cn)杭州(hz)的文件(files),从 Queue B 中拉取所有中国(cn)商店(store)的文件(files)。
- Topic Exchange 绑定 Queue:
- Topic Exchange 和 Queue A 的 Binding Key 为 files.cn.hz.#。
- Topic Exchange 和 Queue B 的 Binding Key 为 files.cn.*.store。
- Producer 向 Topic Exchange 发送消息:
- 消息 A 的 Routing Key 为 files.cn.hz。
- 消息 B 的 Routing Key 为 files.cn.hz.store。
- 消息 C 的 Routing Key 为 files.cn.sz.store。
- Topic Exchange 根据通配符匹配的规则路由消息:
- Routing Key 为 files.cn.hz 的消息 A 路由至 Binding Key 为 files.cn.hz.# 的 Queue A。
- Routing Key 为 files.cn.hz.store 的消息 B 路由至 Binding Key 为 files.cn.hz.# 的 Queue A 和 Binding Key 为 files.cn.*.store 的 Queue B。
- Routing Key 为 files.cn.sz.store 的消息 C 路由至 Binding Key 为 files.cn.*.store 的Queue B。
Fanout Exchange
- 路由规则Fanout Exchange 无视 Routing Key 和 Binding Key 的匹配规则,将消息投递至所有绑定的 Queue。
- 使用场景广播消息。
- 示例图 3. Fanout Exchange
Fanout Exchange 将消息投递至所有绑定的 Queue,Consumer 可以从所有 Queue 中拉取同一消息。
- Fanout Exchange 绑定 Queue:Fanout Exchange 和 Queue A、Queue B、Queue C 的 Binding Key 都可以为任意值。
- Producer 向 Fanout Exchange 发送消息:消息 A 的 Routing Key 可以为任意值。
- Fanout Exchange 将消息路由至所有绑定的 Queue:Routing Key 为任意值的消息 A 分别路由至 Binding Key 为任意值的 Queue A、Queue B、Queue C。