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));
}
相关推荐
是梦终空14 小时前
JAVA毕业设计253—基于Java+Springboot+vue3+协同过滤推荐算法的传统服饰文化平台(源代码+数据库+任务书+12000字论文)
java·spring boot·vue·毕业设计·课程设计·协同过滤推荐算法·传统服饰文化平台
韩立学长1 天前
基于Springboot流浪动物领养网站0kh2iyb4(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·后端
源码获取_wx:Fegn08951 天前
基于springboot + vue心理健康管理系统
vue.js·spring boot·后端
QD_IT伟1 天前
SpringBoot项目整合Tlog 数据链路的规范加强
java·spring boot·后端
源码获取_wx:Fegn08951 天前
基于springboot + vue二手交易管理系统
java·vue.js·spring boot·后端·spring·课程设计
爬山算法1 天前
Springboot请求和响应相关注解及使用场景
java·spring boot·后端
老华带你飞1 天前
在线教育|基于springboot + vue在线教育系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端
TT哇1 天前
【项目】玄策五子——匹配模块
java·spring boot·websocket·spring·java-ee·maven
VX:Fegn08951 天前
计算机毕业设计|基于springboot + vue音乐管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·课程设计
凌波粒1 天前
Springboot基础教程(9)--Swagger2
java·spring boot·后端