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 小时前
Spring Boot Web MVC配置详解
spring boot·后端
初次攀爬者20 小时前
Kafka 基础介绍
spring boot·kafka·消息队列
用户83071968408220 小时前
spring ai alibaba + nacos +mcp 实现mcp服务负载均衡调用实战
spring boot·spring·mcp
Java水解1 天前
SpringBoot3全栈开发实战:从入门到精通的完整指南
spring boot·后端
用户8307196840822 天前
RabbitMQ vs RocketMQ 事务大对决:一个在“裸奔”,一个在“开挂”?
后端·rabbitmq·rocketmq
初次攀爬者2 天前
RocketMQ在Spring Boot上的基础使用
java·spring boot·rocketmq
花花无缺2 天前
搞懂@Autowired 与@Resuorce
java·spring boot·后端
Derek_Smart2 天前
从一次 OOM 事故说起:打造生产级的 JVM 健康检查组件
java·jvm·spring boot
Nyarlathotep01132 天前
SpringBoot Starter的用法以及原理
java·spring boot
dkbnull3 天前
深入理解Spring两大特性:IoC和AOP
spring boot