Exchange 类型
direct、topic、fanout、headers。
35 分钟
Exchange 类型
Exchange 决定消息如何到达 Queue。direct 精确匹配 routing key,topic 模式匹配,fanout 广播,headers 按头属性路由。这是 RabbitMQ 相对 Kafka「单一 Topic」最灵活之处。
学习目标
- 配置四种 Exchange 并完成 Binding
- 为订单事件设计 topic routing key 命名
- 理解 fanout 与 redis-pubsub 广播的差异
核心内容
direct:点对点路由
channel.exchangeDeclare("coderoadmap.direct", BuiltinExchangeType.DIRECT, true);
channel.queueBind("queue.email", "coderoadmap.direct", "notify.email");
channel.queueBind("queue.sms", "coderoadmap.direct", "notify.sms");
channel.basicPublish("coderoadmap.direct", "notify.email", null, body);
routing key 必须 完全一致 才进对应队列。适合「一种任务一种队列」。
topic:模式订阅
channel.exchangeDeclare("coderoadmap.topic", BuiltinExchangeType.TOPIC, true);
channel.queueBind("queue.order.all", "coderoadmap.topic", "order.*");
channel.queueBind("queue.order.paid", "coderoadmap.topic", "order.paid");
channel.basicPublish("coderoadmap.topic", "order.paid", null, body);
* 匹配一词,# 匹配零或多个词。订单域可用 order.created、order.paid 分级;综合练习见 rmq-practice。
fanout 与 headers
fanout 忽略 routing key,绑定队列全收——类似 Redis Pub/Sub 或 Kafka 多 consumer group 各读一遍,但消息 ack 后删除,不能按 offset 重放(kafka-vs-mq)。
headers 用 x-match: all|any 匹配消息头,适合 routing key 难以表达的多维过滤;日常 topic 更常见。
Spring 声明(预览)
@Bean
TopicExchange orderExchange() {
return new TopicExchange("coderoadmap.topic", true, false);
}
完整 Spring 配置在 rmq-spring。
练习
- 用 topic 让
order.*进审计队列,仅order.paid进财务队列 - fanout 绑定两个队列,发一条消息验证双收