Fanout交换器特点:
各个队列与Topic交换器之间没有路由键绑定配置,发送者发送一条消息给交换器,只要与此交换器绑定的队列,都会接收到消息。
生产者module,只需要指定交换器,发送消息也只需要指定交换器即可
pom.xml导入RabbitMQ坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
application.properties配置RabbitMQ信息
#RabbitMQ基本信息
spring.rabbitmq.host=182.61.40.184
spring.rabbitmq.port=5672
spring.rabbitmq.username=rabbitmq
spring.rabbitmq.password=rabbitmq
#自定义配置
#设置交换器名称
spring.rabbitmq.exchange.name=fanoutExchange
创建Controller,通过浏览器请求,发送消息到RabbitMQ
@Controller
public class RabbitMQController {
@Autowired
private AmqpTemplate amqpTemplate;
@Value("${spring.rabbitmq.exchange.name}")
String exchange;
@RequestMapping(value="/fanoutExchangeTest",method=RequestMethod.GET)
@ResponseBody
public void fanoutExchangeTest() throws InterruptedException {
while (true) {
Thread.sleep(1000);
amqpTemplate.convertAndSend(exchange, "", "fanoutExchange....");
}
}
}
创建消息消费者module:编写队列消息处理组件,配置队列名称,交换器名称和类型,并进行绑定。
pom.xml导入RabbitMQ坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
application.properties配置RabbitMQ信息
#RabbitMQ基本信息
spring.rabbitmq.host=182.61.40.184
spring.rabbitmq.port=5672
spring.rabbitmq.username=rabbitmq
spring.rabbitmq.password=rabbitmq
#自定义信息
#设置交换器名称
spring.rabbitmq.exchageName=fanoutExchange
#设置队列A名称
spring.rabbitmq.queueA=fanoutQueueA
#设置队列B名称
spring.rabbitmq.queueB=fanoutQueueB
队列A处理消息组件
@Component
@RabbitListener(
bindings = @QueueBinding(
value = @Queue(value = "${spring.rabbitmq.queueA}",autoDelete = "true"),
exchange = @Exchange(value="${spring.rabbitmq.exchageName}",type = ExchangeTypes.FANOUT)
)
)
public class RabbitMQComponentA {
@RabbitHandler
public void getMessage(String msg) {
System.out.println("队列fanoutQueueA收到消息:" + msg + ".........");
}
}
队列B处理消息组件
@Component
@RabbitListener(
bindings = @QueueBinding(
value = @Queue(value = "${spring.rabbitmq.queueB}",autoDelete = "true"),
exchange = @Exchange(value="${spring.rabbitmq.exchageName}",type = ExchangeTypes.FANOUT)
)
)
public class RabbitMQComponentB {
@RabbitHandler
public void getMessage(String msg) {
System.out.println("队列fanoutQueueB收到消息:" + msg + ".........");
}
}
测试:
启动两个module,访问Controller。
来源:CSDN
作者:Lonely || Soul
链接:https://blog.csdn.net/qq_39115469/article/details/104574770