0
点赞
收藏
分享

微信扫一扫

SpringBoot-RabbitMQ05-交换器【fanout】介绍

交换器介绍

  RabbitMQ中有三种主要的交互器分别如下

交换器

说明

direct

发布与订阅 完全匹配

fanout

广播

topic

主体,规则匹配

Fanout

  FanoutExchange 的数据交换策略是把所有到达 FanoutExchang 的消息转发给所有与它绑定的Queue ,在这种策略中, routingkey 将不起任何作用.

SpringBoot-RabbitMQ05-交换器【fanout】介绍_spring

SpringBoot-RabbitMQ05-交换器【fanout】介绍_fanout_02

1.创建消费者

项目结构

SpringBoot-RabbitMQ05-交换器【fanout】介绍_ide_03

配置文件

spring.application.name=springcloud-mq
spring.rabbitmq.host=192.168.88.150
spring.rabbitmq.port=5672
spring.rabbitmq.username=dpb
spring.rabbitmq.password=123

mq.config.exchange=order.fanout
#短信服务队列名称
mq.config.queue.sms=order.sms
#push 服务队列名称
mq.config.queue.push=order.push

两个消费者

@Component
@RabbitListener(
bindings=@QueueBinding(
value=@Queue(value="${mq.config.queue.sms}",autoDelete="true"),
exchange=@Exchange(value="${mq.config.exchange}",type= ExchangeTypes.FANOUT)
)
)
public class SmsReciver {
/**
* 接收消息的方法。采用消息队列监听机制
* @param msg
*/
@RabbitHandler
public void process(String msg){
System.out.println("Sms........receiver: "+msg);
}
}
@Component
@RabbitListener(
bindings=@QueueBinding(
value=@Queue(value="${mq.config.queue.push}",autoDelete="true"),
exchange=@Exchange(value="${mq.config.exchange}",type= ExchangeTypes.FANOUT)
)
)
public class PushReciver {
/**
* 接收消息的方法。采用消息队列监听机制
* @param msg
*/
@RabbitHandler
public void process(String msg){
System.out.println("Push........receiver: "+msg);
}
}

启动后等待接收消息即可~

2.创建订单服务

项目结构

SpringBoot-RabbitMQ05-交换器【fanout】介绍_spring_04

配置文件

spring.application.name=springcloud-mq
spring.rabbitmq.host=192.168.88.150
spring.rabbitmq.port=5672
spring.rabbitmq.username=dpb
spring.rabbitmq.password=123
#设置交换器的名称
mq.config.exchange=order.fanout

服务提供者

/**
* @program: rabbitmq-direct-provider
* @description: 发送者
* @author: 波波烤鸭
* @create: 2019-05-22 15:51
*/
@Component
public class Sender {
@Autowired
private AmqpTemplate rabbitAmqpTemplate;
//exchange 交换器名称
@Value("${mq.config.exchange}")
private String exchange;
/*
* 发送消息的方法
*/
public void send(String msg){
//向消息队列发送消息
//参数一:交换器名称。
//参数二:路由键
//参数三:消息
this.rabbitAmqpTemplate.convertAndSend(this.exchange,"", msg);
}
}

单元测试

@RunWith(SpringRunner.class)
@SpringBootTest(classes = RabbitmqDirectProviderApplication.class)
public class RabbitmqDirectProviderApplicationTests {

@Autowired
private Sender sender;

@Test
public void contextLoads() throws Exception{
sender.send("hello .... ");
}
}

启动后查看消费者的控制台

SpringBoot-RabbitMQ05-交换器【fanout】介绍_fanout_05


举报

相关推荐

0 条评论