MQ教程 | Exchange(交换机)

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)消息。

  1. Direct Exchange 绑定 Queue:
    • Direct Exchange 和 Queue A 的 Binding Key 为 img.create
    • Direct Exchange 和 Queue B 的 Binding Key 为 img.log
  2. Producer 向 Direct Exchange 发送消息:
    • 消息 A 的 Routing Key 为 img.create
    • 消息 B 的 Routing Key 为 img.log
  3. 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)。

  1. Topic Exchange 绑定 Queue:
    • Topic Exchange 和 Queue A 的 Binding Key 为 files.cn.hz.#
    • Topic Exchange 和 Queue B 的 Binding Key 为 files.cn.*.store
  2. Producer 向 Topic Exchange 发送消息:
    • 消息 A 的 Routing Key 为 files.cn.hz
    • 消息 B 的 Routing Key 为 files.cn.hz.store
    • 消息 C 的 Routing Key 为 files.cn.sz.store
  3. 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 中拉取同一消息。

  1. Fanout Exchange 绑定 Queue:Fanout Exchange 和 Queue A、Queue B、Queue C 的 Binding Key 都可以为任意值。
  2. Producer 向 Fanout Exchange 发送消息:消息 A 的 Routing Key 可以为任意值。
  3. Fanout Exchange 将消息路由至所有绑定的 Queue:Routing Key 为任意值的消息 A 分别路由至 Binding Key 为任意值的 Queue A、Queue B、Queue C。

转载: MQ教程 | Exchange(交换机)介绍(六)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值