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));
}
相关推荐
皮皮林5511 天前
SpringBoot 全局/局部双模式 Gzip 压缩实战:14MB GeoJSON 秒变 3MB
java·spring boot
weixin_456904271 天前
Spring Boot 用户管理系统
java·spring boot·后端
奔跑吧邓邓子1 天前
【Java实战㉞】从0到1:Spring Boot Web开发与接口设计实战
java·spring boot·实战·web开发·接口设计
茶本无香1 天前
深入理解Spring Boot的EnvironmentPostProcessor:环境处理的黑科技
spring boot
奔跑吧邓邓子1 天前
【Java实战㉝】Spring Boot实战:从入门到自动配置的进阶之路
java·spring boot·实战·自动配置
ONLYOFFICE1 天前
【技术教程】如何将ONLYOFFICE文档集成到使用Spring Boot框架编写的Java Web应用程序中
java·spring boot·编辑器
上官浩仁1 天前
springboot redisson 缓存入门与实战
spring boot·redis·缓存
小小工匠1 天前
SpringBoot - Spring 资源加载全解析:ResourceLoader 与 ResourceUtils 的正确打开方式
spring boot·spring·resourceloader·resourcutils
little_xianzhong1 天前
关于对逾期提醒的定时任务~改进完善
java·数据库·spring boot·spring·mybatis
苹果醋31 天前
数据库索引设计:在 MongoDB 中创建高效索引的策略
java·运维·spring boot·mysql·nginx