RabbitMQ:SpringAMQP Topic Exchange(主题交换机)

目录


TopicExchange与DirectExchange类似,区别在于RoutingKey可以是多个单次的列表,并且以.分割。

Queue与Exchange指定BindingKey时可以使用通配符:

  • #:代指0个或多个单词。
  • *:代指一个单词。

生产者源码
消费者源码

一、案例需求

  1. 在RabbitMQ控制台中,声明队列topic.queue1和topic.queue2。
  2. 在RabbitMQ控制台中,声明交换机mt.topic,将两个队列与其绑定。
  3. 在生产者服务中,利用不同的RoutingKey向mt.topic交换机发送消息。
  4. 在消费者服务中,编写两个消费者,分别监听队列topic.queue1和topic.queue2。

二、基础配置

首先创建两个队列topic.queue1和topic.queue2。

创建一个主题交换机mt.topic,需要注意的是,在创建交换机的时候需要修改交换机的类型topic主题交换机。

交换机创建之后,点击交换机的名称,绑定交换机与队列之间的关系。

三、代码实现

生产者

java 复制代码
/**
 * 给交换机发送消息(主题交换机)
 * @throws InterruptedException
 */
@Test
public void topicExchangeTest() throws InterruptedException {
    String exchangeName = "mt.topic";
    String message = "黄色警报 ......";
//        rabbitTemplate.convertAndSend(exchangeName, "china.news", message);
//        rabbitTemplate.convertAndSend(exchangeName, "japan.news", message);
    rabbitTemplate.convertAndSend(exchangeName, "china.weather", message);
}

消费者

java 复制代码
@RabbitListener(queues = "topic.queue1")
public void listenTopicQueue1(String message) throws InterruptedException {
    System.out.println(String.format("消费者1,收到了topic.queue1: %s", message));
}

@RabbitListener(queues = "topic.queue2")
public void listenTopicQueue2(String message) throws InterruptedException {
    System.err.println(String.format("消费者2,收到了topic.queue2: %s", message));
}
相关推荐
织码weavecodes6 小时前
Spring Boot 接入 AI 图像生成:模型适配、图片转存与 Redis 清理
人工智能·spring boot·redis
Dreams_l10 小时前
基于SpringBoot实现的抽奖系统(四)
java·spring boot·后端
耀耀_很无聊13 小时前
17_Spring Boot 使用 MDC 实现 TraceId 日志追踪
java·spring boot·后端
CoderYanger14 小时前
Java EE 进阶:15. Linux基本使用和程序部署(第二弹):部署 Web 项目到 Linux
linux·服务器·数据库·spring boot·spring·阿里云·java-ee
程序员小杰@15 小时前
SpringBoot + SpringCloudAlibaba 日志 & 链路追踪 完整总结
java·spring boot·后端
IT研究室17 小时前
最新计算机毕业设计选题推荐-基于spring boot的房屋交易系统-网站-文档指导-Java-springboot
java·spring boot·课程设计
RuoyiOffice17 小时前
Java物联网项目拆解:设备接入之后,数据怎样真正用起来
java·vue.js·spring boot·物联网·iot·企业管理·ruoyi office
淘源码A19 小时前
智能预问诊系统源码,基于SpringBoot、MyBatis-Plus、uni-app等技术栈,开箱即用
java·spring boot·源码·二次开发·电子病历·预问诊·智能预问诊
IT枫斗者1 天前
MQ 选型对比:RocketMQ、RabbitMQ、Kafka 各自适合什么场景
开发语言·人工智能·分布式·kafka·rabbitmq·rocketmq
钱栈up1 天前
删 18 个模块全程零报错:烧结系统单体拆微服务的 P0 实操
spring boot·微服务