1、目标
使用springboot完成rabbitmq的消费模式-Fanout
2、实现步骤
- 创建生产者工程:rabbitmq-fanout-producer
- 创建消费者工程:rabbitmq-fanout-consumer
- 引入rabbitmq的依赖
- 进行消息的分发和测试
- 查看和观察web控制台的状况
3、具体实现
创建生产者工程
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
application.yml配置
server:
port: 8082
spring:
rabbitmq:
port: 5672
username: admin
password: admin
host: 110.14.108.40 // rabbimq被我安装在云上,这是云的地址,本地的用127.0.0.1
virtual-host: /
OrderService
@Service
public class OrderService {
@Autowired
private RabbitTemplate rabbitTemplate;
public void send(String msg){
rabbitTemplate.convertAndSend("fanout_exchange","",msg);
}
}
测试类
@SpringBootTest
class RabbitmqFanoutProducerApplicationTests {
@Autowired
private OrderService orderService;
@Test
void contextLoads() {
orderService.send("测试内容");
}
}
创建消费者工程
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
application.yml配置
server:
port: 8081
spring:
rabbitmq:
port: 5672
username: admin
password: admin
host: 110.14.108.40
virtual-host: /
RabbitMqConfig 配置类,定义交换机、消息队列等配置
@Configuration
public class RabbitMqConfig {
// 定义交换机
@Bean
public FanoutExchange fanoutExchange(){
return new FanoutExchange("fanout_exchange");
}
// 定义消息队列
@Bean
public Queue smsQueue(){
return new Queue("sms_fanout_queue");
}
@Bean
public Queue emailQueue(){
return new Queue("email_fanout_queue");
}
// 绑定消息队列和交换机
@Bean
public Binding smsBinding(){
return BindingBuilder.bind(smsQueue()).to(fanoutExchange());
}
@Bean
public Binding emailBinding(){
return BindingBuilder.bind(emailQueue()).to(fanoutExchange());
}
}
EmailService
@Service
@RabbitListener(queues = "email_fanout_queue")
public class EmailService {
@RabbitHandler
public void email(String msg){
System.out.println("email recive------------------>"+msg);
}
}
SmsService
@Service
@RabbitListener(queues = "sms_fanout_queue")
public class SmsService {
@RabbitHandler
public void sms(String msg){
System.out.println("sms recive----------------->"+msg);
}
}
启动消费者项目
交换机和消息队列被生成
启动测试类contextLoads()
消息被发送,consumer消费到被发送的消息