md_files/自学/消息队列MQ.md

64 lines
1.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 消息队列MQ
## 初识MQ
### **同步调用**
<img src="https://pic.bitday.top/i/2025/05/27/so4pss-0.png" alt="image-20250527173401081" style="zoom: 67%;" />
同步调用有3个问题
- **拓展性差**,每次有新的需求,现有支付逻辑都要跟着变化,代码经常变动
- **性能下降**,每次远程调用,调用者都是阻塞等待状态。最终整个业务的响应时长就是每次远程调用的执行时长之和
- **级联失败**,当交易服务、通知服务出现故障时,整个事务都会回滚,交易失败。
### 异步调用
![image-20250527175753038](https://pic.bitday.top/i/2025/05/27/t2dfdb-0.png)
### 技术选型
![image-20250527190824767](https://pic.bitday.top/i/2025/05/27/vk3zfw-0.png)
## RabbitMQ
### 部署
```yml
mq:
image: rabbitmq:3.8-management
container_name: mq
restart: unless-stopped
hostname: mq
environment:
RABBITMQ_DEFAULT_USER: admin
RABBITMQ_DEFAULT_PASS: "admin"
RABBITMQ_PLUGINS_DIR: "/plugins:/custom-plugins"
ports:
- "15672:15672"
- "5672:5672"
volumes:
- ./mq-plugins:/custom-plugins
networks:
- hmall-net
```
http://localhost:15672/ 访问控制台
### 架构图
![image-20250527200935901](https://pic.bitday.top/i/2025/05/27/x8b2ej-0.png)
- **`publisher`**:生产者,发送消息的一方
- **`consumer`**:消费者,消费消息的一方
- **`queue`**:队列,存储消息。生产者投递的消息会暂存在消息队列中,等待消费者处理
- **`exchange`**:交换机,负责消息路由。生产者发送的消息由交换机决定投递到哪个队列。**不存储**
- **`virtual host`**虚拟主机起到数据隔离的作用。每个虚拟主机相互独立有各自的exchange、queue