Fanout模式,即广播模式,一个发送到交换机的消息会被转发到与该交换机绑定的所有队列上。
一、Provider
配置文件
1 spring.application.name=provider
2 spring.rabbitmq.host=192.168.50.30
3 spring.rabbitmq.port=5672
4 spring.rabbitmq.username=rabbit
5 spring.rabbitmq.password=rabbit
6 #设置交换器的名称
7 mq.config.exchange=order.fanout
代码
1 @Component
2 public class Sender {
3 @Autowired
4 private AmqpTemplate amqpTemplate;
5
6 @Value("${mq.config.exchange}")
7 private String exchange;
8
9 public void send(String msg){
10 this.amqpTemplate.convertAndSend(this.exchange, "", msg);
11 }
12 }
二、Consumer
配置文件
1 spring.application.name=consumer
2 spring.rabbitmq.host=192.168.50.30
3 spring.rabbitmq.port=5672
4 spring.rabbitmq.username=rabbit
5 spring.rabbitmq.password=rabbit
6 #设置交换器的名称
7 mq.config.exchange=order.fanout
8 #短信服务队列名称
9 mq.config.queue.sms=order.sms
10 #push 服务队列名称
11 mq.config.queue.push=order.push
代码
SmsReceiver
1 /**
2 @RabbitListener bindings:绑定队列
3 @QueueBinding value:绑定队列的名称
4 exchange:配置交换器
5 key:路由键
6 @Queue value:配置队列名称
7 autoDelete:是否是一个可删除的临时队列
8 @Exchange value:为交换器起个名称
9 type:指定具体的交换器类型
10 */
11 @Component
12 @RabbitListener(
13 bindings=@QueueBinding(
14 value=@Queue(
15 value="${mq.config.queue.sms}",
16 autoDelete="true"
17 ),
18 exchange=@Exchange(
19 value="${mq.config.exchange}",
20 type=ExchangeTypes.FANOUT
21 )
22 )
23 )
24 public class SmsReceiver {
25 @RabbitHandler
26 public void process(String msg) {
27 System.out.println(msg);
28 }
29 }
PushReceiver
1 /**
2 @RabbitListener bindings:绑定队列
3 @QueueBinding value:绑定队列的名称
4 exchange:配置交换器
5 @Queue value:配置队列名称
6 autoDelete:是否是一个可删除的临时队列
7 @Exchange value:为交换器起个名称
8 type:指定具体的交换器类型
9 */
10 @Component
11 @RabbitListener(
12 bindings=@QueueBinding(
13 value=@Queue(
14 value="${mq.config.queue.push}",
15 autoDelete="true"),
16 exchange=@Exchange(
17 value="${mq.config.exchange}",
18 type=ExchangeTypes.FANOUT
19 )
20 )
21 )
22 public class PushReceiver {
23 @RabbitHandler
24 public void process(String msg){
25 System.out.println("Push receiver: " + msg);
26 }
27 }