1、简介
Fanout,英文翻译是扇出。
![](https://file.jishuzhan.net/article/1750325995400859649/2d1f411ac6931d535a5edc239bf66d5d.webp)
2、 特点
1) 可以有多个队列
2) 每个队列都要绑定到Exchange(交换机)
3) 生产者发送的消息,只能发送到交换机
4) 交换机把消息发送给绑定过的所有队列
5) 订阅队列的消费者都能拿到消息
3、设置队列
![](https://file.jishuzhan.net/article/1750325995400859649/b34f172b3c1c1d09a8656874c249f38a.webp)
4、设置交换机
![](https://file.jishuzhan.net/article/1750325995400859649/3f41a135af629eee7d09af2ac15afa11.webp)
5、绑定队列
![](https://file.jishuzhan.net/article/1750325995400859649/e2fa4077fca2544d70690af208e6c67c.webp)
6、设置生产者
java
@Test
void testSendFanout() {
String exchangeName = "test.fanout";
String msg = "hello, everyone!";
rabbitTemplate.convertAndSend(exchangeName, null, msg);
}
7、设置消费者
java
@RabbitListener(queues = "fanout.queue1")
public void listenFanoutQueue1(String msg) throws InterruptedException {
System.out.println("消费者1 收到了 fanout.queue1的消息----:【" + msg +"】");
}
@RabbitListener(queues = "fanout.queue2")
public void listenFanoutQueue2(String msg) throws InterruptedException {
System.out.println("消费者2 收到了 fanout.queue2的消息====:【" + msg +"】");
}
8、测试
![](https://file.jishuzhan.net/article/1750325995400859649/dd3f3e95ae6c295b8ad97d3f1fee3726.webp)
9、总结
交换机的作用是什么?
接收publisher发送的消息
将消息按照规则路由到与之绑定的队列
不能缓存消息,路由失败,消息丢失
FanoutExchange会将消息路由到每个绑定的队列