生产者
步骤:
-
创建Springboot工程
-
导入依赖
<dependency> <groupld>org.springframework.boot</groupld> <artifactld>spring-boot-starter-amqp</artifactld> </dependency>
-
编写yml配置
spring: rabbitmq: host: 192.168.200.128 # ip port: 5672 username: guest password: guest virtual-host: /
-
定义交换机,队列以及绑定关系的配置类
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.Queue 队列 @Bean("bootQueue") public Queue bootQueue(){ return QueueBuilder.durable(QUEUE_NAME).withArgument("x-message-ttl","5000").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(); } }
-
注入RabbitTemplate,调用方法,完成消息发送
import com.itheima.rabbitmq.config.RabbitMQConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @SpringBootTest @RunWith(SpringRunner.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> <groupld>org.springframework.boot</groupld> <artifactld>spring-boot-starter-amqp</artifactld> </dependency>
-
编写yml配置,基本信息配置
spring: rabbitmq: host: 192.168.200.128 #主机ip port: 5672 #端口 username: guest password: guest virtual-host: / publisher-confirms: true publisher-returns: true listener: simple: acknowledge-mode: manual
-
定义监听类,使用@RabbitListener注解完成队列监听。
import com.rabbitmq.client.Channel; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component public class RabbimtMQListener { @RabbitListener(queues = "boot_queue") public void ListenerQueue(Message message, Channel channel){ System.out.println(new String(message.getBody())); } }