🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] # 简介 Fanout 就是我们熟悉的⼴播模式或者订阅模式,给 Fanout 交换机发送消息,绑定了这个交换机的所有队列都收到这个消息 # 定义队列 这⾥使⽤了 A、B 两个个队列绑定到 Fanout 交换机上⾯,发送端的 routing\_key 写任何字符都会被忽略 ~~~ import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.BindingBuilder; import org.springframework.amqp.core.FanoutExchange; import org.springframework.amqp.core.Queue; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class RabbitConfig { /** * 定义队列 */ @Bean public Queue AMessage() { return new Queue("fanout.A"); } @Bean public Queue BMessage() { return new Queue("fanout.B"); } @Bean public Queue CMessage() { return new Queue("fanout.C"); } /** * 定义交换机 */ @Bean FanoutExchange fanoutExchange() { return new FanoutExchange("fanoutExchange"); } /** * 分部进⾏绑定 */ @Bean Binding bindingExchangeA(Queue AMessage, FanoutExchange fanoutExchange) { return BindingBuilder.bind(AMessage).to(fanoutExchange); } @Bean Binding bindingExchangeB(Queue BMessage, FanoutExchange fanoutExchange) { return BindingBuilder.bind(BMessage).to(fanoutExchange); } } ~~~ # 定义发送者 ~~~ import org.springframework.amqp.core.AmqpTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class FanoutSender { @Autowired private AmqpTemplate rabbitTemplate; public void send() { String context = "hi, fanout msg "; System.out.println("Sender : " + context); this.rabbitTemplate.convertAndSend("fanoutExchange","", context); } } ~~~ # 定义接收者 **接收者A** ~~~ import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component @RabbitListener(queues = "fanout.A") public class FanoutReceiverA { @RabbitHandler public void process(String message) { System.out.println("fanout Receiver A: " + message); } } ~~~ **接收者B** ~~~ import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component @RabbitListener(queues = "fanout.B") public class FanoutReceiverB { @RabbitHandler public void process(String message) { System.out.println("fanout Receiver B: " + message); } } ~~~ # 测试 绑定到 fanout 交换机上⾯的队列都收到了消息 ~~~ @Autowired private FanoutSender sender; @Test public void fanoutSender() throws Exception { sender.send(); Thread.sleep(1000L); } ~~~