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));
}
相关推荐
JH30739 小时前
SpringBoot 优雅处理金额格式化:拦截器+自定义注解方案
java·spring boot·spring
qq_124987075312 小时前
基于SSM的动物保护系统的设计与实现(源码+论文+部署+安装)
java·数据库·spring boot·毕业设计·ssm·计算机毕业设计
Coder_Boy_12 小时前
基于SpringAI的在线考试系统-考试系统开发流程案例
java·数据库·人工智能·spring boot·后端
2301_8187320612 小时前
前端调用控制层接口,进不去,报错415,类型不匹配
java·spring boot·spring·tomcat·intellij-idea
汤姆yu16 小时前
基于springboot的尿毒症健康管理系统
java·spring boot·后端
暮色妖娆丶16 小时前
Spring 源码分析 单例 Bean 的创建过程
spring boot·后端·spring
biyezuopinvip17 小时前
基于Spring Boot的企业网盘的设计与实现(任务书)
java·spring boot·后端·vue·ssm·任务书·企业网盘的设计与实现
JavaGuide17 小时前
一款悄然崛起的国产规则引擎,让业务编排效率提升 10 倍!
java·spring boot
figo10tf18 小时前
Spring Boot项目集成Redisson 原始依赖与 Spring Boot Starter 的流程
java·spring boot·后端
zhangyi_viva18 小时前
Spring Boot(七):Swagger 接口文档
java·spring boot·后端