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));
}
相关推荐
xiaoqiMikko1 天前
Dependabot 面板全绿,不代表你的 Tomcat 没洞
java·spring boot
摇滚侠1 天前
SpringBoot 官网 阅读笔记 启用生产就绪功能 端点
spring boot·笔记·后端
evans在进步1 天前
HashMap 为什么线程不安全?ConcurrentHashMap 如何解决?
java·spring boot·spring
华章酱1 天前
基于 RabbitMQ 与 Hyperf 的消息顺序性保障方案
分布式·rabbitmq
小林敲代码77881 天前
Spring Boot 3 升级踩坑:aj-captcha 行为验证码底图加载失效
java·spring boot·后端
程序员阿明1 天前
spring boot3访问resources下的文件,使得在浏览器url中可以直接访问
java·spring boot·后端
霸道流氓气质1 天前
SpringBoot中使用OAuth2 认证与 JWT Token — 概念、原理与实践
java·spring boot·后端
snow@li1 天前
Vue Axios封装与SpringBoot Payload封装全景关联分析(前后端数据交互底层闭环)
前端·vue.js·spring boot
用户3126874877201 天前
Spring Boot 日志体系到底怎么加载的?从 Logback 到 MDC 的全链路拆解
spring boot
paopaokaka_luck1 天前
基于springboot3+vue3的云南本土影视文旅推荐平台(协同过滤算法、Echarts图形化分析)
前端·spring boot·学习·算法·echarts·mybatis