RabbitMQ:SpringAMQP Fanout Exchange(扇型交换机)

目录


扇形交换机也叫做广播交换机,通过交换机将消息发送给所有的队列

生产者源码
消费者源码

一、案例需求

  1. 在RabbitMQ控制台中,声明队列fanout.queue1fanout.queue2
  2. 在RabbitMQ控制台中,声明交换机mt.fanout,将两个队列与其绑定。
  3. 在生产者服务中,向交换机mt.fanout发送消息。
  4. 在消费者服务中,编写两个消费者方法,分别监听fanout.queue1fanout.queue2

二、基础配置

首先需要创建两个队列fanout.queue1fanout.queue2

创建一个广播交换机mt.fanout,需要注意的是,在创建交换机的时候需要修改交换机的类型fanount广播交换机

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

三、代码实现

生产者

java 复制代码
/**
* 给交换机发送消息(广播交换机)
 * exchange:交换机的名称
 * routingKey:直接填写NULL
 * Object:传递的参数
 * @throws InterruptedException
 */
@Test
public void fanoutExchangeTest() throws InterruptedException {
    String exchangeName = "mt.fanout";
    String message = "Fanout Exchange ......";
    rabbitTemplate.convertAndSend(exchangeName, null, message);
}

消费者,特别注意的是消费者绑定的是队列,而不是交换机。

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

@RabbitListener(queues = "fanout.queue2")
public void listenFanoutQueue2(String message) throws InterruptedException {
    System.err.println(String.format("消费者2,收到了fanout.queue2: %s", message));
}
相关推荐
yangminlei7 小时前
Spring Boot3集成LiteFlow!轻松实现业务流程编排
java·spring boot·后端
qq_318121597 小时前
互联网大厂Java面试故事:从Spring Boot到微服务架构的技术挑战与解答
java·spring boot·redis·spring cloud·微服务·面试·内容社区
计算机毕设VX:Fegn08957 小时前
计算机毕业设计|基于springboot + vue医院设备管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
J_liaty7 小时前
Spring Boot整合Nacos:从入门到精通
java·spring boot·后端·nacos
2***d8858 小时前
SpringBoot 集成 Activiti 7 工作流引擎
java·spring boot·后端
计算机毕设VX:Fegn08959 小时前
计算机毕业设计|基于springboot + vue小型房屋租赁系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
better_liang9 小时前
每日Java面试场景题知识点之-XXL-JOB分布式任务调度实践
java·spring boot·xxl-job·分布式任务调度·企业级开发
q***o3769 小时前
Spring Boot环境配置
java·spring boot·后端
hhzz9 小时前
Springboot项目中使用POI操作Excel(详细教程系列3/3)
spring boot·后端·excel·poi·easypoi
刀法如飞10 小时前
开箱即用的 DDD(领域驱动设计)工程脚手架,基于 Spring Boot 4.0.1 和 Java 21
java·spring boot·mysql·spring·设计模式·intellij-idea