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

目录


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

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

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

生产者源码
消费者源码

一、案例需求

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

二、基础配置

首先创建两个队列topic.queue1topic.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));
}
相关推荐
不爱编程的小九九2 小时前
小九源码-springboot088-宾馆客房管理系统
java·开发语言·spring boot
OxYGC3 小时前
[RabbitMQ] 最新版本深度解析:4.0+ 新特性、性能飞跃与生产实践(2025 年更新)
分布式·rabbitmq
Super Rookie3 小时前
RabbitMQ 自动化脚本安装方案
运维·自动化·rabbitmq
抹香鲸之海3 小时前
Prometheus+Grafana实现Springboot服务监控
spring boot·grafana·prometheus
摇滚侠4 小时前
Spring Boot 3零基础教程,WEB 开发 内嵌服务器底层源码分析 笔记48
spring boot·笔记
萌新小码农‍5 小时前
SpringBoot+alibaba的easyexcel实现前端使用excel表格批量插入
前端·spring boot·excel
韩立学长5 小时前
【开题答辩实录分享】以《租房小程序的设计和实现》为例进行答辩实录分享
java·spring boot·小程序
zl9798995 小时前
SpringBoot-数据访问之MyBatis与Redis
java·spring boot·spring
重生之我是Java开发战士6 小时前
【Java EE】快速上手Spring Boot
java·spring boot·java-ee
不爱编程的小九九8 小时前
小九源码-springboot099-基于Springboot的本科实践教学管理系统
java·spring boot·后端