生产者:
1.创建生产者SpringBoot工程
2.引入依赖坐标
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency>
3.编写yml文件,基本信息配置
# 配置RabbitMQ的基本信息, IP 端口 username password。。。 spring: rabbitmq: host: 192.168.0.103 #ip port: 5673 #配置的mq发消息的端口 username: guest password: guest virtual-host: /
4.定义交换机,队列以及绑定关系的配置类
package com.practice.producer.rabbitmq.config; import org.springframework.amqp.core.*; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @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.队列 @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(); } }
5.注入RabbitTemplate,调用方法,完成消息发送
@SpringBoottest @RunWith(springrunner.class) class ProducerSpringbootApplicationTests { //1.注入RabbitTemplate @Autowired private RabbitTemplate rabbitTemplate; @Test public void testSend() { rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,"boot.haha","boot mq hello~~~"); } }
消费者
1.创建springboot工程
2.引入start,依赖坐标
同上
3.编写yml配置,基本信息配置
同上
4.定义监听类使用@RabbitListener注解完成队列监听
package com.practice.comsumerspringbot; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component public class RabbitLMQListener { //这里监听的队列要跟生产者一致 @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完成消息接收