feat: 短信服务
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
FROM openjdk:8u292
|
||||
|
||||
LABEL MAINTAINER=Andy
|
||||
WORKDIR /apps
|
||||
ADD target/msg-center.jar /apps/
|
||||
CMD ["java","-jar","msg-center.jar"]
|
||||
# docker run --name msg-center \
|
||||
# -e spring_cloud_nacos_server_addr=10.0.0.12:8848 \
|
||||
# -e zlt_datasource_ip=10.0.0.12 \
|
||||
# -e zlt_datasource_username=root \
|
||||
# -e zlt_datasource_password=redhat \
|
||||
# -e spring_redis_host=10.0.0.12 \
|
||||
# -d msg-center:6.0.0
|
||||
@@ -0,0 +1,563 @@
|
||||
# 消息中心 (msg-center)
|
||||
|
||||
消息中心是一个独立的微服务模块,提供短信、邮件、推送等消息发送功能。
|
||||
|
||||
## 功能特性
|
||||
|
||||
### 已实现功能
|
||||
- ✅ 腾讯云短信发送
|
||||
- ✅ 阿里云短信发送
|
||||
- ✅ **阿里云和腾讯云独立API接口(可分别调用)**
|
||||
- ✅ 多服务商切换(支持动态配置)
|
||||
- ✅ 短信发送记录保存到数据库
|
||||
- ✅ 验证码短信发送
|
||||
- ✅ RESTful API接口
|
||||
- ✅ 短信发送记录查询
|
||||
|
||||
### 计划功能
|
||||
- 📋 邮件发送
|
||||
- 📋 站内消息
|
||||
- 📋 APP推送通知
|
||||
- 📋 短信发送统计
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 1. 数据库初始化
|
||||
|
||||
执行数据库初始化脚本创建短信发送记录表:
|
||||
|
||||
```bash
|
||||
mysql -u root -p your_database < db/init.sql
|
||||
```
|
||||
|
||||
或手动执行 `db/init.sql` 中的SQL语句。
|
||||
|
||||
### 2. 配置短信服务商
|
||||
|
||||
支持两种短信服务商:**腾讯云** 和 **阿里云**。
|
||||
|
||||
**重要更新:** 现在支持**同时配置两个服务商**,并通过不同的API接口分别调用,无需切换配置!
|
||||
|
||||
#### 同时配置腾讯云和阿里云
|
||||
|
||||
在 `application.yml` 中配置:
|
||||
|
||||
```yaml
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:mysql://${zlt.datasource.ip}/msg-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
|
||||
username: ${zlt.datasource.username}
|
||||
password: ${zlt.datasource.password}
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
|
||||
sms:
|
||||
# 默认服务商(用于通用接口 /sms/send)
|
||||
provider: TENCENT
|
||||
|
||||
# 腾讯云短信配置
|
||||
tencent:
|
||||
app-id: 1400xxxxxx # 在腾讯云短信控制台获取
|
||||
secret-id: AKIDxxxxxxxx # 在腾讯云控制台获取
|
||||
secret-key: xxxxxxxx # 在腾讯云控制台获取
|
||||
sign-name: 您的签名 # 在腾讯云短信控制台配置
|
||||
verify-code-template-id: 1234567 # 腾讯云验证码模板ID
|
||||
|
||||
# 阿里云短信配置
|
||||
aliyun:
|
||||
access-key-id: LTAIxxxxxxxx # 在阿里云控制台获取
|
||||
access-key-secret: xxxxxxxx # 在阿里云控制台获取
|
||||
sign-name: 您的签名 # 在阿里云短信控制台配置
|
||||
verify-code-template-id: SMS_123456789 # 阿里云验证码模板CODE
|
||||
|
||||
# 是否保存短信发送记录到数据库
|
||||
save-log: true
|
||||
```
|
||||
|
||||
**环境变量配置(推荐):**
|
||||
|
||||
```bash
|
||||
# 数据库配置
|
||||
export zlt.datasource.ip=localhost:3306
|
||||
export zlt.datasource.username=root
|
||||
export zlt.datasource.password=yourpassword
|
||||
|
||||
# 默认服务商
|
||||
export SMS_PROVIDER=TENCENT
|
||||
|
||||
# 腾讯云配置
|
||||
export SMS_TENCENT_APP_ID=1400xxxxxx
|
||||
export SMS_TENCENT_SECRET_ID=AKIDxxxxxxxxxxxxxxxx
|
||||
export SMS_TENCENT_SECRET_KEY=xxxxxxxxxxxxxxxx
|
||||
export SMS_TENCENT_SIGN_NAME=您的签名
|
||||
export SMS_TENCENT_VERIFY_CODE_TEMPLATE_ID=1234567
|
||||
|
||||
# 阿里云配置
|
||||
export SMS_ALIYUN_ACCESS_KEY_ID=LTAIxxxxxxxx
|
||||
export SMS_ALIYUN_ACCESS_KEY_SECRET=xxxxxxxxxxxxxxxx
|
||||
export SMS_ALIYUN_SIGN_NAME=您的签名
|
||||
export SMS_ALIYUN_VERIFY_CODE_TEMPLATE_ID=SMS_123456789
|
||||
```
|
||||
|
||||
### 3. 获取配置参数
|
||||
|
||||
#### 腾讯云短信配置参数获取
|
||||
|
||||
1. 登录 [腾讯云短信控制台](https://console.cloud.tencent.com/smsv2)
|
||||
2. 创建短信应用,获取 `app-id`
|
||||
3. 前往 [API密钥管理](https://console.cloud.tencent.com/cam/capi) 获取 `secret-id` 和 `secret-key`
|
||||
4. 在短信控制台配置短信签名,获取 `sign-name`
|
||||
5. 创建短信模板,获取 `template-id`
|
||||
|
||||
#### 阿里云短信配置参数获取
|
||||
|
||||
1. 登录 [阿里云短信控制台](https://dysms.console.aliyun.com/)
|
||||
2. 前往 [AccessKey管理](https://ram.console.aliyun.com/manage/ak) 创建AccessKey,获取 `access-key-id` 和 `access-key-secret`
|
||||
3. 在短信控制台申请短信签名,获取 `sign-name`
|
||||
4. 创建短信模板,获取模板CODE(即 `template-id`,如:SMS_123456789)
|
||||
|
||||
### 4. 启动服务
|
||||
|
||||
```bash
|
||||
cd zlt-business/msg-center
|
||||
mvn spring-boot:run
|
||||
```
|
||||
|
||||
## API接口文档
|
||||
|
||||
服务启动后,访问 Swagger 文档:
|
||||
```
|
||||
http://localhost:8080/doc.html
|
||||
```
|
||||
|
||||
### 主要接口
|
||||
|
||||
#### 1. 发送短信(使用默认服务商)
|
||||
|
||||
**接口地址:** `POST /sms/send`
|
||||
|
||||
**说明:** 使用配置文件中 `sms.provider` 指定的默认服务商发送短信
|
||||
|
||||
**请求参数:**
|
||||
```json
|
||||
{
|
||||
"phone": "13800138000",
|
||||
"templateId": "1234567",
|
||||
"params": {
|
||||
"code": "123456",
|
||||
"time": "5"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**响应示例:**
|
||||
```json
|
||||
{
|
||||
"resp_code": 0,
|
||||
"resp_msg": "success",
|
||||
"datas": {
|
||||
"success": true,
|
||||
"message": "短信发送成功"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 2. 发送阿里云短信
|
||||
|
||||
**接口地址:** `POST /sms/aliyun/send`
|
||||
|
||||
**说明:** 强制使用阿里云发送短信,不受默认配置影响
|
||||
|
||||
**请求参数:**
|
||||
```json
|
||||
{
|
||||
"phone": "13800138000",
|
||||
"templateId": "SMS_123456789",
|
||||
"params": {
|
||||
"code": "123456",
|
||||
"time": "5"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**响应示例:**
|
||||
```json
|
||||
{
|
||||
"resp_code": 0,
|
||||
"resp_msg": "success",
|
||||
"datas": {
|
||||
"success": true,
|
||||
"message": "阿里云短信发送成功"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 3. 发送腾讯云短信
|
||||
|
||||
**接口地址:** `POST /sms/tencent/send`
|
||||
|
||||
**说明:** 强制使用腾讯云发送短信,不受默认配置影响
|
||||
|
||||
**请求参数:**
|
||||
```json
|
||||
{
|
||||
"phone": "13800138000",
|
||||
"templateId": "1234567",
|
||||
"params": {
|
||||
"code": "123456",
|
||||
"time": "5"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**响应示例:**
|
||||
```json
|
||||
{
|
||||
"resp_code": 0,
|
||||
"resp_msg": "success",
|
||||
"datas": {
|
||||
"success": true,
|
||||
"message": "腾讯云短信发送成功"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 4. 发送验证码(使用默认服务商)
|
||||
|
||||
**接口地址:** `POST /sms/send-verify-code`
|
||||
|
||||
**请求参数:**
|
||||
- `phone`: 手机号(必填)
|
||||
- `code`: 验证码(必填)
|
||||
|
||||
**示例:**
|
||||
```
|
||||
POST /sms/send-verify-code?phone=13800138000&code=123456
|
||||
```
|
||||
|
||||
**响应示例:**
|
||||
```json
|
||||
{
|
||||
"resp_code": 0,
|
||||
"resp_msg": "success",
|
||||
"datas": {
|
||||
"success": true,
|
||||
"message": "验证码发送成功"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 5. 发送阿里云验证码
|
||||
|
||||
**接口地址:** `POST /sms/aliyun/send-verify-code`
|
||||
|
||||
**说明:** 强制使用阿里云发送验证码,使用阿里云配置的验证码模板
|
||||
|
||||
**请求参数:**
|
||||
- `phone`: 手机号(必填)
|
||||
- `code`: 验证码(必填)
|
||||
|
||||
**示例:**
|
||||
```
|
||||
POST /sms/aliyun/send-verify-code?phone=13800138000&code=123456
|
||||
```
|
||||
|
||||
#### 6. 发送腾讯云验证码
|
||||
|
||||
**接口地址:** `POST /sms/tencent/send-verify-code`
|
||||
|
||||
**说明:** 强制使用腾讯云发送验证码,使用腾讯云配置的验证码模板
|
||||
|
||||
**请求参数:**
|
||||
- `phone`: 手机号(必填)
|
||||
- `code`: 验证码(必填)
|
||||
|
||||
**示例:**
|
||||
```
|
||||
POST /sms/tencent/send-verify-code?phone=13800138000&code=123456
|
||||
```
|
||||
|
||||
#### 7. 查询短信发送记录
|
||||
|
||||
**接口地址:** `GET /sms/logs`
|
||||
|
||||
**请求参数:**
|
||||
- `page`: 当前页(默认1)
|
||||
- `size`: 每页大小(默认10)
|
||||
- `phone`: 手机号(可选,模糊查询)
|
||||
- `status`: 状态(可选,0-失败, 1-成功, 2-发送中)
|
||||
|
||||
**示例:**
|
||||
```
|
||||
GET /sms/logs?page=1&size=10&phone=138&status=1
|
||||
```
|
||||
|
||||
**响应示例:**
|
||||
```json
|
||||
{
|
||||
"resp_code": 0,
|
||||
"resp_msg": "success",
|
||||
"datas": {
|
||||
"records": [...],
|
||||
"total": 100,
|
||||
"size": 10,
|
||||
"current": 1,
|
||||
"pages": 10
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 短信模板参数说明
|
||||
|
||||
### 腾讯云模板示例
|
||||
|
||||
**模板内容:**
|
||||
```
|
||||
{1}为您的登录验证码,请于{2}分钟内填写。如非本人操作,请忽略本短信。
|
||||
```
|
||||
|
||||
**对应参数:**
|
||||
```json
|
||||
{
|
||||
"params": {
|
||||
"code": "123456", // {1} 验证码
|
||||
"time": "5" // {2} 有效期(分钟)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 阿里云模板示例
|
||||
|
||||
**模板内容:**
|
||||
```
|
||||
验证码${code},您正在进行身份验证,打死不告诉别人哦!有效期${time}分钟。
|
||||
```
|
||||
|
||||
**对应参数:**
|
||||
```json
|
||||
{
|
||||
"params": {
|
||||
"code": "123456", // ${code} 验证码
|
||||
"time": "5" // ${time} 有效期(分钟)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**注意事项:**
|
||||
- 腾讯云使用 `{1}`, `{2}` 这样的占位符,参数按顺序传入
|
||||
- 阿里云使用 `${变量名}` 这样的占位符,参数需要使用JSON格式的key-value对
|
||||
|
||||
## 数据库表结构
|
||||
|
||||
### sms_send_log - 短信发送记录表
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| id | bigint | 主键ID |
|
||||
| phone | varchar(20) | 手机号 |
|
||||
| template_id | varchar(50) | 短信模板ID |
|
||||
| template_params | varchar(500) | 模板参数(JSON格式) |
|
||||
| content | varchar(500) | 短信内容 |
|
||||
| status | tinyint | 发送状态: 0-失败, 1-成功, 2-发送中 |
|
||||
| provider | varchar(20) | 服务商: TENCENT, ALIYUN |
|
||||
| request_id | varchar(100) | 服务商返回的请求ID |
|
||||
| response_code | varchar(50) | 服务商返回的状态码 |
|
||||
| response_message | varchar(200) | 服务商返回的消息 |
|
||||
| error_message | varchar(500) | 错误信息 |
|
||||
| tenant_id | varchar(32) | 租户ID |
|
||||
| create_time | datetime | 创建时间 |
|
||||
| update_time | datetime | 更新时间 |
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
msg-center/
|
||||
├── db/
|
||||
│ └── init.sql # 数据库初始化脚本
|
||||
├── src/
|
||||
│ └── main/
|
||||
│ ├── java/com/central/
|
||||
│ │ ├── MsgCenterApp.java # 启动类
|
||||
│ │ └── msg/
|
||||
│ │ ├── config/
|
||||
│ │ │ └── SmsConfig.java
|
||||
│ │ ├── controller/
|
||||
│ │ │ └── SmsController.java
|
||||
│ │ ├── mapper/
|
||||
│ │ │ └── SmsSendLogMapper.java
|
||||
│ │ ├── model/
|
||||
│ │ │ ├── dto/
|
||||
│ │ │ │ ├── SmsRequest.java
|
||||
│ │ │ │ └── SmsResponse.java
|
||||
│ │ │ └── entity/
|
||||
│ │ │ └── SmsSendLog.java
|
||||
│ │ └── service/
|
||||
│ │ ├── MsgSmsService.java
|
||||
│ │ └── impl/
|
||||
│ │ └── MsgSmsServiceImpl.java
|
||||
│ └── resources/
|
||||
│ ├── application.yml # 配置文件
|
||||
│ ├── bootstrap.yml # 服务名称配置
|
||||
│ └── mapper/
|
||||
│ └── SmsSendLogMapper.xml
|
||||
├── Dockerfile # Docker镜像构建文件
|
||||
├── pom.xml # Maven配置
|
||||
└── README.md # 本文档
|
||||
```
|
||||
|
||||
## 常见问题
|
||||
|
||||
### 1. 短信发送失败
|
||||
|
||||
**可能原因:**
|
||||
- 配置参数错误(检查各项配置是否正确)
|
||||
- 签名未审核通过
|
||||
- 模板未审核通过
|
||||
- 账户余额不足
|
||||
- 手机号格式错误
|
||||
- 发送频率过高(部分运营商有限制)
|
||||
|
||||
**解决方法:**
|
||||
- 查看日志中的详细错误信息
|
||||
- 登录服务商控制台检查签名和模板审核状态
|
||||
- 确认账户余额充足
|
||||
- 检查手机号格式是否正确
|
||||
- 调整发送频率
|
||||
|
||||
### 2. 数据库连接失败
|
||||
|
||||
确保在 `application.yml` 或 Nacos 配置中心配置了正确的数据库连接信息。
|
||||
|
||||
### 3. 如何在运行时切换短信服务商
|
||||
|
||||
**新版本:无需切换!**
|
||||
|
||||
现在你可以**同时使用阿里云和腾讯云**,只需调用不同的API接口即可:
|
||||
|
||||
- **阿里云短信:** `POST /sms/aliyun/send` 或 `POST /sms/aliyun/send-verify-code`
|
||||
- **腾讯云短信:** `POST /sms/tencent/send` 或 `POST /sms/tencent/send-verify-code`
|
||||
- **默认服务商:** `POST /sms/send` 或 `POST /sms/send-verify-code`(使用配置文件中的 `sms.provider`)
|
||||
|
||||
**使用场景示例:**
|
||||
|
||||
```bash
|
||||
# 某个服务需要使用阿里云发送营销短信
|
||||
curl -X POST http://localhost:8080/sms/aliyun/send \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"phone": "13800138000",
|
||||
"templateId": "SMS_123456789",
|
||||
"params": {"code": "123456", "time": "5"}
|
||||
}'
|
||||
|
||||
# 另一个服务需要使用腾讯云发送验证码
|
||||
curl -X POST http://localhost:8080/sms/tencent/send-verify-code \
|
||||
-d "phone=13900139000&code=654321"
|
||||
```
|
||||
|
||||
**旧方法(仍然支持):**
|
||||
|
||||
如果你只想使用一个服务商,可以通过修改配置切换:
|
||||
|
||||
**方法一:修改配置文件**
|
||||
```yaml
|
||||
sms:
|
||||
provider: ALIYUN # 将 TENCENT 改为 ALIYUN
|
||||
```
|
||||
|
||||
**方法二:使用环境变量(推荐)**
|
||||
```bash
|
||||
export SMS_PROVIDER=ALIYUN
|
||||
```
|
||||
|
||||
重启服务后生效。
|
||||
|
||||
### 4. 腾讯云和阿里云的区别
|
||||
|
||||
| 特性 | 腾讯云 | 阿里云 |
|
||||
|------|--------|--------|
|
||||
| 模板格式 | {1}, {2}, {3}... | ${变量名} |
|
||||
| 参数格式 | 数组形式,按顺序 | JSON键值对 |
|
||||
| 手机号格式 | 需要+86前缀 | 直接手机号 |
|
||||
| SDK包名 | tencentcloud-sdk-java | aliyun-java-sdk-dysmsapi |
|
||||
|
||||
### 5. 如何同时配置两个服务商并分别调用
|
||||
|
||||
**现在已经默认支持!** 无需任何特殊配置。
|
||||
|
||||
只需在配置文件中同时配置腾讯云和阿里云的参数:
|
||||
|
||||
```yaml
|
||||
sms:
|
||||
provider: TENCENT # 默认服务商(用于 /sms/send 接口)
|
||||
|
||||
tencent:
|
||||
app-id: xxx
|
||||
secret-id: xxx
|
||||
secret-key: xxx
|
||||
sign-name: xxx
|
||||
verify-code-template-id: xxx
|
||||
|
||||
aliyun:
|
||||
access-key-id: xxx
|
||||
access-key-secret: xxx
|
||||
sign-name: xxx
|
||||
verify-code-template-id: xxx
|
||||
```
|
||||
|
||||
**然后直接调用对应的API接口:**
|
||||
|
||||
```bash
|
||||
# 使用阿里云发送
|
||||
POST /sms/aliyun/send
|
||||
|
||||
# 使用腾讯云发送
|
||||
POST /sms/tencent/send
|
||||
|
||||
# 使用默认服务商(TENCENT)发送
|
||||
POST /sms/send
|
||||
```
|
||||
|
||||
**优势:**
|
||||
- ✅ 不同服务可以选择不同的短信服务商
|
||||
- ✅ 无需重启服务即可使用不同的服务商
|
||||
- ✅ 可以根据成本、到达率等因素灵活选择
|
||||
- ✅ 支持灾备切换(一个服务商故障时使用另一个)
|
||||
|
||||
**实际应用场景:**
|
||||
|
||||
```java
|
||||
// 服务A:使用阿里云发送营销短信
|
||||
POST /sms/aliyun/send
|
||||
|
||||
// 服务B:使用腾讯云发送验证码
|
||||
POST /sms/tencent/send-verify-code
|
||||
|
||||
// 服务C:使用默认配置发送通知短信
|
||||
POST /sms/send
|
||||
```
|
||||
|
||||
## 开发计划
|
||||
|
||||
- [ ] 添加短信发送频率限制(防刷)
|
||||
- [ ] 添加短信发送统计报表
|
||||
- [ ] 支持批量发送短信
|
||||
- [ ] 添加短信发送队列(异步发送)
|
||||
- [ ] 支持更多短信服务商(华为云、七牛云等)
|
||||
- [ ] 添加邮件发送功能
|
||||
- [ ] 添加消息模板管理
|
||||
- [ ] 添加短信发送失败重试机制
|
||||
|
||||
## 技术栈
|
||||
|
||||
- Spring Boot 3.1.6
|
||||
- Spring Cloud
|
||||
- MyBatis Plus 3.5.4
|
||||
- 腾讯云短信 SDK 3.1.1040
|
||||
- 阿里云短信 SDK 2.1.0
|
||||
- MySQL 8.0
|
||||
- Redis 7.0
|
||||
- Nacos (服务注册与配置中心)
|
||||
|
||||
## 联系方式
|
||||
|
||||
如有问题,请提交 Issue 或联系开发团队。
|
||||
@@ -0,0 +1,26 @@
|
||||
-- =============================================
|
||||
-- 消息中心 - 短信发送记录表
|
||||
-- =============================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `sms_send_log` (
|
||||
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||
`phone` varchar(20) NOT NULL COMMENT '手机号',
|
||||
`template_id` varchar(50) NOT NULL COMMENT '短信模板ID',
|
||||
`template_params` varchar(500) DEFAULT NULL COMMENT '模板参数(JSON格式)',
|
||||
`content` varchar(500) DEFAULT NULL COMMENT '短信内容',
|
||||
`status` tinyint(4) NOT NULL DEFAULT '2' COMMENT '发送状态: 0-失败, 1-成功, 2-发送中',
|
||||
`provider` varchar(20) NOT NULL DEFAULT 'TENCENT' COMMENT '服务商: TENCENT, ALIYUN',
|
||||
`request_id` varchar(100) DEFAULT NULL COMMENT '服务商返回的请求ID',
|
||||
`response_code` varchar(50) DEFAULT NULL COMMENT '服务商返回的状态码',
|
||||
`response_message` varchar(200) DEFAULT NULL COMMENT '服务商返回的消息',
|
||||
`error_message` varchar(500) DEFAULT NULL COMMENT '错误信息',
|
||||
`tenant_id` varchar(32) DEFAULT NULL COMMENT '租户ID',
|
||||
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_phone` (`phone`),
|
||||
KEY `idx_template_id` (`template_id`),
|
||||
KEY `idx_create_time` (`create_time`),
|
||||
KEY `idx_status` (`status`),
|
||||
KEY `idx_tenant_id` (`tenant_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='短信发送记录表';
|
||||
@@ -0,0 +1,130 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-business</artifactId>
|
||||
<version>6.0.0</version>
|
||||
</parent>
|
||||
<artifactId>msg-center</artifactId>
|
||||
<description>消息中心</description>
|
||||
<dependencies>
|
||||
<!-- 公共实体类模块 -->
|
||||
<dependency>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-config</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-log-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-common-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-db-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-redis-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-loadbalancer-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-sentinel-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<!-- swagger -->
|
||||
<dependency>
|
||||
<groupId>com.github.xiaoymin</groupId>
|
||||
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.micrometer</groupId>
|
||||
<artifactId>micrometer-registry-prometheus</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-validator</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- 短信服务 -->
|
||||
<dependency>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-sms-spring-boot-starter</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>com.spotify</groupId>
|
||||
<artifactId>docker-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<imageName>${docker.image.prefix}/${project.artifactId}</imageName>
|
||||
<imageTags>
|
||||
<imageTag>${project.version}</imageTag>
|
||||
<imageTag>latest</imageTag>
|
||||
</imageTags>
|
||||
<forceTags>true</forceTags>
|
||||
<baseImage>${docker.baseImage}</baseImage>
|
||||
<volumes>${docker.volumes}</volumes>
|
||||
<env>
|
||||
<JAVA_OPTS>${docker.java.opts}</JAVA_OPTS>
|
||||
</env>
|
||||
<entryPoint>["sh","-c","java $JAVA_OPTS ${docker.java.security.egd} -jar /${project.build.finalName}.jar"]</entryPoint>
|
||||
<resources>
|
||||
<resource>
|
||||
<targetPath>/</targetPath>
|
||||
<directory>${project.build.directory}</directory>
|
||||
<include>${project.build.finalName}.jar</include>
|
||||
</resource>
|
||||
</resources>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
<finalName>${project.artifactId}</finalName>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.central;
|
||||
|
||||
import com.central.common.lb.annotation.EnableFeignInterceptor;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
/**
|
||||
* 消息中心启动类
|
||||
* @author system
|
||||
*/
|
||||
@EnableDiscoveryClient
|
||||
@EnableTransactionManagement
|
||||
@EnableFeignInterceptor
|
||||
@SpringBootApplication
|
||||
public class MsgCenterApp {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(MsgCenterApp.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.central.msg.config;
|
||||
|
||||
import com.central.sms.config.SmsProperties;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* 短信配置类
|
||||
* @author system
|
||||
*/
|
||||
@Configuration
|
||||
@EnableConfigurationProperties(SmsProperties.class)
|
||||
public class SmsConfig {
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package com.central.msg.controller;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.central.common.model.Result;
|
||||
import com.central.msg.model.dto.SmsRequest;
|
||||
import com.central.msg.model.dto.SmsResponse;
|
||||
import com.central.msg.model.entity.SmsSendLog;
|
||||
import com.central.msg.service.MsgSmsService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
/**
|
||||
* 短信发送Controller
|
||||
* @author system
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/sms")
|
||||
@Tag(name = "短信服务", description = "短信发送相关接口")
|
||||
public class SmsController {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(SmsController.class);
|
||||
|
||||
@Autowired
|
||||
private MsgSmsService msgSmsService;
|
||||
|
||||
/**
|
||||
* 发送短信(使用默认服务商)
|
||||
*/
|
||||
@PostMapping("/send")
|
||||
@Operation(summary = "发送短信", description = "使用默认服务商发送模板短信")
|
||||
public Result<SmsResponse> sendSms(@Valid @RequestBody SmsRequest request) {
|
||||
logger.info("收到短信发送请求: {}", request);
|
||||
|
||||
try {
|
||||
boolean success = msgSmsService.sendSms(
|
||||
request.getPhone(),
|
||||
request.getTemplateId(),
|
||||
request.getParams()
|
||||
);
|
||||
|
||||
if (success) {
|
||||
SmsResponse response = new SmsResponse(true, "短信发送成功");
|
||||
return Result.succeed(response);
|
||||
} else {
|
||||
SmsResponse response = new SmsResponse(false, "短信发送失败");
|
||||
return Result.failed(response,"短信发送失败!");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("短信发送异常: {}", e.getMessage(), e);
|
||||
SmsResponse response = new SmsResponse(false, "短信发送异常: " + e.getMessage());
|
||||
return Result.failed(response,"短信发送失败!");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送阿里云短信
|
||||
*/
|
||||
@PostMapping("/aliyun/send")
|
||||
@Operation(summary = "发送阿里云短信", description = "使用阿里云发送模板短信")
|
||||
public Result<SmsResponse> sendAliyunSms(@Valid @RequestBody SmsRequest request) {
|
||||
logger.info("收到阿里云短信发送请求: {}", request);
|
||||
|
||||
try {
|
||||
boolean success = msgSmsService.sendAliyunSms(
|
||||
request.getPhone(),
|
||||
request.getTemplateId(),
|
||||
request.getParams()
|
||||
);
|
||||
|
||||
if (success) {
|
||||
SmsResponse response = new SmsResponse(true, "阿里云短信发送成功");
|
||||
return Result.succeed(response);
|
||||
} else {
|
||||
SmsResponse response = new SmsResponse(false, "阿里云短信发送失败");
|
||||
return Result.failed(response,"短信发送失败!");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("阿里云短信发送异常: {}", e.getMessage(), e);
|
||||
SmsResponse response = new SmsResponse(false, "阿里云短信发送异常: " + e.getMessage());
|
||||
return Result.failed(response,"短信发送失败!");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送腾讯云短信
|
||||
*/
|
||||
@PostMapping("/tencent/send")
|
||||
@Operation(summary = "发送腾讯云短信", description = "使用腾讯云发送模板短信")
|
||||
public Result<SmsResponse> sendTencentSms(@Valid @RequestBody SmsRequest request) {
|
||||
logger.info("收到腾讯云短信发送请求: {}", request);
|
||||
|
||||
try {
|
||||
boolean success = msgSmsService.sendTencentSms(
|
||||
request.getPhone(),
|
||||
request.getTemplateId(),
|
||||
request.getParams()
|
||||
);
|
||||
|
||||
if (success) {
|
||||
SmsResponse response = new SmsResponse(true, "腾讯云短信发送成功");
|
||||
return Result.succeed(response);
|
||||
} else {
|
||||
SmsResponse response = new SmsResponse(false, "腾讯云短信发送失败");
|
||||
return Result.failed(response,"短信发送失败!");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("腾讯云短信发送异常: {}", e.getMessage(), e);
|
||||
SmsResponse response = new SmsResponse(false, "腾讯云短信发送异常: " + e.getMessage());
|
||||
return Result.failed(response,"短信发送失败!");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送验证码(使用默认服务商)
|
||||
*/
|
||||
@PostMapping("/send-verify-code")
|
||||
@Operation(summary = "发送验证码", description = "使用默认服务商发送验证码短信")
|
||||
public Result<SmsResponse> sendVerifyCode(
|
||||
@Parameter(description = "手机号", required = true) @RequestParam("phone") String phone,
|
||||
@Parameter(description = "验证码", required = true) @RequestParam("code") String code) {
|
||||
logger.info("收到验证码发送请求: phone={}, code={}", phone, code);
|
||||
|
||||
try {
|
||||
boolean success = msgSmsService.sendVerifyCode(phone, code);
|
||||
|
||||
if (success) {
|
||||
SmsResponse response = new SmsResponse(true, "验证码发送成功");
|
||||
return Result.succeed(response);
|
||||
} else {
|
||||
SmsResponse response = new SmsResponse(false, "验证码发送失败");
|
||||
return Result.failed(response,"短信发送失败!");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("验证码发送异常: {}", e.getMessage(), e);
|
||||
SmsResponse response = new SmsResponse(false, "验证码发送异常: " + e.getMessage());
|
||||
return Result.failed(response,"短信发送失败!");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送阿里云验证码
|
||||
*/
|
||||
@PostMapping("/aliyun/send-verify-code")
|
||||
@Operation(summary = "发送阿里云验证码", description = "使用阿里云发送验证码短信")
|
||||
public Result<SmsResponse> sendAliyunVerifyCode(
|
||||
@Parameter(description = "手机号", required = true) @RequestParam("phone") String phone,
|
||||
@Parameter(description = "验证码", required = true) @RequestParam("code") String code) {
|
||||
logger.info("收到阿里云验证码发送请求: phone={}, code={}", phone, code);
|
||||
|
||||
try {
|
||||
boolean success = msgSmsService.sendAliyunVerifyCode(phone, code);
|
||||
|
||||
if (success) {
|
||||
SmsResponse response = new SmsResponse(true, "阿里云验证码发送成功");
|
||||
return Result.succeed(response);
|
||||
} else {
|
||||
SmsResponse response = new SmsResponse(false, "阿里云验证码发送失败");
|
||||
return Result.failed(response,"短信发送失败!");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("阿里云验证码发送异常: {}", e.getMessage(), e);
|
||||
SmsResponse response = new SmsResponse(false, "阿里云验证码发送异常: " + e.getMessage());
|
||||
return Result.failed(response,"短信发送失败!");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送腾讯云验证码
|
||||
*/
|
||||
@PostMapping("/tencent/send-verify-code")
|
||||
@Operation(summary = "发送腾讯云验证码", description = "使用腾讯云发送验证码短信")
|
||||
public Result<SmsResponse> sendTencentVerifyCode(
|
||||
@Parameter(description = "手机号", required = true) @RequestParam("phone") String phone,
|
||||
@Parameter(description = "验证码", required = true) @RequestParam("code") String code) {
|
||||
logger.info("收到腾讯云验证码发送请求: phone={}, code={}", phone, code);
|
||||
|
||||
try {
|
||||
boolean success = msgSmsService.sendTencentVerifyCode(phone, code);
|
||||
|
||||
if (success) {
|
||||
SmsResponse response = new SmsResponse(true, "腾讯云验证码发送成功");
|
||||
return Result.succeed(response);
|
||||
} else {
|
||||
SmsResponse response = new SmsResponse(false, "腾讯云验证码发送失败");
|
||||
return Result.failed(response,"短信发送失败!");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("腾讯云验证码发送异常: {}", e.getMessage(), e);
|
||||
SmsResponse response = new SmsResponse(false, "腾讯云验证码发送异常: " + e.getMessage());
|
||||
return Result.failed(response,"短信发送失败!");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询短信发送记录
|
||||
*/
|
||||
@GetMapping("/logs")
|
||||
@Operation(summary = "查询短信发送记录", description = "分页查询短信发送记录")
|
||||
public Result<Page<SmsSendLog>> querySmsSendLog(
|
||||
@Parameter(description = "当前页", required = true) @RequestParam(value = "page", defaultValue = "1") int page,
|
||||
@Parameter(description = "每页大小", required = true) @RequestParam(value = "size", defaultValue = "10") int size,
|
||||
@Parameter(description = "手机号") @RequestParam(value = "phone", required = false) String phone,
|
||||
@Parameter(description = "状态: 0-失败, 1-成功, 2-发送中") @RequestParam(value = "status", required = false) Integer status) {
|
||||
logger.info("查询短信发送记录: page={}, size={}, phone={}, status={}", page, size, phone, status);
|
||||
|
||||
try {
|
||||
Page<SmsSendLog> result = msgSmsService.querySmsSendLog(page, size, phone, status);
|
||||
return Result.succeed(result);
|
||||
} catch (Exception e) {
|
||||
logger.error("查询短信发送记录异常: {}", e.getMessage(), e);
|
||||
return Result.failed("查询失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.central.msg.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.central.msg.model.entity.SmsSendLog;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
/**
|
||||
* 短信发送记录Mapper
|
||||
* @author system
|
||||
*/
|
||||
@Mapper
|
||||
public interface SmsSendLogMapper extends BaseMapper<SmsSendLog> {
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.central.msg.model.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 短信发送请求DTO
|
||||
* @author system
|
||||
*/
|
||||
@Schema(description = "短信发送请求")
|
||||
public class SmsRequest {
|
||||
|
||||
@Schema(description = "手机号", required = true, example = "13800138000")
|
||||
@NotBlank(message = "手机号不能为空")
|
||||
@Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
|
||||
private String phone;
|
||||
|
||||
@Schema(description = "短信模板ID", required = true, example = "123456")
|
||||
@NotBlank(message = "模板ID不能为空")
|
||||
private String templateId;
|
||||
|
||||
@Schema(description = "模板参数", example = "{\"code\":\"1234\",\"time\":\"5\"}")
|
||||
private Map<String, String> params;
|
||||
|
||||
public String getPhone() {
|
||||
return phone;
|
||||
}
|
||||
|
||||
public void setPhone(String phone) {
|
||||
this.phone = phone;
|
||||
}
|
||||
|
||||
public String getTemplateId() {
|
||||
return templateId;
|
||||
}
|
||||
|
||||
public void setTemplateId(String templateId) {
|
||||
this.templateId = templateId;
|
||||
}
|
||||
|
||||
public Map<String, String> getParams() {
|
||||
return params;
|
||||
}
|
||||
|
||||
public void setParams(Map<String, String> params) {
|
||||
this.params = params;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "SmsRequest{" +
|
||||
"phone='" + phone + '\'' +
|
||||
", templateId='" + templateId + '\'' +
|
||||
", params=" + params +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.central.msg.model.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
/**
|
||||
* 短信发送响应DTO
|
||||
* @author system
|
||||
*/
|
||||
@Schema(description = "短信发送响应")
|
||||
public class SmsResponse {
|
||||
|
||||
@Schema(description = "是否成功")
|
||||
private boolean success;
|
||||
|
||||
@Schema(description = "消息")
|
||||
private String message;
|
||||
|
||||
@Schema(description = "请求ID")
|
||||
private String requestId;
|
||||
|
||||
public SmsResponse() {
|
||||
}
|
||||
|
||||
public SmsResponse(boolean success, String message) {
|
||||
this.success = success;
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public SmsResponse(boolean success, String message, String requestId) {
|
||||
this.success = success;
|
||||
this.message = message;
|
||||
this.requestId = requestId;
|
||||
}
|
||||
|
||||
public boolean isSuccess() {
|
||||
return success;
|
||||
}
|
||||
|
||||
public void setSuccess(boolean success) {
|
||||
this.success = success;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public String getRequestId() {
|
||||
return requestId;
|
||||
}
|
||||
|
||||
public void setRequestId(String requestId) {
|
||||
this.requestId = requestId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "SmsResponse{" +
|
||||
"success=" + success +
|
||||
", message='" + message + '\'' +
|
||||
", requestId='" + requestId + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.central.msg.model.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 短信发送记录实体
|
||||
* @author system
|
||||
*/
|
||||
@Data
|
||||
@TableName("sms_send_log")
|
||||
public class SmsSendLog implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 主键ID
|
||||
*/
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* 手机号
|
||||
*/
|
||||
private String phone;
|
||||
|
||||
/**
|
||||
* 短信模板ID
|
||||
*/
|
||||
private String templateId;
|
||||
|
||||
/**
|
||||
* 模板参数(JSON格式)
|
||||
*/
|
||||
private String templateParams;
|
||||
|
||||
/**
|
||||
* 短信内容
|
||||
*/
|
||||
private String content;
|
||||
|
||||
/**
|
||||
* 发送状态: 0-失败, 1-成功, 2-发送中
|
||||
*/
|
||||
private Integer status;
|
||||
|
||||
/**
|
||||
* 服务商: TENCENT, ALIYUN
|
||||
*/
|
||||
private String provider;
|
||||
|
||||
/**
|
||||
* 服务商返回的请求ID
|
||||
*/
|
||||
private String requestId;
|
||||
|
||||
/**
|
||||
* 服务商返回的状态码
|
||||
*/
|
||||
private String responseCode;
|
||||
|
||||
/**
|
||||
* 服务商返回的消息
|
||||
*/
|
||||
private String responseMessage;
|
||||
|
||||
/**
|
||||
* 错误信息
|
||||
*/
|
||||
private String errorMessage;
|
||||
|
||||
/**
|
||||
* 租户ID
|
||||
*/
|
||||
private String tenantId;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
private Date createTime;
|
||||
|
||||
/**
|
||||
* 更新时间
|
||||
*/
|
||||
private Date updateTime;
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.central.msg.service;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.central.msg.model.entity.SmsSendLog;
|
||||
import com.central.sms.enums.SmsProviderType;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 消息中心短信服务接口
|
||||
* @author system
|
||||
*/
|
||||
public interface MsgSmsService {
|
||||
|
||||
/**
|
||||
* 发送短信(使用默认服务商)
|
||||
* @param phone 手机号
|
||||
* @param templateId 模板ID
|
||||
* @param params 模板参数
|
||||
* @return 是否发送成功
|
||||
*/
|
||||
boolean sendSms(String phone, String templateId, Map<String, String> params);
|
||||
|
||||
/**
|
||||
* 发送短信(指定服务商)
|
||||
* @param phone 手机号
|
||||
* @param templateId 模板ID
|
||||
* @param params 模板参数
|
||||
* @param provider 服务商类型
|
||||
* @return 是否发送成功
|
||||
*/
|
||||
boolean sendSms(String phone, String templateId, Map<String, String> params, SmsProviderType provider);
|
||||
|
||||
/**
|
||||
* 发送阿里云短信
|
||||
* @param phone 手机号
|
||||
* @param templateId 模板ID
|
||||
* @param params 模板参数
|
||||
* @return 是否发送成功
|
||||
*/
|
||||
boolean sendAliyunSms(String phone, String templateId, Map<String, String> params);
|
||||
|
||||
/**
|
||||
* 发送腾讯云短信
|
||||
* @param phone 手机号
|
||||
* @param templateId 模板ID
|
||||
* @param params 模板参数
|
||||
* @return 是否发送成功
|
||||
*/
|
||||
boolean sendTencentSms(String phone, String templateId, Map<String, String> params);
|
||||
|
||||
/**
|
||||
* 发送验证码短信(使用默认服务商)
|
||||
* @param phone 手机号
|
||||
* @param code 验证码
|
||||
* @return 是否发送成功
|
||||
*/
|
||||
boolean sendVerifyCode(String phone, String code);
|
||||
|
||||
/**
|
||||
* 发送验证码短信(指定服务商)
|
||||
* @param phone 手机号
|
||||
* @param code 验证码
|
||||
* @param provider 服务商类型
|
||||
* @return 是否发送成功
|
||||
*/
|
||||
boolean sendVerifyCode(String phone, String code, SmsProviderType provider);
|
||||
|
||||
/**
|
||||
* 发送阿里云验证码
|
||||
* @param phone 手机号
|
||||
* @param code 验证码
|
||||
* @return 是否发送成功
|
||||
*/
|
||||
boolean sendAliyunVerifyCode(String phone, String code);
|
||||
|
||||
/**
|
||||
* 发送腾讯云验证码
|
||||
* @param phone 手机号
|
||||
* @param code 验证码
|
||||
* @return 是否发送成功
|
||||
*/
|
||||
boolean sendTencentVerifyCode(String phone, String code);
|
||||
|
||||
/**
|
||||
* 分页查询短信发送记录
|
||||
* @param page 当前页
|
||||
* @param size 每页大小
|
||||
* @param phone 手机号(可选)
|
||||
* @param status 状态(可选)
|
||||
* @return 分页数据
|
||||
*/
|
||||
Page<SmsSendLog> querySmsSendLog(int page, int size, String phone, Integer status);
|
||||
}
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
package com.central.msg.service.impl;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.central.msg.mapper.SmsSendLogMapper;
|
||||
import com.central.msg.model.entity.SmsSendLog;
|
||||
import com.central.msg.service.MsgSmsService;
|
||||
import com.central.sms.config.SmsProperties;
|
||||
import com.central.sms.enums.SmsProviderType;
|
||||
import com.central.sms.service.ISmsService;
|
||||
import com.central.sms.service.impl.AliyunSmsService;
|
||||
import com.central.sms.service.impl.TencentSmsService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 消息中心短信服务实现类
|
||||
* @author system
|
||||
*/
|
||||
@Service
|
||||
public class MsgSmsServiceImpl implements MsgSmsService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MsgSmsServiceImpl.class);
|
||||
|
||||
@Autowired
|
||||
private AliyunSmsService aliyunSmsService;
|
||||
|
||||
@Autowired
|
||||
private TencentSmsService tencentSmsService;
|
||||
|
||||
@Autowired
|
||||
private SmsSendLogMapper smsSendLogMapper;
|
||||
|
||||
@Autowired
|
||||
private SmsProperties smsProperties;
|
||||
|
||||
@Value("${sms.save-log:true}")
|
||||
private boolean saveLog;
|
||||
|
||||
@Override
|
||||
public boolean sendSms(String phone, String templateId, Map<String, String> params) {
|
||||
return sendSms(phone, templateId, params, smsProperties.getProvider());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean sendSms(String phone, String templateId, Map<String, String> params, SmsProviderType provider) {
|
||||
SmsSendLog log = new SmsSendLog();
|
||||
log.setPhone(phone);
|
||||
log.setTemplateId(templateId);
|
||||
log.setTemplateParams(params != null ? JSON.toJSONString(params) : null);
|
||||
log.setProvider(provider.name());
|
||||
log.setCreateTime(new Date());
|
||||
log.setUpdateTime(new Date());
|
||||
|
||||
try {
|
||||
logger.info("开始发送短信: phone={}, templateId={}, params={}, provider={}",
|
||||
phone, templateId, params, provider);
|
||||
log.setStatus(2); // 发送中
|
||||
|
||||
ISmsService smsService = getSmsService(provider);
|
||||
boolean result = smsService.sendSms(phone, templateId, params);
|
||||
|
||||
if (result) {
|
||||
logger.info("短信发送成功: phone={}, templateId={}, provider={}", phone, templateId, provider);
|
||||
log.setStatus(1); // 成功
|
||||
log.setResponseCode("Ok");
|
||||
log.setResponseMessage("发送成功");
|
||||
} else {
|
||||
logger.warn("短信发送失败: phone={}, templateId={}, provider={}", phone, templateId, provider);
|
||||
log.setStatus(0); // 失败
|
||||
log.setResponseCode("Failed");
|
||||
log.setResponseMessage("发送失败");
|
||||
}
|
||||
|
||||
// 保存发送记录
|
||||
if (saveLog) {
|
||||
saveSendLog(log);
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (Exception e) {
|
||||
logger.error("短信发送异常: phone={}, templateId={}, provider={}, error={}",
|
||||
phone, templateId, provider, e.getMessage(), e);
|
||||
log.setStatus(0); // 失败
|
||||
log.setErrorMessage(e.getMessage());
|
||||
log.setResponseMessage("发送异常: " + e.getMessage());
|
||||
|
||||
// 保存发送记录
|
||||
if (saveLog) {
|
||||
saveSendLog(log);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean sendAliyunSms(String phone, String templateId, Map<String, String> params) {
|
||||
return sendSms(phone, templateId, params, SmsProviderType.ALIYUN);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean sendTencentSms(String phone, String templateId, Map<String, String> params) {
|
||||
return sendSms(phone, templateId, params, SmsProviderType.TENCENT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean sendVerifyCode(String phone, String code) {
|
||||
return sendVerifyCode(phone, code, smsProperties.getProvider());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean sendVerifyCode(String phone, String code, SmsProviderType provider) {
|
||||
String templateId = getVerifyCodeTemplateId(provider);
|
||||
if (templateId == null || templateId.isEmpty()) {
|
||||
logger.error("{}验证码模板ID未配置,无法发送验证码短信", provider.name());
|
||||
return false;
|
||||
}
|
||||
|
||||
Map<String, String> params = new HashMap<>();
|
||||
params.put("code", code);
|
||||
params.put("time", "5"); // 默认5分钟有效期
|
||||
|
||||
return sendSms(phone, templateId, params, provider);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean sendAliyunVerifyCode(String phone, String code) {
|
||||
return sendVerifyCode(phone, code, SmsProviderType.ALIYUN);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean sendTencentVerifyCode(String phone, String code) {
|
||||
return sendVerifyCode(phone, code, SmsProviderType.TENCENT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Page<SmsSendLog> querySmsSendLog(int page, int size, String phone, Integer status) {
|
||||
Page<SmsSendLog> pageParam = new Page<>(page, size);
|
||||
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<SmsSendLog> wrapper =
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
||||
|
||||
// 手机号模糊查询
|
||||
if (phone != null && !phone.isEmpty()) {
|
||||
wrapper.like(SmsSendLog::getPhone, phone);
|
||||
}
|
||||
|
||||
// 状态查询
|
||||
if (status != null) {
|
||||
wrapper.eq(SmsSendLog::getStatus, status);
|
||||
}
|
||||
|
||||
// 按创建时间倒序
|
||||
wrapper.orderByDesc(SmsSendLog::getCreateTime);
|
||||
|
||||
return smsSendLogMapper.selectPage(pageParam, wrapper);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据服务商类型获取短信服务实例
|
||||
*/
|
||||
private ISmsService getSmsService(SmsProviderType provider) {
|
||||
switch (provider) {
|
||||
case ALIYUN:
|
||||
return aliyunSmsService;
|
||||
case TENCENT:
|
||||
default:
|
||||
return tencentSmsService;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取验证码模板ID
|
||||
*/
|
||||
private String getVerifyCodeTemplateId(SmsProviderType provider) {
|
||||
switch (provider) {
|
||||
case ALIYUN:
|
||||
return smsProperties.getAliyun().getVerifyCodeTemplateId();
|
||||
case TENCENT:
|
||||
return smsProperties.getTencent().getVerifyCodeTemplateId();
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存短信发送记录
|
||||
*/
|
||||
private void saveSendLog(SmsSendLog log) {
|
||||
try {
|
||||
smsSendLogMapper.insert(log);
|
||||
} catch (Exception e) {
|
||||
logger.error("保存短信发送记录失败: {}", e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
# 消息中心配置文件
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:mysql://${zlt.datasource.ip}/msg-center?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
|
||||
username: ${zlt.datasource.username}
|
||||
password: ${zlt.datasource.password}
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
|
||||
mybatis-plus:
|
||||
mapper-locations: classpath:/mapper/*Mapper.xml
|
||||
type-aliases-package: com.central.msg.model.entity
|
||||
global-config:
|
||||
db-config:
|
||||
id-type: auto
|
||||
|
||||
springdoc:
|
||||
group-configs:
|
||||
- group: 'default'
|
||||
paths-to-match: '/**'
|
||||
packages-to-scan: com.central.msg.controller
|
||||
|
||||
knife4j:
|
||||
enable: true
|
||||
setting:
|
||||
swagger-model-name: 消息中心接口文档
|
||||
|
||||
# 短信服务配置
|
||||
sms:
|
||||
# 短信服务提供商: TENCENT(腾讯云) 或 ALIYUN(阿里云)
|
||||
# 默认提供商,用于未指定提供商的接口
|
||||
provider: ${SMS_PROVIDER:TENCENT}
|
||||
|
||||
# 腾讯云短信配置
|
||||
tencent:
|
||||
# 腾讯云短信应用ID (在腾讯云短信控制台获取)
|
||||
app-id: ${SMS_TENCENT_APP_ID:}
|
||||
# 腾讯云SecretId (在腾讯云控制台获取)
|
||||
secret-id: ${SMS_TENCENT_SECRET_ID:}
|
||||
# 腾讯云SecretKey (在腾讯云控制台获取)
|
||||
secret-key: ${SMS_TENCENT_SECRET_KEY:}
|
||||
# 短信签名 (在腾讯云短信控制台配置)
|
||||
sign-name: ${SMS_TENCENT_SIGN_NAME:}
|
||||
# 验证码模板ID
|
||||
verify-code-template-id: ${SMS_TENCENT_VERIFY_CODE_TEMPLATE_ID:}
|
||||
|
||||
# 阿里云短信配置
|
||||
aliyun:
|
||||
# 阿里云AccessKeyId (在阿里云控制台获取)
|
||||
access-key-id: ${SMS_ALIYUN_ACCESS_KEY_ID:}
|
||||
# 阿里云AccessKeySecret (在阿里云控制台获取)
|
||||
access-key-secret: ${SMS_ALIYUN_ACCESS_KEY_SECRET:}
|
||||
# 短信签名 (在阿里云短信控制台配置)
|
||||
sign-name: ${SMS_ALIYUN_SIGN_NAME:}
|
||||
# 验证码模板ID
|
||||
verify-code-template-id: ${SMS_ALIYUN_VERIFY_CODE_TEMPLATE_ID:}
|
||||
|
||||
# 是否保存短信发送记录到数据库
|
||||
save-log: ${SMS_SAVE_LOG:true}
|
||||
|
||||
# 多租户配置
|
||||
zlt:
|
||||
tenant:
|
||||
enable: true
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
spring:
|
||||
application:
|
||||
name: msg-center
|
||||
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.central.msg.mapper.SmsSendLogMapper">
|
||||
|
||||
<resultMap id="BaseResultMap" type="com.central.msg.model.entity.SmsSendLog">
|
||||
<id column="id" property="id"/>
|
||||
<result column="phone" property="phone"/>
|
||||
<result column="template_id" property="templateId"/>
|
||||
<result column="template_params" property="templateParams"/>
|
||||
<result column="content" property="content"/>
|
||||
<result column="status" property="status"/>
|
||||
<result column="provider" property="provider"/>
|
||||
<result column="request_id" property="requestId"/>
|
||||
<result column="response_code" property="responseCode"/>
|
||||
<result column="response_message" property="responseMessage"/>
|
||||
<result column="error_message" property="errorMessage"/>
|
||||
<result column="tenant_id" property="tenantId"/>
|
||||
<result column="create_time" property="createTime"/>
|
||||
<result column="update_time" property="updateTime"/>
|
||||
</resultMap>
|
||||
|
||||
</mapper>
|
||||
@@ -22,5 +22,7 @@
|
||||
<module>order-center</module>
|
||||
<!-- 优惠券中心 -->
|
||||
<module>coupon-center</module>
|
||||
<!-- 消息中心 -->
|
||||
<module>msg-center</module>
|
||||
</modules>
|
||||
</project>
|
||||
|
||||
Reference in New Issue
Block a user