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));
}
相关推荐
一 乐7 小时前
婚纱摄影网站|基于ssm + vue婚纱摄影网站系统(源码+数据库+文档)
前端·javascript·数据库·vue.js·spring boot·后端
期待のcode10 小时前
前后端分离项目 Springboot+vue 在云服务器上的部署
服务器·vue.js·spring boot
ProgramHan10 小时前
Spring Boot 3.2 新特性:虚拟线程的落地实践
java·jvm·spring boot
源码获取_wx:Fegn089511 小时前
基于 vue智慧养老院系统
开发语言·前端·javascript·vue.js·spring boot·后端·课程设计
毕设源码_郑学姐12 小时前
计算机毕业设计springboot基于HTML5的酒店预订管理系统 基于Spring Boot框架的HTML5酒店预订管理平台设计与实现 HTML5与Spring Boot技术驱动的酒店预订管理系统开
spring boot·后端·课程设计
不吃香菜学java12 小时前
spring-依赖注入
java·spring boot·后端·spring·ssm
南部余额12 小时前
Spring Boot 整合 MinIO:封装常用工具类简化文件上传、启动项目初始化桶
java·spring boot·后端·文件上传·工具类·minio·minioutils
QQ196328847512 小时前
ssm基于Springboot+的球鞋销售商城网站vue
vue.js·spring boot·后端
太空眼睛13 小时前
【MCP】使用SpringBoot基于Streamable-HTTP构建MCP-Server
spring boot·sse·curl·mcp·mcp-server·spring-ai·streamable
幽络源小助理13 小时前
springboot校园车辆管理系统源码 – SpringBoot+Vue项目免费下载 | 幽络源
vue.js·spring boot·后端