SpringAMQP交换机:Fanout
作者:互联网
与简单消息队列的区别是允许将同一个消息发布给多个消费者,实现方式说加了交换机exchange。
publisher 。。。。。。。。。。。。。exchange。。。。。。。。。。。queue。。。。。。。。。。。。。。。consumer
exchange负责消息路由,而不是存储,路由失败则消息丢失。
exchange的常见类型:
Fanout 广播
Direct 路由
Topic 话题
Fanout 会将收到的消息路由到每个跟其绑定的队列
1.在consumer服务中,利用代码声明队列交换机 并绑定,新建配置类
@Configuration public class FanoutConfig { //声明交换机 @Bean public FanoutExchange fanoutExchange(){ return new FanoutExchange("itcast.fanout"); } //声明队列 @Bean public Queue fanoutQueue1(){ return new Queue("fanout.queue1"); } //绑定 @Bean public Binding fanoutBinding1(Queue fanoutQueue1, FanoutExchange fanoutExchange){ return BindingBuilder.bind(fanoutQueue1).to(fanoutExchange); } @Bean public Queue fanoutQueue2(){ return new Queue("fanout.queue1"); } //绑定 @Bean public Binding fanoutBinding2(Queue fanoutQueue2, FanoutExchange fanoutExchange){ return BindingBuilder.bind(fanoutQueue2).to(fanoutExchange); } }
2.在consumer服务中,编写两个消费者方法,在listener中分别监听fanout.queue1 和fanout.queue2
@RabbitListener(queues = "fanout.queue1") public void listenFanoutQueue1(String msg){ System.out.printf("接收到fanout.queue1:【"+msg+"】"); } @RabbitListener(queues = "fanout.queue2") public void listenFanoutQueue2(String msg){ System.out.printf("接收到fanout.queue2:【"+msg+"】"); }
3.在publisher中编写测试方法,向itcast.fanout发送消息
@Test public void testSendFanoutMessage(){ String exchangeName = "itcast.fanout"; String message = "hello, hey"; rabbitTemplate.convertAndSend(exchangeName,"", message); }
标签:fanout,queue1,fanoutExchange,return,Queue,交换机,SpringAMQP,public,Fanout 来源: https://www.cnblogs.com/timewarlock/p/15533575.html