一、搭建生产者工程

创建SpringBoot 项目:producer-springboot

1、添加依赖

1
2
3
4
5
6
7
8
9
10
11
12
<!-- rabbitmq -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>

2、配置文件

配置application.yml配置文件

1
2
3
4
5
6
7
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
virtual-host: /

3、创建配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.atguigu.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";

// 交换机
@Bean("bootExchange")
public Exchange bootExchange() {
// durable:是否持久化,当mq重启之后,还在
return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
}

// 队列
@Bean("bootQueue")
public Queue bootQueue() {
return QueueBuilder.durable(QUEUE_NAME).build();
}

// 队列和交换机绑定
@Bean
public Binding bindQueueExchange(@Qualifier("bootQueue") Queue queue,
@Qualifier("bootExchange") Exchange exchange) {
// noargs():表示不指定参数
return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
}
}

4、发送消息

在 test 目录下创建测试文件 ProducerTest.java

1
2
3
4
5
6
7
8
9
10
11
@SpringBootTest
@RunWith(SpringRunner.class)
public class ProducerTest {
@Autowired
private RabbitTemplate rabbitTemplate;

@Test
public void testSend() {
rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME, "boot.hello", "明天是端午节");
}
}

运行 testSend 测试,查看消息

二、搭建消费者工程

创建SpringBoot 项目consumber-springboot

1、添加依赖

1
2
3
4
5
<!--RabbitMQ 启动依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

2、配置文件

配置application.yml配置文件

1
2
3
4
5
6
7
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
virtual-host: /

3、消息监听器

队列监听器

创建 RabbimtMQListener.java

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.atguigu.listener;

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) {
System.out.println(new String(message.getBody()));
}
}

4、接收消息

运行 ConsumberSpringbootApplication 主程序