基本消息队列
1. 什么是基本消息队列
Section titled “1. 什么是基本消息队列”消息队列(Message Queue) 是一种应用间异步通信的机制。生产者将消息发送到队列中,消费者从队列中取出消息进行处理,两者之间解耦,无需直接交互。
RabbitMQ 中最简单的模型就是基本消息队列,由三个角色组成:
| 角色 | 说明 |
|---|---|
| 生产者(Producer) | 负责创建并发送消息到队列 |
| 消息队列(Queue) | 存储消息的缓冲区,消息按顺序排列等待消费 |
| 消费者(Consumer) | 从队列中取出消息并处理 |
生产者 ──发送消息──▶ [消息队列] ──消费消息──▶ 消费者2. 使用 SpringAMQP 实现
Section titled “2. 使用 SpringAMQP 实现”SpringAMQP 是 Spring 对 AMQP 协议的封装,提供了 RabbitTemplate 模板类(类似 JdbcTemplate),简化了 RabbitMQ 的客户端操作,无需每次手动创建连接。
2.1. 添加依赖
Section titled “2.1. 添加依赖”<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> <version>${spring-boot-starter-amqp}</version></dependency>2.2. RabbitMQ 配置
Section titled “2.2. RabbitMQ 配置”在 application.yml 中配置 RabbitMQ 连接信息:
spring: rabbitmq: host: 127.0.0.1 # RabbitMQ 服务器地址 port: 5672 # RabbitMQ 服务器端口(默认 5672) virtual-host: / # 虚拟主机,默认为 / username: admin # 用户名 password: 123456 # 密码2.3. 发送消息(生产者)
Section titled “2.3. 发送消息(生产者)”@RunWith(SpringRunner.class)@SpringBootTestpublic class PublisherTest {
@Autowired private RabbitTemplate rabbitTemplate;
@Autowired private RabbitAdmin rabbitAdmin; // 管理组件,用于声明队列/交换机等
@Test public void sendMessage() { String queueName = "basic.queue"; String message = "Hello, RabbitMQ!";
// 声明队列:不存在则自动创建,true 表示持久化 Queue queue = new Queue(queueName, true); rabbitAdmin.declareQueue(queue);
// 发送消息到指定队列 rabbitTemplate.convertAndSend(queueName, message); }}关键 API 说明:
RabbitAdmin#declareQueue(Queue):声明队列,队列不存在时自动创建。第二个参数true表示队列持久化(服务重启后不丢失)。RabbitTemplate#convertAndSend(routingKey, message):发送消息,底层自动完成序列化。
2.4. 接收消息(消费者)
Section titled “2.4. 接收消息(消费者)”@Componentpublic class ConsumerListener {
@RabbitListener(queues = "basic.queue") public void onMessage(String message) { System.out.println("Received message: " + message); }}关键注解说明:
@RabbitListener(queues = "..."):监听指定队列,有消息时自动回调该方法。方法参数类型需与消息类型匹配,SpringAMQP 会自动完成反序列化。