生产端
- 创建生产者SpringBoot工程
- 引入start,依赖坐标
- 编写yml配置,基本信息配置
- 定义交换机,队列以及绑定关系的配置类
- 注入RabbitTemplate,调用方法,完成消息发送
1)导入依赖
<dependencies>
<!--rabbitmq-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
2)编写application.yml配置
# 配置RabbitMQ的基本信息 ip 端口 username password..
spring:
rabbitmq:
host: 172.16.98.133 # ip
port: 5672
username: guest
password: guest
virtual-host: /
3)编写RabbitMQConfig配置类
@Configuration
public class RabbitMQConfig {
public static final String EXCHANGE_NAME = "boot_topic_exchange";
public static final String QUEUE_NAME = "boot_queue";
//1.交换机
@Bean("bootExchange")
public Exchange bootExchange(){
return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
}
//2.Queue 队列
@Bean("bootQueue")
public Queue bootQueue(){
return QueueBuilder.durable(QUEUE_NAME).build();
}
//3. 队列和交互机绑定关系 Binding
/*
1. 知道哪个队列
2. 知道哪个交换机
3. routing key
*/
@Bean
public Binding bindQueueExchange(@Qualifier("bootQueue") Queue queue, @Qualifier("bootExchange") Exchange exchange){
return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
}
}
4)编写发送消息的代码
@SpringBootTest
@RunWith(SpringRunner.class)
public class ProducerTest {
//1.注入RabbitTemplate
@Autowired
private RabbitTemplate rabbitTemplate;
//topic主题模式
@Test
public void testSend(){
//参数1:表示交换机的名称
//参数2:表示路由key的名称
//参数3:表示发送消息的内容body
rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,"boot.haha","boot mq hello~~~");
}
}
消费端
- 创建消费者SpringBoot工程
- 引入start,依赖坐标
- 编写yml配置,基本信息配置
- 定义监听类,使用@RabbitListener注解完成队列监听。
1)导入依赖
<dependencies>
<!--RabbitMQ 启动依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
</dependencies>
2)配置application.yml配置文件
spring:
rabbitmq:
host: 172.16.98.133 #主机ip
port: 5672 #端口
username: guest
password: guest
virtual-host: /
3)编写监听类
@Component
public class RabbimtMQListener {
//使用@RabbitListener注解,用来监听boot_queue这个队列的消息
@RabbitListener(queues = "boot_queue")
public void ListenerQueue(Message message){
//System.out.println(message);
System.out.println(new String(message.getBody()));
}
}
小结
- SpringBoot提供了快速整合RabbitMQ的方式
- 基本信息再yml中配置,队列交互机以及绑定关系在配置类中使用Bean的方式配置
- 生产端直接注入RabbitTemplate完成消息发送
- 消费端直接使用@RabbitListener完成消息接收