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));
}
相关推荐
程序猿小蒜5 分钟前
基于springboot的汽车资讯网站开发与实现
java·前端·spring boot·后端·spring
それども5 分钟前
SpringBoot 切面AOP获取注解为null
java·spring boot·spring
q***98527 分钟前
前端的dist包放到后端springboot项目下一起打包
前端·spring boot·后端
vx_bisheyuange7 分钟前
基于SpringBoot的热门旅游推荐系统设计与实现
java·spring boot·后端·毕业设计
代码or搬砖9 分钟前
SpringBoot整合SpringMVC
java·spring boot·后端
程序定小飞9 分钟前
基于springboot的汽车资讯网站开发与实现
java·开发语言·spring boot·后端·spring
大米粥哥哥24 分钟前
Qt 使用QAMQP连接RabbitMQ
开发语言·qt·rabbitmq·qamqp
毕设源码-钟学长1 小时前
【开题答辩全过程】以 基于springboot的在线影院系统设为例,包含答辩的问题和答案
java·spring boot·后端
xiezhr1 小时前
Java开发中那些常见的坑,你踩过几个?
java·spring boot·spring
q***23571 小时前
Spring Boot+Vue项目从零入手
vue.js·spring boot·后端