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));
}
相关推荐
lzp079118 小时前
元数据驱动开发 - 面向对象编程思想的补充(上)
spring boot·后端·ui
happymaker06261 天前
SpringBoot学习日记——DAY06(整合MyBatisPlus的其他功能)
java·spring boot·学习
孟林洁1 天前
Java转AI应用开发速成(3)—— 第一个 SpringAI 聊天应用
java·spring boot·后端·ai·机器人
EnCi Zheng1 天前
01-如何监听接口调用情况?
java·spring boot·后端
苏渡苇1 天前
强强联合:OpenFeign 整合 Sentinel
spring boot·spring cloud·微服务·sentinel·openfeign
程序员buddha1 天前
Spring Boot框架,类注入成 Bean的方式
java·spring boot·后端
希望永不加班1 天前
SpringBoot 消费者并发控制:线程池配置
java·spring boot·后端·spring
i220818 Faiz Ul2 天前
理财系统|基于java+vue的家庭理财系统小程序(源码+数据库+文档)
java·vue.js·spring boot·小程序·论文·毕设·理财系统
Byron__2 天前
SpringBoot 核心面试知识点(自动配置/启动流程/注解/Starter)
spring boot·后端·面试
一 乐2 天前
个人博客系统|基于Springboot的个人博客系统设计与实现(源码+数据库+文档)
java·数据库·spring boot·后端·论文·毕设·个人博客系统