广播嘛,消息发送者发送了消息,只要是使用广播的接收者,也就是Fanout类型的队列都会接收到这条消息。
目录
首先创建两个项目
rabbitmq_fanout_consumer 消息接收者和 rabbitmq_fanout_provider消息发送者
配置yml文件
rabbitmq_fanout_consumer 消息接收者
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
#设置交换器的名称
mq.config.exchange: order.fanout
#短信服务队列名称
mq.config.queue.sms: order.sms
#push服务队列名称
mq.config.queue.push: order.push
rabbitmq_fanout_provider消息发送者
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
#设置交换器的名称
mq.config.exchange: order.fanout
编写Consumer消息接收者
SmsReceiver
package com.lgh.rabbit_mq.config;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;
/**
* 消息接收者
* @RabbitListener bindings:绑定队列
* @QueueBinding value:绑定队列的名称
* exchange:配置交换器
*
* @Queue value:配置队列名称
* autoDelete:是否是一个可删除的临时队列
*
* @Exchange value:为交换器起个名称
* type:指定具体的交换器类型
*/
@Component
@RabbitListener(
bindings=@QueueBinding(
value=@Queue(
value="${mq.config.queue.sms}",
autoDelete="true"),
exchange=@Exchange(
value="${mq.config.exchange}",
type=ExchangeTypes.FANOUT),
key="*.log.error"))
public class SmsReceiver{
@RabbitHandler
public void process(String msg) {
System.out.println("Sms........receiver:" + msg);
}
}
PushReceiver
package com.lgh.rabbit_mq.config;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;
/**
* 消息接收者
* @RabbitListener bindings:绑定队列
* @QueueBinding value:绑定队列的名称
* exchange:配置交换器
*
* @Queue value:配置队列名称
* autoDelete:是否是一个可删除的临时队列
*
* @Exchange value:为交换器起个名称
* type:指定具体的交换器类型
*/
@Component
@RabbitListener(
bindings=@QueueBinding(
value=@Queue(
value="${mq.config.queue.push}",
autoDelete="true"),
exchange=@Exchange(
value="${mq.config.exchange}",
type=ExchangeTypes.FANOUT),
key="*.log.error"))
public class PushReceiver{
@RabbitHandler
public void process(String msg) {
System.out.println("push........receiver:" + msg);
}
}
编写Provider消息发送者
package com.lgh.rabbitmq.config;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 消息发送者
**/
@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);
}
}