一、添加Maven依赖项
<!-- 1. 父工程依赖-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
</parent>
<dependencies>
<!--2. 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>
二、编写yml配置文件,包含rabbitmq的ip、端口、账号、密码和虚拟机等
# 配置RabbitMQ的基本信息 ip 端口 username password..
spring:
rabbitmq:
host: 192.168.100.129 # ip
port: 5672
username: guest
password: guest
virtual-host: itcast
三、生产者代码
编写配置文件,配置交换机和队列,代码如下:
@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();
}
/*
1. 知道哪个队列
2. 知道哪个交换机
3. routing key
*/
//3. 队列和交互机绑定 Binding
@Bean
public Binding bindQueueExchange(@Qualifier("bootQueue") Queue queue, @Qualifier("bootExchange") Exchange exchange){
return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
}
}
四、消费者代码
编写一个监听器类即可,监听某个队列的消息,代码如下:
@Component
public class RabbimtMQListener {
//监听队列名为boot_queue的消息
@RabbitListener(queues = "boot_queue")
public void ListenerQueue(Message message){
//System.out.println(message);
System.out.println(new String(message.getBody()));
}
}
五、测试
在生产者工程中编写测试类,代码如下:
@SpringBootTest
@RunWith(SpringRunner.class)
public class ProducerTest {
//1.注入RabbitTemplate
@Autowired
private RabbitTemplate rabbitTemplate;
//发送routingKey为boot.haha,消息内容为boot mq hello~~~的消息
//EXCHANGE_NAME = "boot_topic_exchange"
@Test
public void testSend(){
rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,"boot.haha","boot mq hello~~~");
}
}
1、消息发送之前可以看到消息为0
2、测试类运行后发送消息后,消息队列boot_queue中存储着一条消息
3、启动消费者的启动类,可以看到控制台打印接收的消息: