SpringBoot整合RabbitMQ
生产者:
- 创建生产者SpringBoot工程
- 引入依赖坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
- 编写yml配置,基本信息配置
- 定义交换机,队列以及绑定关系的配置类
- 注入RabbitTemplate,调用方法,完成消息发送
配置文件:
# 配置rabbitMq的基本信息
spring:
rabbitmq:
host: 118.178.241.65 # 主机名
port: 5672
username: 你的账号
password: 你的密码
virtual-host: /你的虚拟主机
配置类代码:
/**
* rabbitmq配置类
*
* @author liu xiang zheng
* @data 4.14 15:55
**/
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(){
// durable 是否持久化
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();
}
}
测试代码:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ProducerApplication.class)
public class ProducerTest {
// 1.注入RabbitTemplate
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void testSend(){
rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,"boot.haha","boot mq hello~~~");
}
}
消费者:
- 创建消费者SpringBoot工程
- 引入start,引入依赖坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
- 编写yml配置,基本信息配置
- 定义监听类,使用@RabbitListener注解完成队列监听
测试代码:
/**
* 消费者
*
* @author liu xiang zheng
* @data 4.14 20:12
**/
@Component // 被springboot所识别
public class RabbitMQListener {
@RabbitListener(queues = "boot_queue")
public void ListenerQueue(Message message){
System.out.println(message);
}
小结:
- SpringBoot提供了快速整合RabbitMQ的方式
- 基本信息在yml中配置,队列交互机以及绑定关系在配置类中使用Bean的方式配置
- 生产端直接注入RabbitTemplate完成消息发送
- 消费端直接使用@RabbitListener完成消息接收