本节讲解 RabbitMQ 与 Spring Boot 的整合方式。需提前准备好 Spring 项目基本框架。
整合时有两种方式创建交换机、队列及它们的绑定关系:
- 添加配置类(加上@Configuration注解和@Bean注解),适用于 topic 模式、direct 模式,也需要用到@RabbitListener,只起监听队列的作用。
- 用注解创建(@RabbitListener),注解中的内容比之增加,用来创建交换机、队列及它们的绑定关系,以及监听队列。
Fanout 模式
1. 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
然后在 Spring 项目中创建两个模块,一个生产者模块,一个消费者模块。
2. 在 yml/properties 文件进行相应的配置
分别在两个模块中都进行创建。
server:
port: 8080
spring:
application:
name: RabbitMQ-demo
rabbitmq:
username: guest
password: guest
virtual-host: /
host: 127.0.0.1
port: 5672
3. 创建配置类(创建相应的交换机与队列,且绑定关系)
分别在两个模块中都进行创建(防止一方没有配置类启动时报错)。
package com.lx.producer.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
org.springframework.amqp.core.Queue;
org.springframework.context.annotation.Bean;
org.springframework.context.annotation.Configuration;
{
FanoutExchange {
(, , );
}
Queue {
(, );
}
Queue {
(, );
}
Queue {
(, );
}
Binding {
BindingBuilder.bind(smsQueue()).to(fanoutExchange());
}
Binding {
BindingBuilder.bind(duanxinQueue()).to(fanoutExchange());
}
Binding {
BindingBuilder.bind(emailQueue()).to(fanoutExchange());
}
}

