消息中心集成spug短信发送功能
This commit is contained in:
@@ -0,0 +1,631 @@
|
||||
# MessageHub 消息中心系统文档
|
||||
|
||||
## 目录
|
||||
- [系统概述](#系统概述)
|
||||
- [架构设计](#架构设计)
|
||||
- [核心功能](#核心功能)
|
||||
- [技术栈](#技术栈)
|
||||
- [配置说明](#配置说明)
|
||||
- [使用方法](#使用方法)
|
||||
- [API 示例](#api-示例)
|
||||
- [最佳实践](#最佳实践)
|
||||
- [故障排查](#故障排查)
|
||||
|
||||
---
|
||||
|
||||
## 系统概述
|
||||
|
||||
MessageHub 是一个基于 Spring Boot 的消息中心微服务,提供统一的消息发送和管理能力。系统采用消息队列(RabbitMQ)实现异步消息处理,支持多种消息发送渠道,包括邮件、短信、微信和 Telegram。
|
||||
|
||||
### 主要特性
|
||||
|
||||
- **多渠道支持**:支持邮件(Gmail、QQMail)、短信(Spug)、微信、Telegram
|
||||
- **异步处理**:基于 RabbitMQ 消息队列,实现高并发、高可用
|
||||
- **模板管理**:支持消息模板配置,便于统一管理消息内容
|
||||
- **日志记录**:完整的消息发送日志,便于追踪和审计
|
||||
- **健康检查**:自动监控消息发送服务连接状态
|
||||
- **配置中心**:集成 Nacos,实现配置的集中管理
|
||||
|
||||
---
|
||||
|
||||
## 架构设计
|
||||
|
||||
### 系统架构图
|
||||
|
||||
```
|
||||
┌─────────────┐
|
||||
│ 业务服务 │
|
||||
│ (Producer) │
|
||||
└──────┬──────┘
|
||||
│
|
||||
│ MessageDTO
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ MessageHub 微服务 │
|
||||
├─────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌──────────────┐ ┌──────────────────┐ │
|
||||
│ │MessageProducer│ │ RabbitMQ │ │
|
||||
│ │ Service │────────▶│ 消息队列 │ │
|
||||
│ └──────────────┘ └────────┬─────────┘ │
|
||||
│ │ │
|
||||
│ │ │
|
||||
│ ┌──────────────┐ │ │
|
||||
│ │ Queue │◀────────────────┘ │
|
||||
│ │ Listeners │ │
|
||||
│ └──────┬───────┘ │
|
||||
│ │ │
|
||||
│ ├──────────────────────────────────────────────────────┤
|
||||
│ │ │
|
||||
│ ┌──────▼──────┐ ┌──────────────┐ ┌─────────────┐ │
|
||||
│ │ Email │ │ SMS │ │ WeChat │ │
|
||||
│ │ Sender │ │ Sender │ │ Sender │ │
|
||||
│ └─────────────┘ └─────────────┘ └─────────────┘ │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ ┌──────────────┐ │
|
||||
│ │ Database │ │
|
||||
│ │ (MySQL) │ │
|
||||
│ └──────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 核心组件
|
||||
|
||||
#### 1. MessageProducerService
|
||||
消息生产者服务,负责接收业务系统的消息请求,将消息发送到 RabbitMQ 队列。
|
||||
|
||||
**主要方法**:
|
||||
- `sendMessage(MessageDTO message)` - 发送消息到队列
|
||||
- `sendEmail(String to, String subject, String content)` - 发送邮件消息
|
||||
- `sendSms(String phone, String content)` - 发送短信消息
|
||||
|
||||
#### 2. Queue Listeners
|
||||
消息队列监听器,负责从 RabbitMQ 队列中消费消息并调用相应的发送服务。
|
||||
|
||||
**监听器列表**:
|
||||
- `SmsQueueListener` - 监听短信队列
|
||||
- `EmailQueueListener` - 监听邮件队列
|
||||
|
||||
#### 3. Message Senders
|
||||
消息发送器实现,负责实际的消息发送操作。
|
||||
|
||||
**发送器列表**:
|
||||
- `GmailSender` - Gmail 邮件发送器
|
||||
- `QQMailSender` - QQ 邮件发送器
|
||||
- `SpugSmsSender` - Spug 短信发送器
|
||||
- `WeChatSendService` - 微信发送服务
|
||||
- `TgSendService` - Telegram 发送服务
|
||||
|
||||
#### 4. MessageHandleService
|
||||
消息处理服务,负责消息的持久化和日志记录。
|
||||
|
||||
#### 5. ConnectionHealthChecker
|
||||
连接健康检查器,定期检查消息发送服务的连接状态。
|
||||
|
||||
---
|
||||
|
||||
## 核心功能
|
||||
|
||||
### 1. 消息发送
|
||||
|
||||
支持多种消息类型的发送:
|
||||
|
||||
#### 邮件发送
|
||||
```java
|
||||
@Autowired
|
||||
private MessageProducerService messageProducerService;
|
||||
|
||||
messageProducerService.sendEmail("recipient@example.com", "邮件主题", "邮件内容");
|
||||
```
|
||||
|
||||
#### 短信发送
|
||||
```java
|
||||
messageProducerService.sendSms("13800138000", "验证码:123456");
|
||||
```
|
||||
|
||||
#### 微信消息发送
|
||||
```java
|
||||
@Autowired
|
||||
private WeChatSendService weChatSendService;
|
||||
|
||||
weChatSendService.sendMessage(openId, message);
|
||||
```
|
||||
|
||||
#### Telegram 消息发送
|
||||
```java
|
||||
@Autowired
|
||||
private TgSendService tgSendService;
|
||||
|
||||
tgSendService.sendMessage(chatId, message);
|
||||
```
|
||||
|
||||
### 2. 消息模板
|
||||
|
||||
系统支持消息模板功能,可以预定义消息模板,使用时只需传入参数。
|
||||
|
||||
**模板数据结构**:
|
||||
```java
|
||||
public class PushTemplateDO {
|
||||
private Long id;
|
||||
private String templateCode;
|
||||
private String templateName;
|
||||
private String templateContent;
|
||||
private String templateType;
|
||||
private Integer status;
|
||||
}
|
||||
```
|
||||
|
||||
**使用模板发送消息**:
|
||||
```java
|
||||
@Autowired
|
||||
private MessageHandleService messageHandleService;
|
||||
|
||||
String content = messageHandleService.renderTemplate("VERIFY_CODE", Map.of("code", "123456"));
|
||||
messageProducerService.sendSms("13800138000", content);
|
||||
```
|
||||
|
||||
### 3. 消息日志
|
||||
|
||||
所有消息发送都会记录到数据库,便于追踪和审计。
|
||||
|
||||
**日志数据结构**:
|
||||
```java
|
||||
public class PushLogDO {
|
||||
private Long id;
|
||||
private String messageContent;
|
||||
private String receiver;
|
||||
private String messageType;
|
||||
private String platform;
|
||||
private Integer status;
|
||||
private String errorMessage;
|
||||
private LocalDateTime createTime;
|
||||
}
|
||||
```
|
||||
|
||||
### 4. 健康检查
|
||||
|
||||
系统会定期检查消息发送服务的连接状态,确保服务可用性。
|
||||
|
||||
---
|
||||
|
||||
## 技术栈
|
||||
|
||||
### 后端框架
|
||||
- **Spring Boot** 2.7.18 - 应用框架
|
||||
- **Spring Cloud** 2021.0.8 - 微服务框架
|
||||
- **Spring Cloud Alibaba** 2021.0.5.0 - 阿里云组件
|
||||
|
||||
### 服务治理
|
||||
- **Nacos** - 服务发现和配置中心
|
||||
- **RabbitMQ** - 消息队列
|
||||
|
||||
### 数据库
|
||||
- **MySQL** - 关系型数据库
|
||||
- **MyBatis-Plus** 3.5.3.1 - ORM 框架
|
||||
- **Druid** 1.2.23 - 数据库连接池
|
||||
|
||||
### 消息发送
|
||||
- **JavaMail** - 邮件发送
|
||||
- **RestTemplate** - HTTP 客户端(用于短信发送)
|
||||
|
||||
### 其他
|
||||
- **Lombok** - 简化 Java 代码
|
||||
- **Log4j2** - 日志框架
|
||||
- **Validation** - 参数校验
|
||||
|
||||
---
|
||||
|
||||
## 配置说明
|
||||
|
||||
### application.yml 配置
|
||||
|
||||
```yaml
|
||||
spring:
|
||||
application:
|
||||
name: messagehub
|
||||
cloud:
|
||||
nacos:
|
||||
discovery:
|
||||
server-addr: localhost:8848
|
||||
config:
|
||||
server-addr: localhost:8848
|
||||
file-extension: yml
|
||||
rabbitmq:
|
||||
host: localhost
|
||||
port: 5672
|
||||
username: guest
|
||||
password: guest
|
||||
datasource:
|
||||
type: com.alibaba.druid.pool.DruidDataSource
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
url: jdbc:mysql://localhost:3306/messagehub?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
|
||||
username: root
|
||||
password: password
|
||||
|
||||
mybatis-plus:
|
||||
configuration:
|
||||
map-underscore-to-camel-case: true
|
||||
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
|
||||
global-config:
|
||||
db-config:
|
||||
logic-delete-field: deleted
|
||||
logic-delete-value: 1
|
||||
logic-not-delete-value: 0
|
||||
|
||||
logging:
|
||||
level:
|
||||
com.xiaowang.messagehub: INFO
|
||||
org.springframework.amqp: INFO
|
||||
```
|
||||
|
||||
### 邮件配置(Nacos)
|
||||
|
||||
```yaml
|
||||
email:
|
||||
gmail:
|
||||
host: smtp.gmail.com
|
||||
port: 587
|
||||
username: your-email@gmail.com
|
||||
password: your-app-password
|
||||
from: your-email@gmail.com
|
||||
auth: true
|
||||
starttls: true
|
||||
ssl: false
|
||||
qqmail:
|
||||
host: smtp.qq.com
|
||||
port: 587
|
||||
username: your-email@qq.com
|
||||
password: your-authorization-code
|
||||
from: your-email@qq.com
|
||||
auth: true
|
||||
starttls: true
|
||||
ssl: false
|
||||
```
|
||||
|
||||
### 短信配置(Nacos)
|
||||
|
||||
```yaml
|
||||
sms:
|
||||
spug:
|
||||
base-url: https://sms.spug.com
|
||||
template-id: your-template-id
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 使用方法
|
||||
|
||||
### 1. 添加依赖
|
||||
|
||||
在其他微服务的 `pom.xml` 中添加 MessageHub 的依赖:
|
||||
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>com.xiaowang</groupId>
|
||||
<artifactId>messagehub-api</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
### 2. 配置 Nacos
|
||||
|
||||
确保 Nacos 配置中心包含邮件和短信的配置信息。
|
||||
|
||||
### 3. 注入服务
|
||||
|
||||
在需要发送消息的类中注入 `MessageProducerService`:
|
||||
|
||||
```java
|
||||
@Service
|
||||
public class OrderService {
|
||||
|
||||
@Autowired
|
||||
private MessageProducerService messageProducerService;
|
||||
|
||||
public void createOrder(Order order) {
|
||||
// 创建订单逻辑
|
||||
|
||||
// 发送订单确认邮件
|
||||
messageProducerService.sendEmail(
|
||||
order.getUserEmail(),
|
||||
"订单创建成功",
|
||||
"您的订单 " + order.getOrderNo() + " 已创建成功"
|
||||
);
|
||||
|
||||
// 发送订单确认短信
|
||||
messageProducerService.sendSms(
|
||||
order.getUserPhone(),
|
||||
"您的订单 " + order.getOrderNo() + " 已创建成功"
|
||||
);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 4. 使用 Feign 客户端
|
||||
|
||||
如果使用 Feign 进行服务调用,可以定义 Feign 客户端:
|
||||
|
||||
```java
|
||||
@FeignClient(name = "messagehub")
|
||||
public interface MessageHubClient {
|
||||
|
||||
@PostMapping("/message/send")
|
||||
Result<Void> sendMessage(@RequestBody MessageDTO message);
|
||||
|
||||
@PostMapping("/email/send")
|
||||
Result<Void> sendEmail(@RequestParam String to,
|
||||
@RequestParam String subject,
|
||||
@RequestParam String content);
|
||||
|
||||
@PostMapping("/sms/send")
|
||||
Result<Void> sendSms(@RequestParam String phone,
|
||||
@RequestParam String content);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## API 示例
|
||||
|
||||
### 发送简单邮件
|
||||
|
||||
```java
|
||||
MessageDTO message = new MessageDTO();
|
||||
message.setMessageType("EMAIL");
|
||||
message.setReceiver("user@example.com");
|
||||
message.setMessageContent("这是一封测试邮件");
|
||||
message.setPlatform("Gmail");
|
||||
|
||||
messageProducerService.sendMessage(message);
|
||||
```
|
||||
|
||||
### 发送带模板的短信
|
||||
|
||||
```java
|
||||
// 1. 定义模板参数
|
||||
Map<String, Object> params = new HashMap<>();
|
||||
params.put("code", "123456");
|
||||
params.put("time", "5分钟");
|
||||
|
||||
// 2. 渲染模板
|
||||
String content = messageHandleService.renderTemplate("VERIFY_CODE", params);
|
||||
|
||||
// 3. 发送短信
|
||||
messageProducerService.sendSms("13800138000", content);
|
||||
```
|
||||
|
||||
### 批量发送消息
|
||||
|
||||
```java
|
||||
List<String> recipients = Arrays.asList(
|
||||
"user1@example.com",
|
||||
"user2@example.com",
|
||||
"user3@example.com"
|
||||
);
|
||||
|
||||
for (String recipient : recipients) {
|
||||
messageProducerService.sendEmail(
|
||||
recipient,
|
||||
"系统通知",
|
||||
"系统将于今晚进行维护,请提前做好准备"
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 发送微信消息
|
||||
|
||||
```java
|
||||
@Autowired
|
||||
private WeChatSendService weChatSendService;
|
||||
|
||||
WeChatMessage message = new WeChatMessage();
|
||||
message.setOpenId("user-openid");
|
||||
message.setMessageType("text");
|
||||
message.setContent("您好,您的订单已发货");
|
||||
|
||||
weChatSendService.sendMessage(message);
|
||||
```
|
||||
|
||||
### 发送 Telegram 消息
|
||||
|
||||
```java
|
||||
@Autowired
|
||||
private TgSendService tgSendService;
|
||||
|
||||
TgMessage message = new TgMessage();
|
||||
message.setChatId("user-chat-id");
|
||||
message.setContent("系统通知:新功能已上线");
|
||||
|
||||
tgSendService.sendMessage(message);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 最佳实践
|
||||
|
||||
### 1. 使用消息队列
|
||||
|
||||
始终通过 `MessageProducerService` 发送消息,而不是直接调用发送器。这样可以:
|
||||
- 实现异步处理,提高系统响应速度
|
||||
- 解耦业务逻辑和消息发送逻辑
|
||||
- 便于扩展和监控
|
||||
|
||||
### 2. 错误处理
|
||||
|
||||
消息发送可能会失败,建议添加适当的错误处理:
|
||||
|
||||
```java
|
||||
try {
|
||||
messageProducerService.sendEmail(
|
||||
user.getEmail(),
|
||||
"订单确认",
|
||||
"您的订单已确认"
|
||||
);
|
||||
} catch (Exception e) {
|
||||
log.error("发送邮件失败,用户:{}", user.getEmail(), e);
|
||||
// 可以添加重试逻辑或记录到数据库
|
||||
}
|
||||
```
|
||||
|
||||
### 3. 使用消息模板
|
||||
|
||||
对于重复使用的消息内容,建议使用消息模板:
|
||||
- 便于统一管理消息内容
|
||||
- 支持多语言
|
||||
- 便于修改和维护
|
||||
|
||||
### 4. 日志记录
|
||||
|
||||
系统会自动记录所有消息发送日志,建议:
|
||||
- 定期清理过期日志
|
||||
- 对失败的消息进行重试
|
||||
- 监控消息发送成功率
|
||||
|
||||
### 5. 配置管理
|
||||
|
||||
建议使用 Nacos 配置中心管理邮件和短信的配置:
|
||||
- 避免硬编码敏感信息
|
||||
- 便于动态更新配置
|
||||
- 支持多环境配置
|
||||
|
||||
### 6. 健康检查
|
||||
|
||||
定期检查 `ConnectionHealthChecker` 的日志,确保消息发送服务连接正常。
|
||||
|
||||
---
|
||||
|
||||
## 故障排查
|
||||
|
||||
### 常见问题
|
||||
|
||||
#### 1. 消息发送失败
|
||||
|
||||
**症状**:消息发送失败,日志显示错误信息。
|
||||
|
||||
**可能原因**:
|
||||
- 邮件/短信服务配置错误
|
||||
- 网络连接问题
|
||||
- 账号密码错误
|
||||
|
||||
**解决方案**:
|
||||
1. 检查 Nacos 配置是否正确
|
||||
2. 检查网络连接是否正常
|
||||
3. 验证邮件/短信账号密码是否正确
|
||||
4. 查看日志中的详细错误信息
|
||||
|
||||
#### 2. 消息队列连接失败
|
||||
|
||||
**症状**:无法连接到 RabbitMQ。
|
||||
|
||||
**可能原因**:
|
||||
- RabbitMQ 服务未启动
|
||||
- 连接配置错误
|
||||
- 网络问题
|
||||
|
||||
**解决方案**:
|
||||
1. 检查 RabbitMQ 服务是否启动
|
||||
2. 检查 `application.yml` 中的 RabbitMQ 配置
|
||||
3. 检查网络连接和防火墙设置
|
||||
|
||||
#### 3. 数据库连接失败
|
||||
|
||||
**症状**:无法连接到 MySQL 数据库。
|
||||
|
||||
**可能原因**:
|
||||
- 数据库服务未启动
|
||||
- 数据库配置错误
|
||||
- 数据库不存在
|
||||
|
||||
**解决方案**:
|
||||
1. 检查 MySQL 服务是否启动
|
||||
2. 检查数据库连接配置
|
||||
3. 确保数据库 `messagehub` 已创建
|
||||
|
||||
#### 4. 消息发送延迟
|
||||
|
||||
**症状**:消息发送需要很长时间。
|
||||
|
||||
**可能原因**:
|
||||
- 消息队列堆积
|
||||
- 发送服务性能问题
|
||||
- 网络延迟
|
||||
|
||||
**解决方案**:
|
||||
1. 检查 RabbitMQ 队列状态
|
||||
2. 增加消息监听器数量
|
||||
3. 优化发送服务性能
|
||||
|
||||
### 日志分析
|
||||
|
||||
#### 关键日志位置
|
||||
|
||||
- **消息发送日志**:`com.xiaowang.messagehub.service.impl`
|
||||
- **队列监听日志**:`com.xiaowang.messagehub.listener`
|
||||
- **健康检查日志**:`com.xiaowang.messagehub.health`
|
||||
|
||||
#### 日志级别
|
||||
|
||||
建议在生产环境中设置日志级别为 `INFO` 或 `WARN`,在开发环境中设置为 `DEBUG`。
|
||||
|
||||
---
|
||||
|
||||
## 附录
|
||||
|
||||
### 数据库表结构
|
||||
|
||||
#### message 表
|
||||
```sql
|
||||
CREATE TABLE `message` (
|
||||
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||
`message_content` text COMMENT '消息内容',
|
||||
`receiver` varchar(255) COMMENT '接收者',
|
||||
`message_type` varchar(50) COMMENT '消息类型',
|
||||
`platform` varchar(50) COMMENT '发送平台',
|
||||
`status` int DEFAULT 0 COMMENT '状态:0-待发送,1-发送中,2-发送成功,3-发送失败',
|
||||
`error_message` text COMMENT '错误信息',
|
||||
`create_time` datetime COMMENT '创建时间',
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='消息表';
|
||||
```
|
||||
|
||||
#### push_template 表
|
||||
```sql
|
||||
CREATE TABLE `push_template` (
|
||||
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||
`template_code` varchar(100) COMMENT '模板编码',
|
||||
`template_name` varchar(255) COMMENT '模板名称',
|
||||
`template_content` text COMMENT '模板内容',
|
||||
`template_type` varchar(50) COMMENT '模板类型',
|
||||
`status` int DEFAULT 1 COMMENT '状态:0-禁用,1-启用',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_template_code` (`template_code`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='消息模板表';
|
||||
```
|
||||
|
||||
#### push_log 表
|
||||
```sql
|
||||
CREATE TABLE `push_log` (
|
||||
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||
`message_content` text COMMENT '消息内容',
|
||||
`receiver` varchar(255) COMMENT '接收者',
|
||||
`message_type` varchar(50) COMMENT '消息类型',
|
||||
`platform` varchar(50) COMMENT '发送平台',
|
||||
`status` int DEFAULT 0 COMMENT '状态:0-待发送,1-发送中,2-发送成功,3-发送失败',
|
||||
`error_message` text COMMENT '错误信息',
|
||||
`create_time` datetime COMMENT '创建时间',
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='消息推送日志表';
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 联系方式
|
||||
|
||||
如有问题或建议,请联系开发团队。
|
||||
|
||||
---
|
||||
|
||||
**文档版本**:v1.0
|
||||
**最后更新**:2026-03-02
|
||||
**维护者**:MessageHub 开发团队
|
||||
@@ -16,7 +16,6 @@ public class SmsConfig {
|
||||
@Data
|
||||
public static class SpugConfig {
|
||||
private String baseUrl = "https://push.spug.cc";
|
||||
private String templateId;
|
||||
private String apiKey;
|
||||
}
|
||||
}
|
||||
@@ -17,9 +17,8 @@ import java.util.Map;
|
||||
@Data
|
||||
public class MessageDTO {
|
||||
|
||||
// 接收者邮箱地址,必须符合邮箱格式且不能为空
|
||||
// 接收者,不能为空
|
||||
@NotBlank(message = "接收者不能为空")
|
||||
@Email(message = "接收者必须是有效的邮箱地址")
|
||||
private String receiver;
|
||||
|
||||
// 渠道类型,只能是EMAIL、SMS、PUSH或WECHAT中的一种且不能为空
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.xiaowang.messagehub.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.Pattern;
|
||||
import javax.validation.constraints.Size;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 短信消息DTO
|
||||
* 用于封装短信发送所需的所有信息
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-03-02
|
||||
*/
|
||||
@Data
|
||||
public class SmsMessageDTO extends MessageDTO{
|
||||
// 发送方式,用于指定短信发送渠道
|
||||
@NotBlank(message = "发送方式不能为空")
|
||||
@Pattern(regexp = "^(SPUG|OTHER)$", message = "发送方式必须是SPUG或OTHER")
|
||||
private String sendMethod;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.xiaowang.messagehub.enums;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum MessageExceptionEnum {
|
||||
|
||||
TEMPLATE_NOT_FOUND(1001, "短信模板不存在"),
|
||||
SMS_SEND_FAILED(1002, "短信发送失败"),
|
||||
INVALID_PARAM(1003, "参数无效"),
|
||||
API_CALL_FAILED(1004, "API调用失败"),
|
||||
JSON_PARSE_ERROR(1005, "JSON解析错误"),
|
||||
NETWORK_ERROR(1006, "网络错误"),
|
||||
CONFIG_ERROR(1007, "配置错误");
|
||||
|
||||
private final int code;
|
||||
private final String message;
|
||||
|
||||
public static MessageExceptionEnum getByCode(int code) {
|
||||
for (MessageExceptionEnum exception : values()) {
|
||||
if (exception.getCode() == code) {
|
||||
return exception;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("未知的异常编码: " + code);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.xiaowang.messagehub.exception;
|
||||
|
||||
import com.xiaowang.messagehub.enums.MessageExceptionEnum;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
public class SmsException extends RuntimeException {
|
||||
|
||||
private final Integer code;
|
||||
private final String message;
|
||||
|
||||
public SmsException(MessageExceptionEnum exceptionEnum) {
|
||||
super(exceptionEnum.getMessage());
|
||||
this.code = exceptionEnum.getCode();
|
||||
this.message = exceptionEnum.getMessage();
|
||||
}
|
||||
|
||||
public SmsException(MessageExceptionEnum exceptionEnum, String detailMessage) {
|
||||
super(detailMessage);
|
||||
this.code = exceptionEnum.getCode();
|
||||
this.message = detailMessage;
|
||||
}
|
||||
|
||||
public SmsException(Integer code, String message) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,9 @@ package com.xiaowang.messagehub.listener;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.messagehub.dto.MessageDTO;
|
||||
import com.xiaowang.messagehub.service.EmailSendService;
|
||||
import com.xiaowang.messagehub.service.MessageHandleService;
|
||||
import com.xiaowang.messagehub.service.impl.MessageHandleService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.core.Message;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
|
||||
@@ -2,10 +2,9 @@ package com.xiaowang.messagehub.listener;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.rabbitmq.client.Channel;
|
||||
import com.xiaowang.messagehub.dto.MessageDTO;
|
||||
import com.xiaowang.messagehub.entity.PushTemplateDO;
|
||||
import com.xiaowang.messagehub.dto.SmsMessageDTO;
|
||||
import com.xiaowang.messagehub.entity.PushLogDO;
|
||||
import com.xiaowang.messagehub.mapper.PushLogMapper;
|
||||
import com.xiaowang.messagehub.service.MessageHandleService;
|
||||
import com.xiaowang.messagehub.service.SmsSendService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -13,12 +12,12 @@ import org.springframework.amqp.core.Message;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 短信队列监听器
|
||||
* 用于监听和处理短信队列中的消息,实现短信发送功能
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
@@ -29,87 +28,65 @@ public class SmsQueueListener {
|
||||
private static final Logger logger = LoggerFactory.getLogger(SmsQueueListener.class);
|
||||
|
||||
@Autowired
|
||||
private ObjectMapper objectMapper;
|
||||
private ObjectMapper objectMapper; // JSON对象映射器,用于处理消息序列化和反序列化
|
||||
|
||||
@Autowired
|
||||
private MessageHandleService messageHandleService;
|
||||
private SmsSendService smsSendService; // 短信服务,用于发送短信
|
||||
|
||||
@Autowired
|
||||
private PushLogMapper pushLogMapper;
|
||||
private PushLogMapper pushLogMapper; // 推送日志映射器,用于数据库操作
|
||||
|
||||
@Autowired
|
||||
private SmsSendService smsSendService;
|
||||
|
||||
@RabbitListener(queues = "smsQueue")
|
||||
/**
|
||||
* 处理短信消息的方法
|
||||
* @param message 接收到的消息对象
|
||||
* @param channel RabbitMQ通道,用于消息确认
|
||||
*/
|
||||
@RabbitListener(queues = "smsQueue") // 监听名为smsQueue的队列
|
||||
public void handleSmsMessage(Message message, Channel channel) {
|
||||
String messageId = message.getMessageProperties().getMessageId();
|
||||
LocalDateTime sendTime = LocalDateTime.now();
|
||||
String messageId = message.getMessageProperties().getMessageId(); // 获取消息ID
|
||||
LocalDateTime sendTime = LocalDateTime.now(); // 获取当前接收时间
|
||||
|
||||
try {
|
||||
// 将消息体转换为字符串
|
||||
String messageBody = new String(message.getBody(), "UTF-8");
|
||||
// 打印消息接收日志
|
||||
logger.info("========================================");
|
||||
logger.info("收到短信消息");
|
||||
logger.info("消息ID: {}", messageId);
|
||||
logger.info("消息内容: {}", messageBody);
|
||||
logger.info("接收时间: {}", sendTime);
|
||||
logger.info("========================================");
|
||||
|
||||
MessageDTO messageDTO = objectMapper.readValue(messageBody, MessageDTO.class);
|
||||
// 将消息体反序列化为SmsMessageDTO对象
|
||||
SmsMessageDTO smsMessageDTO = objectMapper.readValue(messageBody, SmsMessageDTO.class);
|
||||
|
||||
boolean isValid = messageHandleService.validateAndSaveLog(messageDTO, messageId, sendTime);
|
||||
// 基础格式验证已通过@Valid注解在DTO中完成
|
||||
logger.info("消息格式验证通过");
|
||||
|
||||
if (isValid) {
|
||||
String finalContent = null;
|
||||
String templateCode = messageDTO.getTemplateCode();
|
||||
|
||||
if (StringUtils.hasText(templateCode)) {
|
||||
PushTemplateDO template = messageHandleService.getTemplateByCode(templateCode);
|
||||
|
||||
if (template != null && StringUtils.hasText(template.getContentPattern())) {
|
||||
logger.info("检测到模板消息,模板编码: {}", templateCode);
|
||||
logger.info("模板内容模式: {}", template.getContentPattern());
|
||||
|
||||
String contentPattern = template.getContentPattern();
|
||||
finalContent = messageHandleService.replaceTemplatePlaceholders(contentPattern, messageDTO.getTemplateParams());
|
||||
|
||||
logger.info("模板参数: {}", messageDTO.getTemplateParams());
|
||||
logger.info("替换后最终内容: {}", finalContent);
|
||||
} else {
|
||||
logger.info("非模板消息或模板不存在/未启用,不进行占位符替换");
|
||||
logger.info("模板编码: {}, 模板存在: {}", templateCode, template != null);
|
||||
}
|
||||
} else {
|
||||
logger.info("未指定模板编码,非模板消息,不进行占位符替换");
|
||||
}
|
||||
|
||||
if (finalContent == null) {
|
||||
if (messageDTO.getTemplateParams() != null && messageDTO.getTemplateParams().containsKey("message")) {
|
||||
finalContent = messageDTO.getTemplateParams().get("message").toString();
|
||||
} else {
|
||||
finalContent = "非模板消息,无最终内容";
|
||||
}
|
||||
}
|
||||
|
||||
pushLogMapper.updateFinalContent(messageId, finalContent);
|
||||
|
||||
smsSendService.sendSms(messageDTO.getReceiver(), finalContent);
|
||||
|
||||
logger.info("========================================");
|
||||
logger.info("消息接收处理完成");
|
||||
logger.info("消息ID: {}", messageId);
|
||||
logger.info("手机号: {}", messageDTO.getReceiver());
|
||||
logger.info("最终内容: {}", finalContent);
|
||||
logger.info("========================================");
|
||||
} else {
|
||||
logger.warn("消息校验失败,消息ID: {}", messageId);
|
||||
}
|
||||
// 保存推送日志
|
||||
savePushLog(messageId, smsMessageDTO, sendTime, 0, null);
|
||||
|
||||
// 发送短信
|
||||
smsSendService.sendSms(smsMessageDTO);
|
||||
|
||||
logger.info("========================================");
|
||||
logger.info("消息接收处理完成");
|
||||
logger.info("消息ID: {}", messageId);
|
||||
logger.info("手机号: {}", smsMessageDTO.getReceiver());
|
||||
logger.info("发送方式: {}", smsMessageDTO.getSendMethod());
|
||||
logger.info("========================================");
|
||||
|
||||
// 确认消息已被处理
|
||||
long deliveryTag = message.getMessageProperties().getDeliveryTag();
|
||||
channel.basicAck(deliveryTag, false);
|
||||
} catch (Exception e) {
|
||||
// 异常处理
|
||||
logger.error("处理短信消息时发生异常,消息ID: {}", messageId, e);
|
||||
|
||||
// 更新日志状态为发送失败
|
||||
updatePushLogStatus(messageId, 2, e.getMessage());
|
||||
|
||||
try {
|
||||
// 即使发生异常也确认消息,避免重复处理
|
||||
long deliveryTag = message.getMessageProperties().getDeliveryTag();
|
||||
channel.basicAck(deliveryTag, false);
|
||||
} catch (Exception ackException) {
|
||||
@@ -117,4 +94,45 @@ public class SmsQueueListener {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存推送日志
|
||||
* @param messageId 消息ID
|
||||
* @param smsMessageDTO 短信消息DTO
|
||||
* @param sendTime 发送时间
|
||||
* @param status 状态
|
||||
* @param failReason 失败原因
|
||||
*/
|
||||
private void savePushLog(String messageId, SmsMessageDTO smsMessageDTO, LocalDateTime sendTime, Integer status, String failReason) {
|
||||
PushLogDO pushLog = new PushLogDO();
|
||||
pushLog.setId(messageId);
|
||||
pushLog.setSourceSystem(smsMessageDTO.getSourceSystem());
|
||||
pushLog.setUniqueId(smsMessageDTO.getUniqueId());
|
||||
pushLog.setReceiver(smsMessageDTO.getReceiver());
|
||||
pushLog.setChannelType(smsMessageDTO.getChannelType()); // 使用DTO中的渠道类型
|
||||
pushLog.setMsgType(smsMessageDTO.getMsgType()); // 使用DTO中的消息类型
|
||||
pushLog.setTemplateCode(smsMessageDTO.getTemplateCode());
|
||||
pushLog.setTemplateParams(smsMessageDTO.getTemplateParams() != null ? smsMessageDTO.getTemplateParams().toString() : null);
|
||||
pushLog.setSendTime(sendTime);
|
||||
pushLog.setRetryCount(0);
|
||||
pushLog.setStatus(status);
|
||||
pushLog.setFailReason(failReason);
|
||||
pushLogMapper.insert(pushLog);
|
||||
logger.info("推送日志保存成功,消息ID: {}", messageId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新推送日志状态
|
||||
* @param messageId 消息ID
|
||||
* @param status 状态
|
||||
* @param failReason 失败原因
|
||||
*/
|
||||
private void updatePushLogStatus(String messageId, Integer status, String failReason) {
|
||||
PushLogDO pushLog = new PushLogDO();
|
||||
pushLog.setId(messageId);
|
||||
pushLog.setStatus(status);
|
||||
pushLog.setFailReason(failReason);
|
||||
pushLogMapper.updateById(pushLog);
|
||||
logger.info("推送日志状态更新成功,消息ID: {}, 状态: {}", messageId, status);
|
||||
}
|
||||
}
|
||||
|
||||
+136
-5
@@ -3,6 +3,7 @@ package com.xiaowang.messagehub.service;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.messagehub.config.RabbitMQConfig;
|
||||
import com.xiaowang.messagehub.dto.MessageDTO;
|
||||
import com.xiaowang.messagehub.dto.SmsMessageDTO;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.core.Message;
|
||||
import org.springframework.amqp.core.MessageBuilder;
|
||||
@@ -13,23 +14,36 @@ import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 消息生产者服务类
|
||||
* 使用RabbitMQ发送短信和邮件消息
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class MessageProducerService {
|
||||
|
||||
// RabbitMQ模板,用于发送消息
|
||||
@Autowired
|
||||
private RabbitTemplate rabbitTemplate;
|
||||
|
||||
// 对象映射器,用于将对象转换为JSON字符串
|
||||
@Autowired
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
public void sendSmsMessage(MessageDTO messageDTO) {
|
||||
/**
|
||||
* 发送短信消息
|
||||
* @param messageDTO 消息数据传输对象,包含短信相关信息
|
||||
*/
|
||||
public void sendSmsMessage(SmsMessageDTO messageDTO) {
|
||||
try {
|
||||
// 生成唯一消息ID
|
||||
String messageId = UUID.randomUUID().toString();
|
||||
messageDTO.setUniqueId(messageId);
|
||||
|
||||
// 将消息对象转换为JSON字符串
|
||||
String messageBody = objectMapper.writeValueAsString(messageDTO);
|
||||
|
||||
// 构建RabbitMQ消息对象
|
||||
Message message = MessageBuilder
|
||||
.withBody(messageBody.getBytes())
|
||||
.setContentType(MessageProperties.CONTENT_TYPE_JSON)
|
||||
@@ -37,43 +51,160 @@ public class MessageProducerService {
|
||||
.setTimestamp(new java.util.Date())
|
||||
.build();
|
||||
|
||||
// 发送消息到短信队列
|
||||
rabbitTemplate.send(
|
||||
RabbitMQConfig.MESSAGE_EXCHANGE,
|
||||
"sms." + messageDTO.getMsgType().toLowerCase(),
|
||||
message
|
||||
);
|
||||
|
||||
// 记录消息发送日志
|
||||
log.info("短信消息已发送到队列,消息ID: {}, 手机号: {}, 消息类型: {}", messageId, messageDTO.getReceiver(), messageDTO.getMsgType());
|
||||
} catch (Exception e) {
|
||||
// 记录错误日志并抛出运行时异常
|
||||
log.error("发送短信消息失败", e);
|
||||
throw new RuntimeException("发送短信消息失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送邮件消息
|
||||
* @param messageDTO 消息数据传输对象,包含邮件相关信息
|
||||
*/
|
||||
public void sendEmailMessage(MessageDTO messageDTO) {
|
||||
try {
|
||||
String messageId = UUID.randomUUID().toString();
|
||||
messageDTO.setUniqueId(messageId);
|
||||
|
||||
|
||||
String messageBody = objectMapper.writeValueAsString(messageDTO);
|
||||
|
||||
|
||||
Message message = MessageBuilder
|
||||
.withBody(messageBody.getBytes())
|
||||
.setContentType(MessageProperties.CONTENT_TYPE_JSON)
|
||||
.setMessageId(messageId)
|
||||
.setTimestamp(new java.util.Date())
|
||||
.build();
|
||||
|
||||
|
||||
rabbitTemplate.send(
|
||||
RabbitMQConfig.MESSAGE_EXCHANGE,
|
||||
"email." + messageDTO.getMsgType().toLowerCase(),
|
||||
message
|
||||
);
|
||||
|
||||
|
||||
log.info("邮件消息已发送到队列,消息ID: {}, 收件人: {}, 消息类型: {}", messageId, messageDTO.getReceiver(), messageDTO.getMsgType());
|
||||
} catch (Exception e) {
|
||||
log.error("发送邮件消息失败", e);
|
||||
throw new RuntimeException("发送邮件消息失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送微信消息
|
||||
* @param messageDTO 消息数据传输对象,包含微信相关信息
|
||||
*/
|
||||
public void sendWeChatMessage(MessageDTO messageDTO) {
|
||||
try {
|
||||
String messageId = UUID.randomUUID().toString();
|
||||
messageDTO.setUniqueId(messageId);
|
||||
|
||||
String messageBody = objectMapper.writeValueAsString(messageDTO);
|
||||
|
||||
Message message = MessageBuilder
|
||||
.withBody(messageBody.getBytes())
|
||||
.setContentType(MessageProperties.CONTENT_TYPE_JSON)
|
||||
.setMessageId(messageId)
|
||||
.setTimestamp(new java.util.Date())
|
||||
.build();
|
||||
|
||||
rabbitTemplate.send(
|
||||
RabbitMQConfig.MESSAGE_EXCHANGE,
|
||||
"wechat." + messageDTO.getMsgType().toLowerCase(),
|
||||
message
|
||||
);
|
||||
|
||||
log.info("微信消息已发送到队列,消息ID: {}, 接收者: {}, 消息类型: {}", messageId, messageDTO.getReceiver(), messageDTO.getMsgType());
|
||||
} catch (Exception e) {
|
||||
log.error("发送微信消息失败", e);
|
||||
throw new RuntimeException("发送微信消息失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送推送消息
|
||||
* @param messageDTO 消息数据传输对象,包含推送相关信息
|
||||
*/
|
||||
public void sendPushMessage(MessageDTO messageDTO) {
|
||||
try {
|
||||
String messageId = UUID.randomUUID().toString();
|
||||
messageDTO.setUniqueId(messageId);
|
||||
|
||||
String messageBody = objectMapper.writeValueAsString(messageDTO);
|
||||
|
||||
Message message = MessageBuilder
|
||||
.withBody(messageBody.getBytes())
|
||||
.setContentType(MessageProperties.CONTENT_TYPE_JSON)
|
||||
.setMessageId(messageId)
|
||||
.setTimestamp(new java.util.Date())
|
||||
.build();
|
||||
|
||||
rabbitTemplate.send(
|
||||
RabbitMQConfig.MESSAGE_EXCHANGE,
|
||||
"push." + messageDTO.getMsgType().toLowerCase(),
|
||||
message
|
||||
);
|
||||
|
||||
log.info("推送消息已发送到队列,消息ID: {}, 接收者: {}, 消息类型: {}", messageId, messageDTO.getReceiver(), messageDTO.getMsgType());
|
||||
} catch (Exception e) {
|
||||
log.error("发送推送消息失败", e);
|
||||
throw new RuntimeException("发送推送消息失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通用发送消息方法
|
||||
* 根据渠道类型自动路由到对应的队列
|
||||
* @param messageDTO 消息数据传输对象
|
||||
*/
|
||||
public void sendMessage(MessageDTO messageDTO) {
|
||||
try {
|
||||
String messageId = UUID.randomUUID().toString();
|
||||
messageDTO.setUniqueId(messageId);
|
||||
|
||||
String messageBody = objectMapper.writeValueAsString(messageDTO);
|
||||
|
||||
Message message = MessageBuilder
|
||||
.withBody(messageBody.getBytes())
|
||||
.setContentType(MessageProperties.CONTENT_TYPE_JSON)
|
||||
.setMessageId(messageId)
|
||||
.setTimestamp(new java.util.Date())
|
||||
.build();
|
||||
|
||||
String channelType = messageDTO.getChannelType();
|
||||
String routingKey;
|
||||
|
||||
if ("SMS".equalsIgnoreCase(channelType)) {
|
||||
routingKey = "sms." + messageDTO.getMsgType().toLowerCase();
|
||||
} else if ("EMAIL".equalsIgnoreCase(channelType)) {
|
||||
routingKey = "email." + messageDTO.getMsgType().toLowerCase();
|
||||
} else if ("WECHAT".equalsIgnoreCase(channelType)) {
|
||||
routingKey = "wechat." + messageDTO.getMsgType().toLowerCase();
|
||||
} else if ("PUSH".equalsIgnoreCase(channelType)) {
|
||||
routingKey = "push." + messageDTO.getMsgType().toLowerCase();
|
||||
} else {
|
||||
routingKey = "unknown." + messageDTO.getMsgType().toLowerCase();
|
||||
}
|
||||
|
||||
rabbitTemplate.send(
|
||||
RabbitMQConfig.MESSAGE_EXCHANGE,
|
||||
routingKey,
|
||||
message
|
||||
);
|
||||
|
||||
log.info("消息已发送到队列,消息ID: {}, 渠道类型: {}, 接收者: {}, 消息类型: {}",
|
||||
messageId, channelType, messageDTO.getReceiver(), messageDTO.getMsgType());
|
||||
} catch (Exception e) {
|
||||
log.error("发送消息失败", e);
|
||||
throw new RuntimeException("发送消息失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,102 +1,17 @@
|
||||
package com.xiaowang.messagehub.service;
|
||||
|
||||
import com.xiaowang.messagehub.config.SmsConfig;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class SmsSendService {
|
||||
|
||||
@Autowired
|
||||
private SmsConfig smsConfig;
|
||||
|
||||
@Autowired
|
||||
private List<SmsSender> smsSenders;
|
||||
import com.xiaowang.messagehub.dto.SmsMessageDTO;
|
||||
|
||||
/**
|
||||
* 短信发送服务接口
|
||||
* 该接口定义了短信发送服务所需的基本方法
|
||||
*/
|
||||
public interface SmsSendService {
|
||||
/**
|
||||
* 发送短信的方法
|
||||
* 发送短信
|
||||
*
|
||||
* @param phone 接收短信的手机号码
|
||||
* @param content 短信内容
|
||||
* @param smsMessage 参数
|
||||
* @return 发送结果
|
||||
*/
|
||||
public void sendSms(String phone, String content) {
|
||||
// 从配置中获取短信平台名称
|
||||
String platform = smsConfig.getPlatform();
|
||||
|
||||
// 根据平台名称从短信发送器列表中查找对应的发送器
|
||||
SmsSender sender = smsSenders.stream()
|
||||
// 过滤出与指定平台名称匹配的发送器
|
||||
.filter(s -> s.getPlatformName().equalsIgnoreCase(platform))
|
||||
// 获取第一个匹配的发送器,如果没有则抛出异常
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new RuntimeException("不支持的短信平台: " + platform));
|
||||
|
||||
// 记录发送短信的日志信息
|
||||
log.info("使用{}平台发送短信,手机号: {}, 内容: {}", platform, phone, content);
|
||||
// 调用发送器的发送短信方法
|
||||
sender.sendSms(phone, content);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送短信的方法
|
||||
*
|
||||
* @param phone 接收短信的手机号码
|
||||
* @param content 短信内容
|
||||
* @param platform 短信平台名称
|
||||
* @throws RuntimeException 当指定的短信平台不被支持时抛出
|
||||
*/
|
||||
public void sendSms(String phone, String content, String platform) {
|
||||
// 从短信发送者列表中筛选出指定平台的发送器
|
||||
SmsSender sender = smsSenders.stream()
|
||||
// 过滤出平台名称匹配的发送器
|
||||
.filter(s -> s.getPlatformName().equalsIgnoreCase(platform))
|
||||
// 获取第一个匹配的发送器,如果不存在则抛出异常
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new RuntimeException("不支持的短信平台: " + platform));
|
||||
|
||||
// 记录发送短信的日志信息
|
||||
log.info("使用{}平台发送短信,手机号: {}, 内容: {}", platform, phone, content);
|
||||
// 调用发送器的sendSms方法发送短信
|
||||
sender.sendSms(phone, content);
|
||||
}
|
||||
|
||||
public void sendSmsWithTemplate(String phone, String templateId, String... params) {
|
||||
String platform = smsConfig.getPlatform();
|
||||
|
||||
SmsSender sender = smsSenders.stream()
|
||||
.filter(s -> s.getPlatformName().equalsIgnoreCase(platform))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new RuntimeException("不支持的短信平台: " + platform));
|
||||
|
||||
log.info("使用{}平台发送模板短信,手机号: {}, 模板ID: {}", platform, phone, templateId);
|
||||
sender.sendSms(phone, templateId, params);
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用指定平台发送模板短信
|
||||
*
|
||||
* @param phone 接收短信的手机号码
|
||||
* @param templateId 短信模板ID
|
||||
* @param platform 短信发送平台名称
|
||||
* @param params 短信模板参数,可变长度参数
|
||||
* @throws RuntimeException 当指定的短信平台不被支持时抛出
|
||||
*/
|
||||
public void sendSmsWithTemplate(String phone, String templateId, String platform, String... params) {
|
||||
// 从短信发送者列表中根据平台名称筛选出对应的发送器
|
||||
SmsSender sender = smsSenders.stream()
|
||||
// 过滤出与指定平台名称匹配的发送器(不区分大小写)
|
||||
.filter(s -> s.getPlatformName().equalsIgnoreCase(platform))
|
||||
// 获取第一个匹配的发送器,如果没有则抛出异常
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new RuntimeException("不支持的短信平台: " + platform));
|
||||
|
||||
// 记录发送短信的日志信息
|
||||
log.info("使用{}平台发送模板短信,手机号: {}, 模板ID: {}", platform, phone, templateId);
|
||||
// 调用发送器的sendSms方法发送短信
|
||||
sender.sendSms(phone, templateId, params);
|
||||
}
|
||||
void sendSms(SmsMessageDTO smsMessage);
|
||||
}
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.xiaowang.messagehub.service;
|
||||
|
||||
public interface SmsSender {
|
||||
|
||||
void sendSms(String phone, String content);
|
||||
|
||||
void sendSms(String phone, String templateId, String... params);
|
||||
|
||||
String getPlatformName();
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
package com.xiaowang.messagehub.service;
|
||||
|
||||
public class TgSendService {
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
package com.xiaowang.messagehub.service;
|
||||
|
||||
public class WeChatSendService {
|
||||
}
|
||||
+63
-14
@@ -1,4 +1,4 @@
|
||||
package com.xiaowang.messagehub.service;
|
||||
package com.xiaowang.messagehub.service.impl;
|
||||
|
||||
import com.xiaowang.messagehub.dto.MessageDTO;
|
||||
import com.xiaowang.messagehub.entity.PushLogDO;
|
||||
@@ -19,7 +19,7 @@ import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 消息队列数据校验服务类
|
||||
* 消息队列数据校验以及数据库操作服务类
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
@@ -27,17 +27,24 @@ import java.util.Set;
|
||||
@Service
|
||||
public class MessageHandleService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessageHandleService.class);
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessageHandleService.class); // 日志记录器
|
||||
|
||||
@Autowired
|
||||
private Validator validator;
|
||||
private Validator validator; // 数据校验器
|
||||
|
||||
@Autowired
|
||||
private PushLogMapper pushLogMapper;
|
||||
private PushLogMapper pushLogMapper; // 推送日志数据访问层
|
||||
|
||||
@Autowired
|
||||
private PushTemplateMapper pushTemplateMapper;
|
||||
private PushTemplateMapper pushTemplateMapper; // 推送模板数据访问层
|
||||
|
||||
/**
|
||||
* 验证消息数据并保存日志
|
||||
* @param messageDTO 消息数据传输对象
|
||||
* @param messageId 消息ID
|
||||
* @param sendTime 发送时间
|
||||
* @return 验证是否通过
|
||||
*/
|
||||
public boolean validateAndSaveLog(MessageDTO messageDTO, String messageId, LocalDateTime sendTime) {
|
||||
Set<ConstraintViolation<MessageDTO>> violations = validator.validate(messageDTO);
|
||||
|
||||
@@ -53,6 +60,11 @@ public class MessageHandleService {
|
||||
pushLog.setSendTime(sendTime);
|
||||
pushLog.setRetryCount(0);
|
||||
|
||||
String channelType = messageDTO.getChannelType();
|
||||
String receiver = messageDTO.getReceiver();
|
||||
|
||||
logger.info("开始校验消息ID: {}, 接收者: {}, 渠道类型: {}", messageId, receiver, channelType);
|
||||
|
||||
if (violations.isEmpty()) {
|
||||
pushLog.setStatus(0);
|
||||
pushLog.setFailReason(null);
|
||||
@@ -65,6 +77,23 @@ public class MessageHandleService {
|
||||
errorBuilder.append(violation.getMessage()).append("; ");
|
||||
}
|
||||
String failReason = errorBuilder.toString();
|
||||
|
||||
if ("SMS".equalsIgnoreCase(channelType)) {
|
||||
if (receiver == null || !receiver.matches("^1[3-9]\\d{9}$")) {
|
||||
failReason = "手机号格式不正确";
|
||||
} else {
|
||||
failReason = "参数校验失败";
|
||||
}
|
||||
} else if ("EMAIL".equalsIgnoreCase(channelType)) {
|
||||
if (receiver == null || !receiver.matches("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$")) {
|
||||
failReason = "邮箱格式不正确";
|
||||
} else {
|
||||
failReason = "参数校验失败";
|
||||
}
|
||||
} else {
|
||||
failReason = "参数校验失败";
|
||||
}
|
||||
|
||||
pushLog.setStatus(2);
|
||||
pushLog.setFailReason(failReason);
|
||||
pushLogMapper.insert(pushLog);
|
||||
@@ -73,37 +102,57 @@ public class MessageHandleService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据模板代码获取推送模板
|
||||
* @param templateCode 模板代码
|
||||
* @return 推送模板对象
|
||||
*/
|
||||
public PushTemplateDO getTemplateByCode(String templateCode) {
|
||||
LambdaQueryWrapper<PushTemplateDO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(PushTemplateDO::getTemplateCode, templateCode)
|
||||
.eq(PushTemplateDO::getIsEnable, 1);
|
||||
return pushTemplateMapper.selectOne(wrapper);
|
||||
wrapper.eq(PushTemplateDO::getTemplateCode, templateCode) // 匹配模板代码
|
||||
.eq(PushTemplateDO::getIsEnable, 1); // 只查询启用的模板
|
||||
return pushTemplateMapper.selectOne(wrapper); // 查询并返回模板
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新推送日志状态
|
||||
* @param messageId 消息ID
|
||||
* @param status 状态码
|
||||
* @param failReason 失败原因
|
||||
*/
|
||||
public void updatePushLogStatus(String messageId, Integer status, String failReason) {
|
||||
PushLogDO pushLog = new PushLogDO();
|
||||
pushLog.setId(messageId);
|
||||
pushLog.setStatus(status);
|
||||
pushLog.setFailReason(failReason);
|
||||
pushLogMapper.updateById(pushLog);
|
||||
pushLogMapper.updateById(pushLog); // 更新日志状态
|
||||
}
|
||||
|
||||
/**
|
||||
* 替换模板中的占位符
|
||||
* @param contentPattern 模板内容
|
||||
* @param templateParams 模板参数
|
||||
* @return 替换后的内容
|
||||
*/
|
||||
public String replaceTemplatePlaceholders(String contentPattern, Map<String, Object> templateParams) {
|
||||
// 如果模板内容为空,直接返回
|
||||
if (!StringUtils.hasText(contentPattern)) {
|
||||
return contentPattern;
|
||||
}
|
||||
|
||||
// 如果模板参数为空,直接返回模板内容
|
||||
if (templateParams == null || templateParams.isEmpty()) {
|
||||
return contentPattern;
|
||||
}
|
||||
|
||||
String result = contentPattern;
|
||||
// 遍历所有参数,替换模板中的占位符
|
||||
for (Map.Entry<String, Object> entry : templateParams.entrySet()) {
|
||||
String placeholder = "${" + entry.getKey() + "}";
|
||||
String value = entry.getValue() != null ? entry.getValue().toString() : "";
|
||||
result = result.replace(placeholder, value);
|
||||
String placeholder = "${" + entry.getKey() + "}"; // 构建占位符
|
||||
String value = entry.getValue() != null ? entry.getValue().toString() : ""; // 获取参数值
|
||||
result = result.replace(placeholder, value); // 替换占位符
|
||||
}
|
||||
|
||||
return result;
|
||||
return result; // 返回替换后的结果
|
||||
}
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
package com.xiaowang.messagehub.service.impl;
|
||||
|
||||
import com.xiaowang.messagehub.dto.SmsMessageDTO;
|
||||
import com.xiaowang.messagehub.entity.PushTemplateDO;
|
||||
import com.xiaowang.messagehub.service.SmsSendService;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 短信发送服务实现类
|
||||
* 实现了SmsSendService接口,提供短信发送功能
|
||||
*/
|
||||
@Service
|
||||
public class SmsSendServiceImpl implements SmsSendService {
|
||||
|
||||
// 注入短信服务基础URL配置
|
||||
@Value("${sms.spug.base-url}")
|
||||
private String spugBaseUrl;
|
||||
|
||||
@Value("${sms.spug.api-key}")
|
||||
// 注入短信服务API密钥配置
|
||||
private String spugApiKey;
|
||||
|
||||
private final MessageHandleService messageHandleService;
|
||||
// 消息处理服务,用于获取短信模板等信息
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(SmsSendServiceImpl.class);
|
||||
// 日志记录器,用于记录服务运行日志
|
||||
/**
|
||||
* 构造函数,通过依赖注入方式初始化MessageHandleService
|
||||
* @param messageHandleService 消息处理服务
|
||||
*/
|
||||
public SmsSendServiceImpl(MessageHandleService messageHandleService) {
|
||||
this.messageHandleService = messageHandleService;
|
||||
}
|
||||
/**
|
||||
* 发送短信方法实现
|
||||
* @param smsMessage 短信消息DTO,包含模板代码、发送方式和模板参数等信息
|
||||
* @throws RuntimeException 当短信模板不存在或发送失败时抛出
|
||||
*/
|
||||
@Override
|
||||
public void sendSms(SmsMessageDTO smsMessage) {
|
||||
try {
|
||||
// 根据模板代码获取短信模板
|
||||
PushTemplateDO templateByCode = messageHandleService.getTemplateByCode(smsMessage.getTemplateCode());
|
||||
if (templateByCode == null) {
|
||||
logger.error("短信模板不存在: {},消息发送失败", smsMessage.getTemplateCode());
|
||||
throw new RuntimeException("短信模板不存在: " + smsMessage.getTemplateCode());
|
||||
}
|
||||
// 根据发送方式调用不同的发送逻辑
|
||||
if ("SPUG".equals(smsMessage.getSendMethod())){
|
||||
String result = sendSmsBySpug(smsMessage,templateByCode);
|
||||
logger.info("短信发送结果: {}", result);
|
||||
}
|
||||
// TODO: 实现其他短信发送逻辑
|
||||
} catch (Exception e) {
|
||||
logger.error("短信发送失败: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("短信发送失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 通过SPUG平台发送短信
|
||||
* @param message 短信消息DTO
|
||||
* @return 发送结果字符串
|
||||
*/
|
||||
private String sendSmsBySpug(SmsMessageDTO message,PushTemplateDO templateByCode) {
|
||||
HttpURLConnection conn = null;
|
||||
BufferedReader br = null;
|
||||
try {
|
||||
// 构建请求URL
|
||||
String url = spugBaseUrl + "/sms/" + templateByCode.getExternalId();
|
||||
// 将模板参数转换为JSON字符串
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
Map<String, Object> templateParams = message.getTemplateParams();
|
||||
templateParams.put("to",message.getReceiver());
|
||||
String json = objectMapper.writeValueAsString(templateParams);
|
||||
|
||||
// 创建HTTP连接
|
||||
conn = (HttpURLConnection) new URL(url).openConnection();
|
||||
conn.setRequestMethod("POST");
|
||||
conn.setRequestProperty("Content-Type", "application/json");
|
||||
conn.setDoOutput(true);
|
||||
// 设置连接和读取超时时间
|
||||
conn.setConnectTimeout(5000);
|
||||
conn.setReadTimeout(10000);
|
||||
|
||||
// 发送请求
|
||||
try (OutputStream os = conn.getOutputStream()) {
|
||||
os.write(json.getBytes());
|
||||
}
|
||||
|
||||
// 获取响应状态码
|
||||
int responseCode = conn.getResponseCode();
|
||||
if (responseCode != HttpURLConnection.HTTP_OK) {
|
||||
logger.error("HTTP请求失败,状态码: {}", responseCode);
|
||||
throw new IOException("HTTP请求失败,状态码: " + responseCode);
|
||||
}
|
||||
// 读取响应内容
|
||||
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
|
||||
StringBuilder response = new StringBuilder();
|
||||
String line;
|
||||
while ((line = br.readLine()) != null) {
|
||||
response.append(line);
|
||||
}
|
||||
|
||||
return response.toString();
|
||||
} catch (Exception e) {
|
||||
logger.error("通过SPUG发送短信失败: {}", e.getMessage(), e);
|
||||
return "发送失败: " + e.getMessage();
|
||||
} finally {
|
||||
// 关闭资源
|
||||
if (br != null) {
|
||||
try {
|
||||
br.close();
|
||||
} catch (IOException e) {
|
||||
logger.error("关闭 BufferedReader 失败", e);
|
||||
}
|
||||
}
|
||||
if (conn != null) {
|
||||
conn.disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
package com.xiaowang.messagehub.service.impl;
|
||||
|
||||
import com.xiaowang.messagehub.config.SmsConfig;
|
||||
import com.xiaowang.messagehub.service.SmsSender;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.*;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
@Slf4j
|
||||
@Service("spugSmsSender")
|
||||
public class SpugSmsSender implements SmsSender {
|
||||
|
||||
@Autowired
|
||||
private SmsConfig smsConfig;
|
||||
|
||||
private RestTemplate restTemplate;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
restTemplate = new RestTemplate();
|
||||
log.info("Spug短信发送器初始化完成,模板ID: {}", smsConfig.getSpug().getTemplateId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendSms(String phone, String content) {
|
||||
try {
|
||||
String url = smsConfig.getSpug().getBaseUrl() + "/send/" + smsConfig.getSpug().getTemplateId();
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
|
||||
|
||||
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
||||
params.add("targets", phone);
|
||||
params.add("code", content);
|
||||
|
||||
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
|
||||
|
||||
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
|
||||
|
||||
if (response.getStatusCode() == HttpStatus.OK) {
|
||||
log.info("Spug短信发送成功,手机号: {}, 内容: {}, 响应: {}", phone, content, response.getBody());
|
||||
} else {
|
||||
log.error("Spug短信发送失败,手机号: {}, 状态码: {}", phone, response.getStatusCode());
|
||||
throw new RuntimeException("短信发送失败,状态码: " + response.getStatusCode());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Spug短信发送异常,手机号: {}, 内容: {}", phone, content, e);
|
||||
throw new RuntimeException("短信发送失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendSms(String phone, String templateId, String... params) {
|
||||
try {
|
||||
String url = smsConfig.getSpug().getBaseUrl() + "/send/" + templateId;
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
|
||||
|
||||
MultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>();
|
||||
requestParams.add("targets", phone);
|
||||
|
||||
if (params != null && params.length > 0) {
|
||||
for (int i = 0; i < params.length; i++) {
|
||||
requestParams.add("param" + (i + 1), params[i]);
|
||||
}
|
||||
}
|
||||
|
||||
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(requestParams, headers);
|
||||
|
||||
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
|
||||
|
||||
if (response.getStatusCode() == HttpStatus.OK) {
|
||||
log.info("Spug短信发送成功,手机号: {}, 模板ID: {}, 响应: {}", phone, templateId, response.getBody());
|
||||
} else {
|
||||
log.error("Spug短信发送失败,手机号: {}, 模板ID: {}, 状态码: {}", phone, templateId, response.getStatusCode());
|
||||
throw new RuntimeException("短信发送失败,状态码: " + response.getStatusCode());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Spug短信发送异常,手机号: {}, 模板ID: {}", phone, templateId, e);
|
||||
throw new RuntimeException("短信发送失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPlatformName() {
|
||||
return "Spug";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
spring:
|
||||
application:
|
||||
name: MessageHub
|
||||
|
||||
spug:
|
||||
sms:
|
||||
url: https://push.spug.cc/sms/A27L33fbgEY # SPUG短信发送接口URL
|
||||
token: d3f334****567890 # SPUG用户ID,用于查询发送状态
|
||||
@@ -0,0 +1,85 @@
|
||||
# 消息队列处理流程文档
|
||||
|
||||
## 整体流程
|
||||
|
||||
当消息队列中收到短信消息时,系统的处理流程如下:
|
||||
|
||||
### 1. 消息接收与解析
|
||||
- **类**: `SmsQueueListener`
|
||||
- **方法**: `handleSmsMessage(Message message, Channel channel)`
|
||||
- **步骤**:
|
||||
1. 接收来自 `smsQueue` 队列的消息
|
||||
2. 获取消息ID和当前时间
|
||||
3. 将消息体转换为字符串并打印日志
|
||||
4. 使用 `ObjectMapper` 将消息体反序列化为 `MessageDTO` 对象
|
||||
|
||||
### 2. 消息验证与日志保存
|
||||
- **类**: `MessageHandleService`
|
||||
- **方法**: `validateAndSaveLog(MessageDTO messageDTO, String messageId, LocalDateTime sendTime)`
|
||||
- **步骤**:
|
||||
1. 验证消息的有效性(如必填字段检查)
|
||||
2. 保存推送日志到数据库
|
||||
|
||||
### 3. 模板处理与内容生成
|
||||
- **类**: `MessageHandleService`
|
||||
- **方法**:
|
||||
- `getTemplateByCode(String templateCode)`: 根据模板编码从数据库获取模板
|
||||
- `replaceTemplatePlaceholders(String contentPattern, Map<String, Object> params)`: 替换模板中的占位符
|
||||
- **步骤**:
|
||||
1. 检查消息是否包含模板编码
|
||||
2. 如果有模板编码,从数据库获取模板信息
|
||||
3. 使用模板内容和参数生成最终消息内容
|
||||
4. 如果没有模板编码,使用默认内容
|
||||
|
||||
### 4. 短信发送
|
||||
- **类**: `SmsSendService`
|
||||
- **方法**: `sendSms(String phone, String content)`
|
||||
- **步骤**:
|
||||
1. 从配置中获取短信平台名称(默认为 "spug")
|
||||
2. 根据平台名称从 `smsSenders` 列表中找到对应的发送器
|
||||
3. 调用发送器的 `sendSms` 方法发送短信
|
||||
|
||||
### 5. Spug短信发送
|
||||
- **类**: `SpugSmsSender`
|
||||
- **方法**: `sendSms(String phone, String content)`
|
||||
- **步骤**:
|
||||
1. 从数据库获取默认短信模板(模板编码 "SMS0001",渠道 "SMS")
|
||||
2. 构建Spug API的URL(使用配置的baseUrl + "/sms/" + 模板的externalId)
|
||||
3. 构建JSON格式的请求参数(包含to和code字段)
|
||||
4. 发送HTTP POST请求到Spug API
|
||||
5. 处理响应并记录日志
|
||||
|
||||
### 6. 消息确认
|
||||
- **类**: `SmsQueueListener`
|
||||
- **方法**: `handleSmsMessage(Message message, Channel channel)`
|
||||
- **步骤**:
|
||||
1. 处理完成后,调用 `channel.basicAck` 确认消息已处理
|
||||
2. 即使发生异常也确认消息,避免重复处理
|
||||
|
||||
## 关键类和方法调用链
|
||||
|
||||
```
|
||||
SmsQueueListener.handleSmsMessage()
|
||||
→ MessageHandleService.validateAndSaveLog()
|
||||
→ MessageHandleService.getTemplateByCode()
|
||||
→ MessageHandleService.replaceTemplatePlaceholders()
|
||||
→ SmsSendService.sendSms()
|
||||
→ SpugSmsSender.sendSms()
|
||||
→ PushTemplateService.getTemplateByCodeAndChannel()
|
||||
→ PushTemplateMapper.selectOne()
|
||||
```
|
||||
|
||||
## 数据流向
|
||||
|
||||
1. **输入**: 消息队列中的JSON消息
|
||||
2. **处理**: 消息解析 → 验证 → 模板处理 → 内容生成 → 短信发送
|
||||
3. **输出**: 发送到Spug API的HTTP请求,以及数据库中的推送日志
|
||||
|
||||
## 配置依赖
|
||||
|
||||
- **SmsConfig**: 提供短信平台配置(如baseUrl)
|
||||
- **PushTemplateService**: 提供模板查询服务
|
||||
- **RabbitMQ**: 提供消息队列功能
|
||||
- **Spug API**: 提供实际的短信发送服务
|
||||
|
||||
此流程确保了消息的可靠处理和短信的及时发送,同时保持了系统的可扩展性和可维护性。
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.xiaowang.yuminailcore.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.Pattern;
|
||||
|
||||
/**
|
||||
* 注册请求 DTO
|
||||
@@ -13,9 +15,18 @@ public class RegisterRequestDTO {
|
||||
|
||||
private String account;
|
||||
|
||||
@NotBlank(message = "密码不能为空")
|
||||
private String password;
|
||||
|
||||
private String nickname;
|
||||
|
||||
private Long shopId;
|
||||
|
||||
@NotBlank(message = "手机号不能为空")
|
||||
@Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
|
||||
private String phone;
|
||||
|
||||
@NotBlank(message = "验证码不能为空")
|
||||
@Pattern(regexp = "^\\d{6}$", message = "验证码必须是6位数字")
|
||||
private String verificationCode;
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.xiaowang.yuminailcore.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.Pattern;
|
||||
|
||||
/**
|
||||
* 发送验证码请求 DTO
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-03-03
|
||||
*/
|
||||
@Data
|
||||
public class SendVerificationCodeRequestDTO {
|
||||
|
||||
@NotBlank(message = "手机号不能为空")
|
||||
@Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
|
||||
private String phone;
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.xiaowang.yuminailcore.service;
|
||||
|
||||
/**
|
||||
* 验证码服务接口
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2026-03-03
|
||||
*/
|
||||
public interface VerificationCodeService {
|
||||
|
||||
String generateVerificationCode();
|
||||
|
||||
void sendVerificationCode(String phone);
|
||||
|
||||
boolean verifyCode(String phone, String code);
|
||||
|
||||
boolean canResend(String phone);
|
||||
}
|
||||
Reference in New Issue
Block a user