杂务:将消息中心拆分为独立仓库
This commit is contained in:
@@ -1,2 +0,0 @@
|
||||
/mvnw text eol=lf
|
||||
*.cmd text eol=crlf
|
||||
@@ -1,33 +0,0 @@
|
||||
HELP.md
|
||||
target/
|
||||
.mvn/wrapper/maven-wrapper.jar
|
||||
!**/src/main/**/target/
|
||||
!**/src/test/**/target/
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
build/
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
@@ -1,3 +0,0 @@
|
||||
wrapperVersion=3.3.4
|
||||
distributionType=only-script
|
||||
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.12/apache-maven-3.9.12-bin.zip
|
||||
@@ -1,321 +0,0 @@
|
||||
# MessageHub 消息队列示例消息体
|
||||
|
||||
## 短信消息示例
|
||||
|
||||
### 1. 普通短信消息(无模板)
|
||||
|
||||
```json
|
||||
{
|
||||
"receiver": "13800138000",
|
||||
"channelType": "SMS",
|
||||
"msgType": "NOTIFICATION",
|
||||
"templateCode": "",
|
||||
"templateParams": {
|
||||
"message": "您的订单已发货,请注意查收"
|
||||
},
|
||||
"sourceSystem": "OrderSystem",
|
||||
"uniqueId": "msg_20250211_001"
|
||||
}
|
||||
```
|
||||
|
||||
### 2. 验证码短信(使用模板)
|
||||
|
||||
```json
|
||||
{
|
||||
"receiver": "13800138000",
|
||||
"channelType": "SMS",
|
||||
"msgType": "VERIFICATION",
|
||||
"templateCode": "VERIFY_CODE",
|
||||
"templateParams": {
|
||||
"code": "123456",
|
||||
"minutes": "10"
|
||||
},
|
||||
"sourceSystem": "UserCenter",
|
||||
"uniqueId": "msg_20250211_002"
|
||||
}
|
||||
```
|
||||
|
||||
### 3. 通知短信(使用模板)
|
||||
|
||||
```json
|
||||
{
|
||||
"receiver": "13800138000",
|
||||
"channelType": "SMS",
|
||||
"msgType": "NOTIFICATION",
|
||||
"templateCode": "ORDER_NOTIFY",
|
||||
"templateParams": {
|
||||
"orderNo": "20250211001",
|
||||
"productName": "iPhone 15 Pro",
|
||||
"amount": "8999.00"
|
||||
},
|
||||
"sourceSystem": "OrderSystem",
|
||||
"uniqueId": "msg_20250211_003"
|
||||
}
|
||||
```
|
||||
|
||||
### 4. 营销短信(使用模板)
|
||||
|
||||
```json
|
||||
{
|
||||
"receiver": "13800138000",
|
||||
"channelType": "SMS",
|
||||
"msgType": "PROMOTION",
|
||||
"templateCode": "PROMOTION_NOTIFY",
|
||||
"templateParams": {
|
||||
"productName": "春季大促",
|
||||
"discount": "8折",
|
||||
"endDate": "2025-02-20"
|
||||
},
|
||||
"sourceSystem": "MarketingSystem",
|
||||
"uniqueId": "msg_20250211_004"
|
||||
}
|
||||
```
|
||||
|
||||
### 5. 告警短信(使用模板)
|
||||
|
||||
```json
|
||||
{
|
||||
"receiver": "13800138000",
|
||||
"channelType": "SMS",
|
||||
"msgType": "ALERT",
|
||||
"templateCode": "SYSTEM_ALERT",
|
||||
"templateParams": {
|
||||
"serverName": "web-server-01",
|
||||
"alertType": "CPU使用率过高",
|
||||
"value": "95%"
|
||||
},
|
||||
"sourceSystem": "MonitorSystem",
|
||||
"uniqueId": "msg_20250211_005"
|
||||
}
|
||||
```
|
||||
|
||||
## 邮件消息示例
|
||||
|
||||
### 1. 普通邮件消息(无模板)
|
||||
|
||||
```json
|
||||
{
|
||||
"receiver": "user@example.com",
|
||||
"channelType": "EMAIL",
|
||||
"msgType": "NOTIFICATION",
|
||||
"templateCode": "",
|
||||
"templateParams": {
|
||||
"message": "您的账户已成功注册,欢迎加入我们!"
|
||||
},
|
||||
"sourceSystem": "UserCenter",
|
||||
"uniqueId": "msg_20250211_006"
|
||||
}
|
||||
```
|
||||
|
||||
### 2. 验证码邮件(使用模板)
|
||||
|
||||
```json
|
||||
{
|
||||
"receiver": "user@example.com",
|
||||
"channelType": "EMAIL",
|
||||
"msgType": "VERIFICATION",
|
||||
"templateCode": "EMAIL_VERIFY",
|
||||
"templateParams": {
|
||||
"code": "123456",
|
||||
"minutes": "10"
|
||||
},
|
||||
"sourceSystem": "UserCenter",
|
||||
"uniqueId": "msg_20250211_007"
|
||||
}
|
||||
```
|
||||
|
||||
### 3. 订单通知邮件(使用模板)
|
||||
|
||||
```json
|
||||
{
|
||||
"receiver": "user@example.com",
|
||||
"channelType": "EMAIL",
|
||||
"msgType": "NOTIFICATION",
|
||||
"templateCode": "ORDER_EMAIL",
|
||||
"templateParams": {
|
||||
"orderNo": "20250211001",
|
||||
"productName": "iPhone 15 Pro",
|
||||
"amount": "8999.00",
|
||||
"address": "北京市朝阳区xxx街道xxx号"
|
||||
},
|
||||
"sourceSystem": "OrderSystem",
|
||||
"uniqueId": "msg_20250211_008"
|
||||
}
|
||||
```
|
||||
|
||||
### 4. 营销邮件(使用模板)
|
||||
|
||||
```json
|
||||
{
|
||||
"receiver": "user@example.com",
|
||||
"channelType": "EMAIL",
|
||||
"msgType": "PROMOTION",
|
||||
"templateCode": "PROMOTION_EMAIL",
|
||||
"templateParams": {
|
||||
"userName": "张三",
|
||||
"productName": "春季大促",
|
||||
"discount": "8折",
|
||||
"link": "https://example.com/promotion"
|
||||
},
|
||||
"sourceSystem": "MarketingSystem",
|
||||
"uniqueId": "msg_20250211_009"
|
||||
}
|
||||
```
|
||||
|
||||
### 5. 告警邮件(使用模板)
|
||||
|
||||
```json
|
||||
{
|
||||
"receiver": "admin@example.com",
|
||||
"channelType": "EMAIL",
|
||||
"msgType": "ALERT",
|
||||
"templateCode": "SYSTEM_ALERT_EMAIL",
|
||||
"templateParams": {
|
||||
"serverName": "web-server-01",
|
||||
"alertType": "CPU使用率过高",
|
||||
"value": "95%",
|
||||
"time": "2025-02-11 16:30:00"
|
||||
},
|
||||
"sourceSystem": "MonitorSystem",
|
||||
"uniqueId": "msg_20250211_010"
|
||||
}
|
||||
```
|
||||
|
||||
## 字段说明
|
||||
|
||||
| 字段名 | 类型 | 必填 | 说明 |
|
||||
|--------|------|------|------|
|
||||
| receiver | String | 是 | 接收者,短信为手机号,邮件为邮箱地址 |
|
||||
| channelType | String | 是 | 渠道类型:SMS(短信)、EMAIL(邮件)、PUSH(推送)、WECHAT(微信) |
|
||||
| msgType | String | 是 | 消息类型:NOTIFICATION(通知)、VERIFICATION(验证码)、PROMOTION(营销)、ALERT(告警) |
|
||||
| templateCode | String | 否 | 模板编码,如果使用模板消息则必填 |
|
||||
| templateParams | Map | 否 | 模板参数,key-value形式,用于模板占位符替换 |
|
||||
| sourceSystem | String | 是 | 来源系统,标识消息来源 |
|
||||
| uniqueId | String | 是 | 唯一标识,用于消息去重和追踪 |
|
||||
|
||||
## 消息类型说明
|
||||
|
||||
### channelType(渠道类型)
|
||||
- **SMS**: 短信消息
|
||||
- **EMAIL**: 邮件消息
|
||||
- **PUSH**: 推送消息
|
||||
- **WECHAT**: 微信消息
|
||||
|
||||
### msgType(消息类型)
|
||||
- **NOTIFICATION**: 通知类消息,如订单通知、系统通知等
|
||||
- **VERIFICATION**: 验证码类消息,如注册验证码、登录验证码等
|
||||
- **PROMOTION**: 营销类消息,如促销活动、产品推荐等
|
||||
- **ALERT**: 告警类消息,如系统告警、异常通知等
|
||||
|
||||
## 模板占位符说明
|
||||
|
||||
模板消息使用 `${key}` 格式的占位符,例如:
|
||||
|
||||
模板内容:
|
||||
```
|
||||
您的验证码是${code},${minutes}分钟内有效,如非本人操作请忽略。
|
||||
```
|
||||
|
||||
对应的 templateParams:
|
||||
```json
|
||||
{
|
||||
"code": "123456",
|
||||
"minutes": "10"
|
||||
}
|
||||
```
|
||||
|
||||
替换后的内容:
|
||||
```
|
||||
您的验证码是123456,10分钟内有效,如非本人操作请忽略。
|
||||
```
|
||||
|
||||
## 使用方式
|
||||
|
||||
### 使用Java客户端发送消息
|
||||
|
||||
参考 `MessageProducerTest.java` 中的测试方法:
|
||||
|
||||
```java
|
||||
@Autowired
|
||||
private MessageProducerService messageProducerService;
|
||||
|
||||
@Test
|
||||
public void testSendSmsMessage() {
|
||||
MessageDTO messageDTO = new MessageDTO();
|
||||
messageDTO.setReceiver("13800138000");
|
||||
messageDTO.setChannelType("SMS");
|
||||
messageDTO.setMsgType("VERIFICATION");
|
||||
messageDTO.setSourceSystem("MessageHub");
|
||||
|
||||
messageProducerService.sendSmsMessage(messageDTO);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSendEmailMessage() {
|
||||
MessageDTO messageDTO = new MessageDTO();
|
||||
messageDTO.setReceiver("test@example.com");
|
||||
messageDTO.setChannelType("EMAIL");
|
||||
messageDTO.setMsgType("NOTIFICATION");
|
||||
messageDTO.setSourceSystem("MessageHub");
|
||||
|
||||
Map<String, Object> params = new HashMap<>();
|
||||
params.put("message", "这是一封测试邮件");
|
||||
messageDTO.setTemplateParams(params);
|
||||
|
||||
messageProducerService.sendEmailMessage(messageDTO);
|
||||
}
|
||||
```
|
||||
|
||||
### 在业务代码中使用
|
||||
|
||||
```java
|
||||
@Service
|
||||
public class OrderService {
|
||||
|
||||
@Autowired
|
||||
private MessageProducerService messageProducerService;
|
||||
|
||||
public void sendOrderNotification(String phone, String orderNo) {
|
||||
MessageDTO messageDTO = new MessageDTO();
|
||||
messageDTO.setReceiver(phone);
|
||||
messageDTO.setChannelType("SMS");
|
||||
messageDTO.setMsgType("NOTIFICATION");
|
||||
messageDTO.setTemplateCode("ORDER_NOTIFY");
|
||||
messageDTO.setSourceSystem("OrderSystem");
|
||||
|
||||
Map<String, Object> params = new HashMap<>();
|
||||
params.put("orderNo", orderNo);
|
||||
params.put("productName", "iPhone 15 Pro");
|
||||
params.put("amount", "8999.00");
|
||||
messageDTO.setTemplateParams(params);
|
||||
|
||||
messageProducerService.sendSmsMessage(messageDTO);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 队列配置
|
||||
|
||||
### 统一消息交换机
|
||||
- **交换机名称**: messageExchange
|
||||
- **交换机类型**: Topic
|
||||
|
||||
### 短信队列
|
||||
- **队列名称**: smsQueue
|
||||
- **路由键模式**: sms.# (匹配所有以sms.开头的routing key)
|
||||
- **监听器**: SmsQueueListener
|
||||
- **支持的routing key**:
|
||||
- sms.verification(验证码短信)
|
||||
- sms.notification(通知短信)
|
||||
- sms.promotion(营销短信)
|
||||
- sms.alert(告警短信)
|
||||
|
||||
### 邮件队列
|
||||
- **队列名称**: emailQueue
|
||||
- **路由键模式**: email.# (匹配所有以email.开头的routing key)
|
||||
- **监听器**: EmailQueueListener
|
||||
- **支持的routing key**:
|
||||
- email.verification(验证码邮件)
|
||||
- email.notification(通知邮件)
|
||||
- email.promotion(营销邮件)
|
||||
- email.alert(告警邮件)
|
||||
@@ -1,631 +0,0 @@
|
||||
# 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 开发团队
|
||||
@@ -1,157 +0,0 @@
|
||||
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.7.18</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>com.xiaowang</groupId>
|
||||
<artifactId>MessageHub</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>MessageHub</name>
|
||||
<description>MessageHub - 消息中心微服务,提供消息队列、数据库操作等服务</description>
|
||||
|
||||
<url/>
|
||||
<licenses>
|
||||
<license/>
|
||||
</licenses>
|
||||
<developers>
|
||||
<developer/>
|
||||
</developers>
|
||||
<scm>
|
||||
<connection/>
|
||||
<developerConnection/>
|
||||
<tag/>
|
||||
<url/>
|
||||
</scm>
|
||||
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
<spring-cloud.version>2021.0.8</spring-cloud.version>
|
||||
<spring-cloud-alibaba.version>2021.0.5.0</spring-cloud-alibaba.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-logging</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-log4j2</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-amqp</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-logging</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-bootstrap</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-jdbc</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-boot-starter</artifactId>
|
||||
<version>3.5.3.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>druid-spring-boot-starter</artifactId>
|
||||
<version>1.2.23</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-mail</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-dependencies</artifactId>
|
||||
<version>${spring-cloud.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
|
||||
<version>${spring-cloud-alibaba.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<build>
|
||||
<finalName>MessageHub-0.0.1-SNAPSHOT</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
@@ -1,63 +0,0 @@
|
||||
package com.xiaowang.messagehub;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
/**
|
||||
* MessageHub application entry.
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@SpringBootApplication
|
||||
public class MessageHubApplication {
|
||||
|
||||
private static final String APP_RUNTIME_DIR = "MessageHub";
|
||||
|
||||
public static void main(String[] args) {
|
||||
configureNacosRuntimePaths();
|
||||
SpringApplication.run(MessageHubApplication.class, args);
|
||||
}
|
||||
|
||||
private static void configureNacosRuntimePaths() {
|
||||
configurePathIfAbsent("JM.LOG.PATH", "logs", true);
|
||||
configurePathIfAbsent("JM.SNAPSHOT.PATH", "nacos-snapshot", false);
|
||||
}
|
||||
|
||||
private static String resolveRuntimePath(String child, boolean includeNacosDir) {
|
||||
Path path = resolveBaseRuntimePath().resolve(child);
|
||||
try {
|
||||
Files.createDirectories(path);
|
||||
if (includeNacosDir) {
|
||||
Files.createDirectories(path.resolve("nacos"));
|
||||
}
|
||||
} catch (IOException exception) {
|
||||
throw new IllegalStateException("Failed to prepare runtime directory: " + path, exception);
|
||||
}
|
||||
return path.toAbsolutePath().toString();
|
||||
}
|
||||
|
||||
private static Path resolveBaseRuntimePath() {
|
||||
String localAppData = System.getenv("LOCALAPPDATA");
|
||||
if (hasText(localAppData)) {
|
||||
return Paths.get(localAppData, APP_RUNTIME_DIR);
|
||||
}
|
||||
return Paths.get(System.getProperty("user.home"), ".messagehub");
|
||||
}
|
||||
|
||||
private static void configurePathIfAbsent(String key, String child, boolean includeNacosDir) {
|
||||
String currentValue = System.getProperty(key);
|
||||
if (!hasText(currentValue)) {
|
||||
System.setProperty(key, resolveRuntimePath(child, includeNacosDir));
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean hasText(String value) {
|
||||
return value != null && !value.trim().isEmpty();
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package com.xiaowang.messagehub.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
|
||||
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class JacksonConfig {
|
||||
|
||||
@Bean
|
||||
public Jackson2ObjectMapperBuilderCustomizer longToStringJacksonCustomizer() {
|
||||
return builder -> {
|
||||
// 消息中心同样可能返回雪花 ID,统一转字符串避免外围系统前端侧精度问题。
|
||||
builder.serializerByType(Long.class, ToStringSerializer.instance);
|
||||
builder.serializerByType(Long.TYPE, ToStringSerializer.instance);
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package com.xiaowang.messagehub.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "messagehub.channel")
|
||||
public class MessageChannelProperties {
|
||||
|
||||
private Security security = new Security();
|
||||
|
||||
private Mock mock = new Mock();
|
||||
|
||||
private Retry retry = new Retry();
|
||||
|
||||
@Data
|
||||
public static class Security {
|
||||
private String encryptionKey = "MessageHub-Change-Me-2026";
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Mock {
|
||||
private boolean autoBootstrap = true;
|
||||
private List<String> profiles = new ArrayList<>(List.of("dev", "local", "test"));
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Retry {
|
||||
private int maxAttempts = 3;
|
||||
private long initialDelayMillis = 1000L;
|
||||
private double multiplier = 2.0D;
|
||||
private long maxDelayMillis = 30000L;
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
package com.xiaowang.messagehub.config;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.DbType;
|
||||
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
|
||||
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
|
||||
import com.xiaowang.messagehub.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* MyBatis-Plus配置类
|
||||
* 用于配置MyBatis-Plus的拦截器,实现分页、乐观锁和防止全表更新等功能
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@Configuration // 标识该类为配置类,Spring会扫描并加载其中的配置
|
||||
@MapperScan("com.xiaowang.messagehub.mapper") // 扫描指定包下的Mapper接口,自动注册为Spring Bean
|
||||
public class MyBatisPlusConfig {
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 配置MyBatis-Plus的拦截器
|
||||
* 用于添加分页、乐观锁和防止全表更新等功能
|
||||
*
|
||||
* @return MybatisPlusInterceptor 配置好的拦截器
|
||||
*/
|
||||
@Bean // 将该方法返回的对象注册为Spring Bean
|
||||
public MybatisPlusInterceptor mybatisPlusInterceptor() {
|
||||
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); // 创建MyBatis-Plus拦截器实例
|
||||
|
||||
// 添加分页插件,设置数据库类型为MySQL
|
||||
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
|
||||
|
||||
// 添加乐观锁插件,实现乐观锁功能
|
||||
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
|
||||
|
||||
// 添加防止全表更新插件,防止恶意或误操作导致的性能问题
|
||||
interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
|
||||
|
||||
return interceptor; // 返回配置好的拦截器
|
||||
}
|
||||
|
||||
@Bean
|
||||
public IdentifierGenerator identifierGenerator(TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator) {
|
||||
return new IdentifierGenerator() {
|
||||
@Override
|
||||
public Number nextId(Object entity) {
|
||||
return snowflakeIdGenerator.nextId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String nextUUID(Object entity) {
|
||||
return snowflakeIdGenerator.nextIdString();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package com.xiaowang.messagehub.config;
|
||||
|
||||
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
|
||||
import org.apache.ibatis.reflection.MetaObject;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* MyBatis-Plus元数据处理器
|
||||
* 该类用于自动填充实体类的公共字段,如创建时间、更新时间等
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@Component // 将此类标记为Spring组件,使其成为Spring容器中的一个Bean
|
||||
public class MyMetaObjectHandler implements MetaObjectHandler { // 实现MyBatis-Plus的MetaObjectHandler接口,用于自动填充功能
|
||||
|
||||
/**
|
||||
* 插入数据时的填充策略
|
||||
* @param metaObject 元数据对象,可以获取和设置到对象的值
|
||||
*/
|
||||
@Override
|
||||
public void insertFill(MetaObject metaObject) {
|
||||
// 在插入数据时,自动填充createTime字段为当前时间
|
||||
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
|
||||
// 在插入数据时,自动填充updateTime字段为当前时间
|
||||
this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新数据时的填充策略
|
||||
* @param metaObject 元数据对象,可以获取和设置到对象的值
|
||||
*/
|
||||
@Override
|
||||
public void updateFill(MetaObject metaObject) {
|
||||
// 在更新数据时,自动填充updateTime字段为当前时间
|
||||
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
|
||||
}
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
package com.xiaowang.messagehub.config;
|
||||
|
||||
import org.springframework.amqp.core.AcknowledgeMode;
|
||||
import org.springframework.amqp.core.Binding;
|
||||
import org.springframework.amqp.core.BindingBuilder;
|
||||
import org.springframework.amqp.core.DirectExchange;
|
||||
import org.springframework.amqp.core.Queue;
|
||||
import org.springframework.amqp.core.QueueBuilder;
|
||||
import org.springframework.amqp.core.TopicExchange;
|
||||
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
|
||||
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
|
||||
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class RabbitMQConfig {
|
||||
|
||||
public static final String SMS_QUEUE = "smsQueue";
|
||||
public static final String EMAIL_QUEUE = "emailQueue";
|
||||
public static final String QQ_QUEUE = "qqQueue";
|
||||
public static final String INGRESS_QUEUE = "messagehub.ingress.queue";
|
||||
|
||||
public static final String MESSAGE_EXCHANGE = "messageExchange";
|
||||
public static final String INGRESS_EXCHANGE = "messagehub.ingress.exchange";
|
||||
public static final String DEAD_LETTER_EXCHANGE = "messageDeadLetterExchange";
|
||||
|
||||
public static final String SMS_DEAD_LETTER_QUEUE = "smsDeadLetterQueue";
|
||||
public static final String EMAIL_DEAD_LETTER_QUEUE = "emailDeadLetterQueue";
|
||||
public static final String QQ_DEAD_LETTER_QUEUE = "qqDeadLetterQueue";
|
||||
public static final String INGRESS_DEAD_LETTER_QUEUE = "messagehubIngressDeadLetterQueue";
|
||||
|
||||
public static final String SMS_ROUTING_KEY = "sms.#";
|
||||
public static final String EMAIL_ROUTING_KEY = "email.#";
|
||||
public static final String QQ_ROUTING_KEY = "qq.#";
|
||||
public static final String INGRESS_ROUTING_KEY = "message.send";
|
||||
|
||||
public static final String SMS_DEAD_LETTER_ROUTING_KEY = "dead.sms";
|
||||
public static final String EMAIL_DEAD_LETTER_ROUTING_KEY = "dead.email";
|
||||
public static final String QQ_DEAD_LETTER_ROUTING_KEY = "dead.qq";
|
||||
public static final String INGRESS_DEAD_LETTER_ROUTING_KEY = "dead.ingress";
|
||||
|
||||
@Bean
|
||||
public Queue smsQueue() {
|
||||
return QueueBuilder.durable(SMS_QUEUE).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue emailQueue() {
|
||||
return QueueBuilder.durable(EMAIL_QUEUE).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue qqQueue() {
|
||||
return QueueBuilder.durable(QQ_QUEUE).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue ingressQueue() {
|
||||
return QueueBuilder.durable(INGRESS_QUEUE).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public TopicExchange messageExchange() {
|
||||
return new TopicExchange(MESSAGE_EXCHANGE, true, false);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public TopicExchange ingressExchange() {
|
||||
return new TopicExchange(INGRESS_EXCHANGE, true, false);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DirectExchange deadLetterExchange() {
|
||||
return new DirectExchange(DEAD_LETTER_EXCHANGE, true, false);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue smsDeadLetterQueue() {
|
||||
return QueueBuilder.durable(SMS_DEAD_LETTER_QUEUE).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue emailDeadLetterQueue() {
|
||||
return QueueBuilder.durable(EMAIL_DEAD_LETTER_QUEUE).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue qqDeadLetterQueue() {
|
||||
return QueueBuilder.durable(QQ_DEAD_LETTER_QUEUE).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue ingressDeadLetterQueue() {
|
||||
return QueueBuilder.durable(INGRESS_DEAD_LETTER_QUEUE).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding smsBinding() {
|
||||
return BindingBuilder.bind(smsQueue()).to(messageExchange()).with(SMS_ROUTING_KEY);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding emailBinding() {
|
||||
return BindingBuilder.bind(emailQueue()).to(messageExchange()).with(EMAIL_ROUTING_KEY);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding qqBinding() {
|
||||
return BindingBuilder.bind(qqQueue()).to(messageExchange()).with(QQ_ROUTING_KEY);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding ingressBinding() {
|
||||
return BindingBuilder.bind(ingressQueue()).to(ingressExchange()).with(INGRESS_ROUTING_KEY);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding smsDeadLetterBinding() {
|
||||
return BindingBuilder.bind(smsDeadLetterQueue()).to(deadLetterExchange()).with(SMS_DEAD_LETTER_ROUTING_KEY);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding emailDeadLetterBinding() {
|
||||
return BindingBuilder.bind(emailDeadLetterQueue()).to(deadLetterExchange()).with(EMAIL_DEAD_LETTER_ROUTING_KEY);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding qqDeadLetterBinding() {
|
||||
return BindingBuilder.bind(qqDeadLetterQueue()).to(deadLetterExchange()).with(QQ_DEAD_LETTER_ROUTING_KEY);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding ingressDeadLetterBinding() {
|
||||
return BindingBuilder.bind(ingressDeadLetterQueue()).to(deadLetterExchange()).with(INGRESS_DEAD_LETTER_ROUTING_KEY);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SimpleRabbitListenerContainerFactory manualAckRabbitListenerContainerFactory(
|
||||
SimpleRabbitListenerContainerFactoryConfigurer configurer,
|
||||
ConnectionFactory connectionFactory
|
||||
) {
|
||||
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
|
||||
configurer.configure(factory, connectionFactory);
|
||||
factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
|
||||
return factory;
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package com.xiaowang.messagehub.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
|
||||
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
|
||||
|
||||
import javax.validation.Validator;
|
||||
|
||||
/**
|
||||
* 校验配置类
|
||||
* 用于配置Spring框架中的数据校验相关Bean
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@Configuration // 标记此类为配置类,用于定义Bean
|
||||
public class ValidationConfig {
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 创建Validator Bean
|
||||
* 用于提供JSR-303规范的校验功能
|
||||
*
|
||||
* @return Validator实例
|
||||
*/
|
||||
@Bean // 将此方法返回的对象注册为Spring容器中的Bean
|
||||
public Validator validator() {
|
||||
return new LocalValidatorFactoryBean();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 创建方法校验后置处理器
|
||||
* 用于在Spring方法调用时执行参数校验
|
||||
*
|
||||
* @return 配置好的MethodValidationPostProcessor实例
|
||||
*/
|
||||
@Bean // 将此方法返回的对象注册为Spring容器中的Bean
|
||||
public MethodValidationPostProcessor methodValidationPostProcessor() {
|
||||
// 创建方法校验后置处理器实例
|
||||
MethodValidationPostProcessor processor = new MethodValidationPostProcessor();
|
||||
// 设置校验器为上面定义的validator Bean
|
||||
processor.setValidator(validator());
|
||||
return processor;
|
||||
}
|
||||
}
|
||||
-47
@@ -1,47 +0,0 @@
|
||||
package com.xiaowang.messagehub.controller;
|
||||
|
||||
import com.xiaowang.messagehub.dto.admin.EmailAttachmentPolicyRequest;
|
||||
import com.xiaowang.messagehub.dto.admin.EmailAttachmentPolicyView;
|
||||
import com.xiaowang.messagehub.dto.admin.EmailAttachmentView;
|
||||
import com.xiaowang.messagehub.dto.common.ApiResponse;
|
||||
import com.xiaowang.messagehub.service.email.AttachmentStorageService;
|
||||
import com.xiaowang.messagehub.service.email.EmailAttachmentPolicyService;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
@Validated
|
||||
@RestController
|
||||
public class EmailAttachmentAdminController {
|
||||
|
||||
private final AttachmentStorageService attachmentStorageService;
|
||||
private final EmailAttachmentPolicyService policyService;
|
||||
|
||||
public EmailAttachmentAdminController(AttachmentStorageService attachmentStorageService,
|
||||
EmailAttachmentPolicyService policyService) {
|
||||
this.attachmentStorageService = attachmentStorageService;
|
||||
this.policyService = policyService;
|
||||
}
|
||||
|
||||
@PostMapping("/admin/api/email-attachments")
|
||||
public ApiResponse<EmailAttachmentView> uploadAttachment(@RequestParam("file") MultipartFile file) {
|
||||
return ApiResponse.success("附件上传成功", attachmentStorageService.upload(file));
|
||||
}
|
||||
|
||||
@GetMapping("/admin/api/email-attachment-policies")
|
||||
public ApiResponse<EmailAttachmentPolicyView> getPolicy() {
|
||||
return ApiResponse.success(policyService.getPolicy());
|
||||
}
|
||||
|
||||
@PutMapping("/admin/api/email-attachment-policies")
|
||||
public ApiResponse<EmailAttachmentPolicyView> updatePolicy(@Valid @RequestBody EmailAttachmentPolicyRequest request) {
|
||||
return ApiResponse.success("附件策略更新成功", policyService.updatePolicy(request));
|
||||
}
|
||||
}
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
package com.xiaowang.messagehub.controller;
|
||||
|
||||
import com.xiaowang.messagehub.dto.admin.EmailTemplateSaveRequest;
|
||||
import com.xiaowang.messagehub.dto.admin.EmailTemplateStatusUpdateRequest;
|
||||
import com.xiaowang.messagehub.dto.admin.EmailTemplateView;
|
||||
import com.xiaowang.messagehub.dto.common.ApiResponse;
|
||||
import com.xiaowang.messagehub.service.email.EmailTemplateService;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import java.util.List;
|
||||
|
||||
@Validated
|
||||
@RestController
|
||||
@RequestMapping("/admin/api/email-templates")
|
||||
public class EmailTemplateAdminController {
|
||||
|
||||
private final EmailTemplateService emailTemplateService;
|
||||
|
||||
public EmailTemplateAdminController(EmailTemplateService emailTemplateService) {
|
||||
this.emailTemplateService = emailTemplateService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ApiResponse<List<EmailTemplateView>> listTemplates() {
|
||||
return ApiResponse.success(emailTemplateService.listTemplates());
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ApiResponse<EmailTemplateView> createTemplate(@Valid @RequestBody EmailTemplateSaveRequest request) {
|
||||
return ApiResponse.success("邮件模板创建成功", emailTemplateService.createTemplate(request));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ApiResponse<EmailTemplateView> updateTemplate(@PathVariable Long id,
|
||||
@Valid @RequestBody EmailTemplateSaveRequest request) {
|
||||
return ApiResponse.success("邮件模板更新成功", emailTemplateService.updateTemplate(id, request));
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/status")
|
||||
public ApiResponse<EmailTemplateView> updateTemplateStatus(@PathVariable Long id,
|
||||
@Valid @RequestBody EmailTemplateStatusUpdateRequest request) {
|
||||
return ApiResponse.success("邮件模板状态更新成功", emailTemplateService.updateTemplateStatus(id, request.getEnabled()));
|
||||
}
|
||||
}
|
||||
-66
@@ -1,66 +0,0 @@
|
||||
package com.xiaowang.messagehub.controller;
|
||||
|
||||
import com.xiaowang.messagehub.dto.common.ApiResponse;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.jdbc.BadSqlGrammarException;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
import javax.validation.ConstraintViolationException;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ApiResponse<Void> handleMethodArgumentNotValid(MethodArgumentNotValidException exception) {
|
||||
String message = exception.getBindingResult().getFieldErrors().stream()
|
||||
.map(error -> error.getDefaultMessage() == null ? error.getField() + "不合法" : error.getDefaultMessage())
|
||||
.collect(Collectors.joining(";"));
|
||||
return ApiResponse.error(message);
|
||||
}
|
||||
|
||||
@ExceptionHandler(BindException.class)
|
||||
public ApiResponse<Void> handleBindException(BindException exception) {
|
||||
String message = exception.getBindingResult().getFieldErrors().stream()
|
||||
.map(error -> error.getDefaultMessage() == null ? error.getField() + "不合法" : error.getDefaultMessage())
|
||||
.collect(Collectors.joining(";"));
|
||||
return ApiResponse.error(message);
|
||||
}
|
||||
|
||||
@ExceptionHandler(ConstraintViolationException.class)
|
||||
public ApiResponse<Void> handleConstraintViolation(ConstraintViolationException exception) {
|
||||
return ApiResponse.error(exception.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpMessageNotReadableException.class)
|
||||
public ApiResponse<Void> handleNotReadable(HttpMessageNotReadableException exception) {
|
||||
return ApiResponse.error("请求体格式不正确");
|
||||
}
|
||||
|
||||
@ExceptionHandler(IllegalArgumentException.class)
|
||||
public ApiResponse<Void> handleIllegalArgument(IllegalArgumentException exception) {
|
||||
return ApiResponse.error(exception.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(BadSqlGrammarException.class)
|
||||
public ApiResponse<Void> handleBadSqlGrammar(BadSqlGrammarException exception) {
|
||||
String message = exception.getMessage();
|
||||
if (message != null && message.contains("message_channel_config") && message.contains("doesn't exist")) {
|
||||
return ApiResponse.error("缺少消息通道配置表,请先执行 2026-03-23_message_channel_management_patch.sql");
|
||||
}
|
||||
if (message != null
|
||||
&& ((message.contains("message_source_system") && message.contains("doesn't exist"))
|
||||
|| (message.contains("message_source_system_channel") && message.contains("doesn't exist")))) {
|
||||
return ApiResponse.error("缺少来源系统配置表,请先执行 2026-03-23_message_source_system_patch.sql");
|
||||
}
|
||||
return ApiResponse.error("数据库语句执行失败,请检查 MessageHub 初始化 SQL");
|
||||
}
|
||||
|
||||
@ExceptionHandler(RuntimeException.class)
|
||||
public ApiResponse<Void> handleRuntime(RuntimeException exception) {
|
||||
return ApiResponse.error(exception.getMessage());
|
||||
}
|
||||
}
|
||||
-120
@@ -1,120 +0,0 @@
|
||||
package com.xiaowang.messagehub.controller;
|
||||
|
||||
import com.xiaowang.messagehub.dto.admin.ChannelConfigSaveRequest;
|
||||
import com.xiaowang.messagehub.dto.admin.ChannelConfigTestRequest;
|
||||
import com.xiaowang.messagehub.dto.admin.ChannelConfigView;
|
||||
import com.xiaowang.messagehub.dto.admin.ChannelSmsTemplateSaveRequest;
|
||||
import com.xiaowang.messagehub.dto.admin.ChannelSmsTemplateStatusUpdateRequest;
|
||||
import com.xiaowang.messagehub.dto.admin.ChannelSmsTemplateView;
|
||||
import com.xiaowang.messagehub.dto.admin.ChannelStatusUpdateRequest;
|
||||
import com.xiaowang.messagehub.dto.admin.ChannelTemplateOptionView;
|
||||
import com.xiaowang.messagehub.dto.common.ApiResponse;
|
||||
import com.xiaowang.messagehub.service.channel.MessageChannelService;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import java.util.List;
|
||||
|
||||
@Validated
|
||||
@RestController
|
||||
@RequestMapping("/admin/api/channels")
|
||||
public class MessageChannelAdminController {
|
||||
|
||||
private final MessageChannelService messageChannelService;
|
||||
|
||||
public MessageChannelAdminController(MessageChannelService messageChannelService) {
|
||||
this.messageChannelService = messageChannelService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ApiResponse<List<ChannelConfigView>> listChannels() {
|
||||
return ApiResponse.success(messageChannelService.listChannels());
|
||||
}
|
||||
|
||||
@GetMapping("/templates")
|
||||
public ApiResponse<List<ChannelTemplateOptionView>> listTemplates(
|
||||
@RequestParam(required = false) String channelType) {
|
||||
return ApiResponse.success(messageChannelService.listEnabledTemplates(channelType));
|
||||
}
|
||||
|
||||
@GetMapping("/sms-templates")
|
||||
public ApiResponse<List<ChannelSmsTemplateView>> listSmsTemplates() {
|
||||
return ApiResponse.success(messageChannelService.listSmsTemplates());
|
||||
}
|
||||
|
||||
@GetMapping("/qq-templates")
|
||||
public ApiResponse<List<ChannelSmsTemplateView>> listQqTemplates() {
|
||||
return ApiResponse.success(messageChannelService.listQqTemplates());
|
||||
}
|
||||
|
||||
@PostMapping("/sms-templates")
|
||||
public ApiResponse<ChannelSmsTemplateView> createSmsTemplate(
|
||||
@Valid @RequestBody ChannelSmsTemplateSaveRequest request) {
|
||||
return ApiResponse.success("模板创建成功", messageChannelService.createSmsTemplate(request));
|
||||
}
|
||||
|
||||
@PutMapping("/sms-templates/{id}")
|
||||
public ApiResponse<ChannelSmsTemplateView> updateSmsTemplate(@PathVariable Long id,
|
||||
@Valid @RequestBody ChannelSmsTemplateSaveRequest request) {
|
||||
return ApiResponse.success("模板更新成功", messageChannelService.updateSmsTemplate(id, request));
|
||||
}
|
||||
|
||||
@PostMapping("/sms-templates/{id}/status")
|
||||
public ApiResponse<ChannelSmsTemplateView> updateSmsTemplateStatus(
|
||||
@PathVariable Long id,
|
||||
@Valid @RequestBody ChannelSmsTemplateStatusUpdateRequest request) {
|
||||
return ApiResponse.success("模板状态更新成功", messageChannelService.updateSmsTemplateStatus(id, request.getEnabled()));
|
||||
}
|
||||
|
||||
@PostMapping("/qq-templates")
|
||||
public ApiResponse<ChannelSmsTemplateView> createQqTemplate(
|
||||
@Valid @RequestBody ChannelSmsTemplateSaveRequest request) {
|
||||
return ApiResponse.success("QQ template created", messageChannelService.createQqTemplate(request));
|
||||
}
|
||||
|
||||
@PutMapping("/qq-templates/{id}")
|
||||
public ApiResponse<ChannelSmsTemplateView> updateQqTemplate(@PathVariable Long id,
|
||||
@Valid @RequestBody ChannelSmsTemplateSaveRequest request) {
|
||||
return ApiResponse.success("QQ template updated", messageChannelService.updateQqTemplate(id, request));
|
||||
}
|
||||
|
||||
@PostMapping("/qq-templates/{id}/status")
|
||||
public ApiResponse<ChannelSmsTemplateView> updateQqTemplateStatus(
|
||||
@PathVariable Long id,
|
||||
@Valid @RequestBody ChannelSmsTemplateStatusUpdateRequest request) {
|
||||
return ApiResponse.success("QQ template status updated", messageChannelService.updateQqTemplateStatus(id, request.getEnabled()));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ApiResponse<ChannelConfigView> getChannel(@PathVariable Long id) {
|
||||
return ApiResponse.success(messageChannelService.getChannel(id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ApiResponse<ChannelConfigView> createChannel(@Valid @RequestBody ChannelConfigSaveRequest request) {
|
||||
return ApiResponse.success("创建成功", messageChannelService.createChannel(request));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ApiResponse<ChannelConfigView> updateChannel(@PathVariable Long id,
|
||||
@Valid @RequestBody ChannelConfigSaveRequest request) {
|
||||
return ApiResponse.success("更新成功", messageChannelService.updateChannel(id, request));
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/status")
|
||||
public ApiResponse<ChannelConfigView> updateStatus(@PathVariable Long id,
|
||||
@Valid @RequestBody ChannelStatusUpdateRequest request) {
|
||||
return ApiResponse.success("状态更新成功", messageChannelService.updateChannelStatus(id, request.getEnabled()));
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/health-check")
|
||||
public ApiResponse<ChannelConfigView> runHealthCheck(@PathVariable Long id) {
|
||||
return ApiResponse.success("检测完成", messageChannelService.runHealthCheck(id));
|
||||
}
|
||||
|
||||
@PostMapping("/test-send")
|
||||
public ApiResponse<String> testSend(@Valid @RequestBody ChannelConfigTestRequest request) {
|
||||
return ApiResponse.success(messageChannelService.sendTest(request));
|
||||
}
|
||||
}
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
package com.xiaowang.messagehub.controller;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
@Controller
|
||||
public class MessageHubAdminPageController {
|
||||
|
||||
@GetMapping({"/messagehub-admin", "/messagehub-admin/"})
|
||||
public String index() {
|
||||
return "redirect:/messagehub-admin/index.html";
|
||||
}
|
||||
}
|
||||
-55
@@ -1,55 +0,0 @@
|
||||
package com.xiaowang.messagehub.controller;
|
||||
|
||||
import com.xiaowang.messagehub.dto.api.MessageIdReserveRequest;
|
||||
import com.xiaowang.messagehub.dto.api.MessageIdReserveResponse;
|
||||
import com.xiaowang.messagehub.dto.api.MessageStatusResponse;
|
||||
import com.xiaowang.messagehub.dto.api.PlatformCapabilityView;
|
||||
import com.xiaowang.messagehub.dto.common.ApiResponse;
|
||||
import com.xiaowang.messagehub.service.api.MessageHubPublicService;
|
||||
import com.xiaowang.messagehub.service.source.MessageSourceSystemService;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import java.util.List;
|
||||
|
||||
@Validated
|
||||
@RestController
|
||||
@RequestMapping("/api/v1")
|
||||
public class MessageHubPublicController {
|
||||
|
||||
private final MessageHubPublicService publicService;
|
||||
|
||||
public MessageHubPublicController(MessageHubPublicService publicService) {
|
||||
this.publicService = publicService;
|
||||
}
|
||||
|
||||
@PostMapping("/messages/ids")
|
||||
public ApiResponse<MessageIdReserveResponse> reserveMessageId(
|
||||
@RequestHeader(MessageSourceSystemService.ACCESS_TOKEN_HEADER) String accessToken,
|
||||
@Valid @RequestBody MessageIdReserveRequest request) {
|
||||
return ApiResponse.success(publicService.reserveMessageId(request.getSourceSystem(), accessToken));
|
||||
}
|
||||
|
||||
@GetMapping("/platforms")
|
||||
public ApiResponse<List<PlatformCapabilityView>> listPlatforms(
|
||||
@RequestHeader(MessageSourceSystemService.ACCESS_TOKEN_HEADER) String accessToken,
|
||||
@RequestParam String sourceSystem) {
|
||||
return ApiResponse.success(publicService.listPlatforms(sourceSystem, accessToken));
|
||||
}
|
||||
|
||||
@GetMapping("/messages/{messageId}/status")
|
||||
public ApiResponse<MessageStatusResponse> getMessageStatus(
|
||||
@RequestHeader(MessageSourceSystemService.ACCESS_TOKEN_HEADER) String accessToken,
|
||||
@PathVariable String messageId,
|
||||
@RequestParam String sourceSystem) {
|
||||
return ApiResponse.success(publicService.getStatus(messageId, sourceSystem, accessToken));
|
||||
}
|
||||
}
|
||||
-57
@@ -1,57 +0,0 @@
|
||||
package com.xiaowang.messagehub.controller;
|
||||
|
||||
import com.xiaowang.messagehub.dto.admin.SourceSystemSaveRequest;
|
||||
import com.xiaowang.messagehub.dto.admin.SourceSystemStatusUpdateRequest;
|
||||
import com.xiaowang.messagehub.dto.admin.SourceSystemView;
|
||||
import com.xiaowang.messagehub.dto.common.ApiResponse;
|
||||
import com.xiaowang.messagehub.service.source.MessageSourceSystemService;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import java.util.List;
|
||||
|
||||
@Validated
|
||||
@RestController
|
||||
@RequestMapping("/admin/api/source-systems")
|
||||
public class MessageSourceSystemAdminController {
|
||||
|
||||
private final MessageSourceSystemService sourceSystemService;
|
||||
|
||||
public MessageSourceSystemAdminController(MessageSourceSystemService sourceSystemService) {
|
||||
this.sourceSystemService = sourceSystemService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ApiResponse<List<SourceSystemView>> listSourceSystems() {
|
||||
return ApiResponse.success(sourceSystemService.listSourceSystems());
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ApiResponse<SourceSystemView> getSourceSystem(@PathVariable Long id) {
|
||||
return ApiResponse.success(sourceSystemService.getSourceSystem(id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ApiResponse<SourceSystemView> createSourceSystem(@Valid @RequestBody SourceSystemSaveRequest request) {
|
||||
return ApiResponse.success("来源系统创建成功", sourceSystemService.createSourceSystem(request));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ApiResponse<SourceSystemView> updateSourceSystem(@PathVariable Long id,
|
||||
@Valid @RequestBody SourceSystemSaveRequest request) {
|
||||
return ApiResponse.success("来源系统更新成功", sourceSystemService.updateSourceSystem(id, request));
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/status")
|
||||
public ApiResponse<SourceSystemView> updateSourceSystemStatus(@PathVariable Long id,
|
||||
@Valid @RequestBody SourceSystemStatusUpdateRequest request) {
|
||||
return ApiResponse.success("来源系统状态更新成功",
|
||||
sourceSystemService.updateSourceSystemStatus(id, request.getEnabled()));
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/access-token/rotate")
|
||||
public ApiResponse<SourceSystemView> rotateAccessToken(@PathVariable Long id) {
|
||||
return ApiResponse.success("access token rotated", sourceSystemService.rotateAccessToken(id));
|
||||
}
|
||||
}
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
package com.xiaowang.messagehub.controller;
|
||||
|
||||
import com.xiaowang.messagehub.dto.admin.PushLogView;
|
||||
import com.xiaowang.messagehub.dto.common.ApiResponse;
|
||||
import com.xiaowang.messagehub.service.admin.PushLogAdminService;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/admin/api/push-logs")
|
||||
public class PushLogAdminController {
|
||||
|
||||
private final PushLogAdminService pushLogAdminService;
|
||||
|
||||
public PushLogAdminController(PushLogAdminService pushLogAdminService) {
|
||||
this.pushLogAdminService = pushLogAdminService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ApiResponse<List<PushLogView>> listLogs(@RequestParam(required = false) String sourceSystem,
|
||||
@RequestParam(required = false) String channelType,
|
||||
@RequestParam(required = false) Integer status,
|
||||
@RequestParam(required = false) String keyword,
|
||||
@RequestParam(required = false) Boolean deadLetter,
|
||||
@RequestParam(defaultValue = "50") int limit) {
|
||||
return ApiResponse.success(pushLogAdminService.listLogs(sourceSystem, channelType, status, keyword, deadLetter, limit));
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class EmailMessageDTO extends MessageDTO {
|
||||
|
||||
private String subject;
|
||||
|
||||
private String content;
|
||||
|
||||
private String bodyType;
|
||||
|
||||
private String emailTemplateCode;
|
||||
|
||||
private List<Long> attachmentIds = new ArrayList<>();
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
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;
|
||||
|
||||
/**
|
||||
* Message payload for queue dispatch.
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@Data
|
||||
public class MessageDTO {
|
||||
|
||||
@NotBlank(message = "接收目标不能为空")
|
||||
private String receiver;
|
||||
|
||||
@NotBlank(message = "通道类型不能为空")
|
||||
@Pattern(regexp = "^(EMAIL|SMS|QQ|PUSH|WECHAT)$", message = "通道类型必须是 EMAIL、SMS、QQ、PUSH 或 WECHAT")
|
||||
private String channelType;
|
||||
|
||||
@NotBlank(message = "消息类型不能为空")
|
||||
@Pattern(regexp = "^(NOTIFICATION|VERIFICATION|PROMOTION|ALERT)$", message = "消息类型必须是 NOTIFICATION、VERIFICATION、PROMOTION 或 ALERT")
|
||||
private String msgType;
|
||||
|
||||
@Size(max = 50, message = "模板编码长度不能超过 50")
|
||||
private String templateCode;
|
||||
|
||||
private Map<String, Object> templateParams;
|
||||
|
||||
/**
|
||||
* Optional dispatch target.
|
||||
* When null, MessageHub uses the current default channel of the given type.
|
||||
* When provided, MessageHub matches by channelType + channelId.
|
||||
*/
|
||||
private Long channelId;
|
||||
|
||||
@NotBlank(message = "来源系统标识不能为空")
|
||||
@Size(max = 64, message = "来源系统标识长度不能超过 64")
|
||||
private String sourceSystem;
|
||||
|
||||
@NotBlank(message = "唯一标识不能为空")
|
||||
@Size(max = 100, message = "唯一标识长度不能超过 100")
|
||||
private String uniqueId;
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class QqMessageDTO extends MessageDTO {
|
||||
|
||||
private String targetType;
|
||||
|
||||
private String content;
|
||||
|
||||
private String contentMode;
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.Pattern;
|
||||
|
||||
/**
|
||||
* 短信消息 DTO。
|
||||
*/
|
||||
@Data
|
||||
public class SmsMessageDTO extends MessageDTO {
|
||||
|
||||
@NotBlank(message = "发送方式不能为空")
|
||||
@Pattern(regexp = "^(SPUG|OTHER)$", message = "发送方式必须是 SPUG 或 OTHER")
|
||||
private String sendMethod;
|
||||
}
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
public class ChannelConfigSaveRequest {
|
||||
|
||||
@NotBlank(message = "通道类型不能为空")
|
||||
private String channelType;
|
||||
|
||||
@NotBlank(message = "提供商不能为空")
|
||||
private String providerCode;
|
||||
|
||||
@NotBlank(message = "通道名称不能为空")
|
||||
private String channelName;
|
||||
|
||||
@NotNull(message = "启用状态不能为空")
|
||||
private Boolean enabled = Boolean.TRUE;
|
||||
|
||||
@NotNull(message = "默认通道标记不能为空")
|
||||
private Boolean isDefault = Boolean.FALSE;
|
||||
|
||||
private Map<String, Object> config = new LinkedHashMap<>();
|
||||
|
||||
private Map<String, String> secretConfig = new LinkedHashMap<>();
|
||||
|
||||
private String remark;
|
||||
}
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
public class ChannelConfigTestRequest {
|
||||
|
||||
@NotNull(message = "通道 ID 不能为空")
|
||||
private Long channelId;
|
||||
|
||||
@NotBlank(message = "接收目标不能为空")
|
||||
private String receiver;
|
||||
|
||||
private String subject;
|
||||
|
||||
private String content;
|
||||
|
||||
private String bodyType;
|
||||
|
||||
private String targetType;
|
||||
|
||||
private String contentMode;
|
||||
|
||||
private String templateCode;
|
||||
|
||||
private Map<String, Object> templateParams = new LinkedHashMap<>();
|
||||
|
||||
private List<Long> attachmentIds = new ArrayList<>();
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
public class ChannelConfigView {
|
||||
|
||||
private Long id;
|
||||
|
||||
private String channelType;
|
||||
|
||||
private String providerCode;
|
||||
|
||||
private String providerName;
|
||||
|
||||
private String channelName;
|
||||
|
||||
private Map<String, Object> config;
|
||||
|
||||
private Map<String, String> secretConfigMask;
|
||||
|
||||
private boolean enabled;
|
||||
|
||||
private boolean isDefault;
|
||||
|
||||
private String healthStatus;
|
||||
|
||||
private String healthMessage;
|
||||
|
||||
private LocalDateTime lastHealthCheckTime;
|
||||
|
||||
private String remark;
|
||||
|
||||
private LocalDateTime createTime;
|
||||
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
-31
@@ -1,31 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
@Data
|
||||
public class ChannelSmsTemplateSaveRequest {
|
||||
|
||||
private String templateCode;
|
||||
|
||||
@NotBlank(message = "模板名称不能为空")
|
||||
private String templateName;
|
||||
|
||||
private Long channelId;
|
||||
|
||||
private String externalId;
|
||||
|
||||
@NotBlank(message = "模板内容不能为空")
|
||||
private String contentPattern;
|
||||
|
||||
@NotNull(message = "启用状态不能为空")
|
||||
private Boolean enabled = Boolean.TRUE;
|
||||
|
||||
private String description;
|
||||
|
||||
private Integer msgType;
|
||||
|
||||
private Integer msgCategory;
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
@Data
|
||||
public class ChannelSmsTemplateStatusUpdateRequest {
|
||||
|
||||
@NotNull(message = "启用状态不能为空")
|
||||
private Boolean enabled;
|
||||
}
|
||||
-41
@@ -1,41 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class ChannelSmsTemplateView {
|
||||
|
||||
private Long id;
|
||||
|
||||
private String templateCode;
|
||||
|
||||
private String templateName;
|
||||
|
||||
private String channelType;
|
||||
|
||||
private Integer msgType;
|
||||
|
||||
private Integer msgCategory;
|
||||
|
||||
private Long channelId;
|
||||
|
||||
private String channelName;
|
||||
|
||||
private String externalId;
|
||||
|
||||
private String contentPattern;
|
||||
|
||||
private boolean enabled;
|
||||
|
||||
private String description;
|
||||
|
||||
private List<String> placeholders = new ArrayList<>();
|
||||
|
||||
private LocalDateTime createTime;
|
||||
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
@Data
|
||||
public class ChannelStatusUpdateRequest {
|
||||
|
||||
@NotNull(message = "启用状态不能为空")
|
||||
private Boolean enabled;
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class ChannelTemplateOptionView {
|
||||
|
||||
private Long id;
|
||||
|
||||
private String templateCode;
|
||||
|
||||
private String templateName;
|
||||
|
||||
private String channelType;
|
||||
|
||||
private String contentPattern;
|
||||
|
||||
private List<String> placeholders = new ArrayList<>();
|
||||
}
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.Min;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
@Data
|
||||
public class EmailAttachmentPolicyRequest {
|
||||
|
||||
@NotNull(message = "单文件大小限制不能为空")
|
||||
@Min(value = 1, message = "单文件大小限制必须大于 0")
|
||||
private Long maxSingleFileSize;
|
||||
|
||||
@NotNull(message = "总附件大小限制不能为空")
|
||||
@Min(value = 1, message = "总附件大小限制必须大于 0")
|
||||
private Long maxTotalFileSize;
|
||||
|
||||
@NotNull(message = "附件数量限制不能为空")
|
||||
@Min(value = 1, message = "附件数量限制必须大于 0")
|
||||
private Integer maxFileCount;
|
||||
|
||||
private String allowedExtensions;
|
||||
|
||||
private String allowedMimeTypes;
|
||||
|
||||
@NotNull(message = "附件保留天数不能为空")
|
||||
@Min(value = 1, message = "附件保留天数必须大于 0")
|
||||
private Integer retentionDays;
|
||||
|
||||
@NotNull(message = "读取超时时间不能为空")
|
||||
@Min(value = 1000, message = "读取超时时间不能小于 1000 毫秒")
|
||||
private Integer readTimeoutMillis;
|
||||
}
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class EmailAttachmentPolicyView {
|
||||
|
||||
private Long maxSingleFileSize;
|
||||
|
||||
private Long maxTotalFileSize;
|
||||
|
||||
private Integer maxFileCount;
|
||||
|
||||
private String allowedExtensions;
|
||||
|
||||
private String allowedMimeTypes;
|
||||
|
||||
private Integer retentionDays;
|
||||
|
||||
private Integer readTimeoutMillis;
|
||||
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class EmailAttachmentView {
|
||||
|
||||
private Long id;
|
||||
|
||||
private String originalFileName;
|
||||
|
||||
private String contentType;
|
||||
|
||||
private String fileExtension;
|
||||
|
||||
private Long fileSize;
|
||||
|
||||
private String status;
|
||||
|
||||
private LocalDateTime expireTime;
|
||||
|
||||
private LocalDateTime createTime;
|
||||
}
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
@Data
|
||||
public class EmailTemplateSaveRequest {
|
||||
|
||||
@Size(max = 64, message = "邮件模板编码不能超过 64 个字符")
|
||||
private String templateCode;
|
||||
|
||||
@NotBlank(message = "邮件模板名称不能为空")
|
||||
@Size(max = 100, message = "邮件模板名称不能超过 100 个字符")
|
||||
private String templateName;
|
||||
|
||||
@NotBlank(message = "邮件主题模板不能为空")
|
||||
private String subjectPattern;
|
||||
|
||||
@NotBlank(message = "邮件正文类型不能为空")
|
||||
private String bodyType;
|
||||
|
||||
@NotBlank(message = "邮件正文模板不能为空")
|
||||
private String bodyPattern;
|
||||
|
||||
private Long channelId;
|
||||
|
||||
private Boolean enabled = Boolean.TRUE;
|
||||
|
||||
@Size(max = 255, message = "描述不能超过 255 个字符")
|
||||
private String description;
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
@Data
|
||||
public class EmailTemplateStatusUpdateRequest {
|
||||
|
||||
@NotNull(message = "启用状态不能为空")
|
||||
private Boolean enabled;
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class EmailTemplateView {
|
||||
|
||||
private Long id;
|
||||
|
||||
private String templateCode;
|
||||
|
||||
private String templateName;
|
||||
|
||||
private String subjectPattern;
|
||||
|
||||
private String bodyType;
|
||||
|
||||
private String bodyPattern;
|
||||
|
||||
private Long channelId;
|
||||
|
||||
private String channelName;
|
||||
|
||||
private boolean enabled;
|
||||
|
||||
private String description;
|
||||
|
||||
private List<String> placeholders = new ArrayList<>();
|
||||
|
||||
private LocalDateTime createTime;
|
||||
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class PushLogView {
|
||||
|
||||
private String id;
|
||||
|
||||
private String sourceSystem;
|
||||
|
||||
private String uniqueId;
|
||||
|
||||
private String receiver;
|
||||
|
||||
private String channelType;
|
||||
|
||||
private Long channelId;
|
||||
|
||||
private String providerCode;
|
||||
|
||||
private String msgType;
|
||||
|
||||
private String templateCode;
|
||||
|
||||
private String finalContent;
|
||||
|
||||
private Integer status;
|
||||
|
||||
private String dispatchStatus;
|
||||
|
||||
private Integer retryCount;
|
||||
|
||||
private LocalDateTime nextRetryTime;
|
||||
|
||||
private String failReason;
|
||||
|
||||
private String deadLetterReason;
|
||||
|
||||
private LocalDateTime sendTime;
|
||||
|
||||
private LocalDateTime createTime;
|
||||
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.Size;
|
||||
import java.util.Set;
|
||||
|
||||
@Data
|
||||
public class SourceSystemSaveRequest {
|
||||
|
||||
@NotBlank(message = "系统标识不能为空")
|
||||
@Size(max = 64, message = "系统标识长度不能超过 64")
|
||||
private String systemCode;
|
||||
|
||||
@NotBlank(message = "系统名称不能为空")
|
||||
@Size(max = 100, message = "系统名称长度不能超过 100")
|
||||
private String systemName;
|
||||
|
||||
private Boolean enabled = Boolean.TRUE;
|
||||
|
||||
@Size(max = 255, message = "备注长度不能超过 255")
|
||||
private String remark;
|
||||
|
||||
private Long defaultSmsChannelId;
|
||||
|
||||
private Long defaultEmailChannelId;
|
||||
|
||||
private Long defaultQqChannelId;
|
||||
|
||||
private Set<String> allowedPlatforms;
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
@Data
|
||||
public class SourceSystemStatusUpdateRequest {
|
||||
|
||||
@NotNull(message = "启停状态不能为空")
|
||||
private Boolean enabled;
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto.admin;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Set;
|
||||
|
||||
@Data
|
||||
public class SourceSystemView {
|
||||
|
||||
private Long id;
|
||||
|
||||
private String systemCode;
|
||||
|
||||
private String systemName;
|
||||
|
||||
private Boolean enabled;
|
||||
|
||||
private String remark;
|
||||
|
||||
private Set<String> allowedPlatforms;
|
||||
|
||||
private String accessToken;
|
||||
|
||||
private String accessTokenHint;
|
||||
|
||||
private LocalDateTime tokenUpdateTime;
|
||||
|
||||
private Long defaultSmsChannelId;
|
||||
|
||||
private String defaultSmsChannelName;
|
||||
|
||||
private Long defaultEmailChannelId;
|
||||
|
||||
private String defaultEmailChannelName;
|
||||
|
||||
private Long defaultQqChannelId;
|
||||
|
||||
private String defaultQqChannelName;
|
||||
|
||||
private LocalDateTime createTime;
|
||||
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto.api;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.Size;
|
||||
|
||||
@Data
|
||||
public class MessageIdReserveRequest {
|
||||
|
||||
@NotBlank(message = "sourceSystem is required")
|
||||
@Size(max = 64, message = "sourceSystem length must not exceed 64")
|
||||
private String sourceSystem;
|
||||
}
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto.api;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class MessageIdReserveResponse {
|
||||
|
||||
private String messageId;
|
||||
|
||||
private String dispatchStatus;
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto.api;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
public class MessageIngressEnvelope {
|
||||
|
||||
private String messageId;
|
||||
|
||||
private String sourceSystem;
|
||||
|
||||
private String platform;
|
||||
|
||||
private String receiver;
|
||||
|
||||
private String msgType;
|
||||
|
||||
private String templateCode;
|
||||
|
||||
private Map<String, Object> templateParams = new LinkedHashMap<>();
|
||||
|
||||
private Long channelId;
|
||||
|
||||
private String uniqueId;
|
||||
|
||||
private Map<String, Object> platformParams = new LinkedHashMap<>();
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto.api;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class MessageStatusResponse {
|
||||
|
||||
private String messageId;
|
||||
|
||||
private String sourceSystem;
|
||||
|
||||
private String uniqueId;
|
||||
|
||||
private String platform;
|
||||
|
||||
private String receiver;
|
||||
|
||||
private String msgType;
|
||||
|
||||
private String dispatchStatus;
|
||||
|
||||
private Integer legacyStatus;
|
||||
|
||||
private Long channelId;
|
||||
|
||||
private String providerCode;
|
||||
|
||||
private Integer retryCount;
|
||||
|
||||
private String failReason;
|
||||
|
||||
private String providerResponse;
|
||||
|
||||
private LocalDateTime sendTime;
|
||||
|
||||
private LocalDateTime createTime;
|
||||
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto.api;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
public class PlatformCapabilityView {
|
||||
|
||||
private String platform;
|
||||
|
||||
private String name;
|
||||
|
||||
private boolean available;
|
||||
|
||||
private int enabledChannelCount;
|
||||
|
||||
private Map<String, String> platformParams = new LinkedHashMap<>();
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package com.xiaowang.messagehub.dto.common;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class ApiResponse<T> {
|
||||
|
||||
private int code;
|
||||
|
||||
private String message;
|
||||
|
||||
private T data;
|
||||
|
||||
public static <T> ApiResponse<T> success(T data) {
|
||||
ApiResponse<T> response = new ApiResponse<>();
|
||||
response.setCode(0);
|
||||
response.setMessage("success");
|
||||
response.setData(data);
|
||||
return response;
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> success(String message, T data) {
|
||||
ApiResponse<T> response = success(data);
|
||||
response.setMessage(message);
|
||||
return response;
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> error(String message) {
|
||||
ApiResponse<T> response = new ApiResponse<>();
|
||||
response.setCode(1);
|
||||
response.setMessage(message);
|
||||
return response;
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
package com.xiaowang.messagehub.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("email_attachment")
|
||||
public class EmailAttachmentDO {
|
||||
|
||||
@TableId(value = "id", type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
|
||||
@TableField("original_file_name")
|
||||
private String originalFileName;
|
||||
|
||||
@TableField("stored_file_name")
|
||||
private String storedFileName;
|
||||
|
||||
@TableField("storage_path")
|
||||
private String storagePath;
|
||||
|
||||
@TableField("content_type")
|
||||
private String contentType;
|
||||
|
||||
@TableField("file_extension")
|
||||
private String fileExtension;
|
||||
|
||||
@TableField("file_size")
|
||||
private Long fileSize;
|
||||
|
||||
@TableField("status")
|
||||
private String status;
|
||||
|
||||
@TableField("expire_time")
|
||||
private LocalDateTime expireTime;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
package com.xiaowang.messagehub.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("email_attachment_policy")
|
||||
public class EmailAttachmentPolicyDO {
|
||||
|
||||
@TableId(value = "id", type = IdType.INPUT)
|
||||
private Long id;
|
||||
|
||||
@TableField("max_single_file_size")
|
||||
private Long maxSingleFileSize;
|
||||
|
||||
@TableField("max_total_file_size")
|
||||
private Long maxTotalFileSize;
|
||||
|
||||
@TableField("max_file_count")
|
||||
private Integer maxFileCount;
|
||||
|
||||
@TableField("allowed_extensions")
|
||||
private String allowedExtensions;
|
||||
|
||||
@TableField("allowed_mime_types")
|
||||
private String allowedMimeTypes;
|
||||
|
||||
@TableField("retention_days")
|
||||
private Integer retentionDays;
|
||||
|
||||
@TableField("read_timeout_millis")
|
||||
private Integer readTimeoutMillis;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
package com.xiaowang.messagehub.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("email_template")
|
||||
public class EmailTemplateDO {
|
||||
|
||||
@TableId(value = "id", type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
|
||||
@TableField("template_code")
|
||||
private String templateCode;
|
||||
|
||||
@TableField("template_name")
|
||||
private String templateName;
|
||||
|
||||
@TableField("subject_pattern")
|
||||
private String subjectPattern;
|
||||
|
||||
@TableField("body_type")
|
||||
private String bodyType;
|
||||
|
||||
@TableField("body_pattern")
|
||||
private String bodyPattern;
|
||||
|
||||
@TableField("channel_id")
|
||||
private Long channelId;
|
||||
|
||||
@TableField("is_enable")
|
||||
private Integer isEnable;
|
||||
|
||||
@TableField("description")
|
||||
private String description;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
package com.xiaowang.messagehub.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("message_channel_config")
|
||||
public class MessageChannelConfigDO {
|
||||
|
||||
@TableId(value = "id", type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
|
||||
@TableField("channel_type")
|
||||
private String channelType;
|
||||
|
||||
@TableField("provider_code")
|
||||
private String providerCode;
|
||||
|
||||
@TableField("channel_name")
|
||||
private String channelName;
|
||||
|
||||
@TableField("config_json")
|
||||
private String configJson;
|
||||
|
||||
@TableField("secret_json")
|
||||
private String secretJson;
|
||||
|
||||
@TableField("enabled")
|
||||
private Integer enabled;
|
||||
|
||||
@TableField("is_default")
|
||||
private Integer isDefault;
|
||||
|
||||
@TableField("health_status")
|
||||
private String healthStatus;
|
||||
|
||||
@TableField("health_message")
|
||||
private String healthMessage;
|
||||
|
||||
@TableField("last_health_check_time")
|
||||
private LocalDateTime lastHealthCheckTime;
|
||||
|
||||
@TableField("remark")
|
||||
private String remark;
|
||||
|
||||
@TableLogic
|
||||
@TableField("deleted")
|
||||
private Integer deleted;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
package com.xiaowang.messagehub.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import lombok.Data;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 消息实体类
|
||||
* 用于存储消息相关的数据信息
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@Data // 使用Lombok的@Data注解,自动生成getter、setter、toString等方法
|
||||
@TableName("message") // MyBatis-Plus的表名注解,指定对应数据库表名为message
|
||||
public class MessageDO {
|
||||
// 主键ID,使用自增策略
|
||||
@TableId(value = "id", type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
|
||||
// 消息内容字段
|
||||
@TableField("content")
|
||||
private String content;
|
||||
|
||||
// 消息主题字段
|
||||
@TableField("topic")
|
||||
private String topic;
|
||||
|
||||
// 消息状态字段
|
||||
@TableField("status")
|
||||
private Integer status;
|
||||
|
||||
// 创建时间字段,在插入时自动填充
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
// 更新时间字段,在插入和更新时自动填充
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
|
||||
// 逻辑删除字段,标记是否已删除
|
||||
@TableLogic
|
||||
@TableField("deleted")
|
||||
private Integer deleted;
|
||||
}
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
package com.xiaowang.messagehub.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("message_source_system_channel")
|
||||
public class MessageSourceSystemChannelDO {
|
||||
|
||||
@TableId(value = "id", type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
|
||||
@TableField("system_id")
|
||||
private Long systemId;
|
||||
|
||||
@TableField("channel_type")
|
||||
private String channelType;
|
||||
|
||||
@TableField("channel_id")
|
||||
private Long channelId;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package com.xiaowang.messagehub.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("message_source_system")
|
||||
public class MessageSourceSystemDO {
|
||||
|
||||
@TableId(value = "id", type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
|
||||
@TableField("system_code")
|
||||
private String systemCode;
|
||||
|
||||
@TableField("system_name")
|
||||
private String systemName;
|
||||
|
||||
@TableField("enabled")
|
||||
private Integer enabled;
|
||||
|
||||
@TableField("remark")
|
||||
private String remark;
|
||||
|
||||
@TableField("access_token_hash")
|
||||
private String accessTokenHash;
|
||||
|
||||
@TableField("access_token_hint")
|
||||
private String accessTokenHint;
|
||||
|
||||
@TableField("token_update_time")
|
||||
private LocalDateTime tokenUpdateTime;
|
||||
|
||||
@TableLogic
|
||||
@TableField("deleted")
|
||||
private Integer deleted;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
package com.xiaowang.messagehub.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("message_source_system_permission")
|
||||
public class MessageSourceSystemPermissionDO {
|
||||
|
||||
@TableId(value = "id", type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
|
||||
@TableField("system_id")
|
||||
private Long systemId;
|
||||
|
||||
@TableField("platform")
|
||||
private String platform;
|
||||
|
||||
@TableField("enabled")
|
||||
private Integer enabled;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
package com.xiaowang.messagehub.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import lombok.Data;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 推送日志实体类
|
||||
* 用于记录系统推送操作的相关信息,包括推送来源、接收者、消息内容等
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@Data // Lombok注解,自动生成getter、setter等方法
|
||||
@TableName("push_log") // MyBatis-Plus注解,指定对应数据库表名
|
||||
public class PushLogDO {
|
||||
@TableId(value = "id", type = IdType.INPUT) // 指定主键字段,类型为手动输入
|
||||
private String id; // 推送日志的唯一标识符
|
||||
|
||||
@TableField("source_system") // 指定对应数据库字段名
|
||||
private String sourceSystem; // 推送来源系统标识
|
||||
|
||||
@TableField("unique_id")
|
||||
private String uniqueId; // 推送内容的唯一标识,用于去重
|
||||
|
||||
@TableField("receiver")
|
||||
private String receiver; // 消息接收者标识
|
||||
|
||||
@TableField("channel_type")
|
||||
private String channelType; // 推送渠道类型,如短信、邮件等
|
||||
|
||||
@TableField("channel_id")
|
||||
private Long channelId;
|
||||
|
||||
@TableField("provider_code")
|
||||
private String providerCode;
|
||||
|
||||
@TableField("msg_type")
|
||||
private String msgType; // 消息类型,如通知、验证码等
|
||||
|
||||
@TableField("template_code")
|
||||
private String templateCode; // 消息模板代码
|
||||
|
||||
@TableField("template_params")
|
||||
private String templateParams; // 消息模板参数,JSON格式
|
||||
|
||||
@TableField("final_content")
|
||||
private String finalContent; // 最终推送的消息内容
|
||||
|
||||
@TableField("status")
|
||||
private Integer status; // 推送状态,如0-待发送,1-发送成功,2-发送失败等
|
||||
|
||||
@TableField("dispatch_status")
|
||||
private String dispatchStatus;
|
||||
|
||||
@TableField("retry_count")
|
||||
private Integer retryCount; // 重试次数
|
||||
|
||||
@TableField("next_retry_time")
|
||||
private LocalDateTime nextRetryTime;
|
||||
|
||||
@TableField("fail_reason")
|
||||
private String failReason; // 失败原因描述
|
||||
|
||||
@TableField("dead_letter_reason")
|
||||
private String deadLetterReason;
|
||||
|
||||
@TableField("request_payload")
|
||||
private String requestPayload;
|
||||
|
||||
@TableField("provider_response")
|
||||
private String providerResponse;
|
||||
|
||||
@TableField("send_time")
|
||||
private LocalDateTime sendTime; // 消息发送时间
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT) // 自动填充字段,插入时自动设置当前时间
|
||||
private LocalDateTime createTime; // 记录创建时间
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
package com.xiaowang.messagehub.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import lombok.Data;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 推送模板实体类
|
||||
* 用于存储推送模板的相关信息,包括模板代码、名称、渠道类型等
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@Data
|
||||
@TableName("push_template")
|
||||
public class PushTemplateDO {
|
||||
// 主键ID,自增长类型
|
||||
@TableId(value = "id", type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
|
||||
// 模板代码,用于唯一标识一个模板
|
||||
@TableField("template_code")
|
||||
private String templateCode;
|
||||
|
||||
// 模板名称,用于显示和识别
|
||||
@TableField("template_name")
|
||||
private String templateName;
|
||||
|
||||
// 渠道类型,标识推送渠道(如APP、短信、邮件等)
|
||||
@TableField("channel_type")
|
||||
private String channelType;
|
||||
|
||||
// 消息类型,用于区分不同类型的消息
|
||||
@TableField("msg_type")
|
||||
private Integer msgType;
|
||||
|
||||
// 绑定的短信通道ID,留空代表全局通用
|
||||
@TableField("channel_id")
|
||||
private Long channelId;
|
||||
|
||||
// 外部ID,用于关联外部系统的模板标识
|
||||
@TableField("external_id")
|
||||
private String externalId;
|
||||
|
||||
// 内容模板,用于定义消息内容的格式
|
||||
@TableField("content_pattern")
|
||||
private String contentPattern;
|
||||
|
||||
// 消息分类,用于消息的分类管理
|
||||
@TableField("msg_category")
|
||||
private Integer msgCategory;
|
||||
|
||||
// 是否启用,标识模板是否可以使用(1-启用,0-禁用)
|
||||
@TableField("is_enable")
|
||||
private Integer isEnable;
|
||||
|
||||
// 模板描述,用于说明模板的用途和特点
|
||||
@TableField("description")
|
||||
private String description;
|
||||
|
||||
// 创建时间,自动填充(插入时)
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
// 更新时间,自动填充(插入和更新时)
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.xiaowang.messagehub.enums;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum ChannelHealthStatusEnum {
|
||||
|
||||
UNKNOWN("UNKNOWN", "待检测"),
|
||||
HEALTHY("HEALTHY", "正常"),
|
||||
UNHEALTHY("UNHEALTHY", "异常");
|
||||
|
||||
private final String code;
|
||||
|
||||
private final String label;
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package com.xiaowang.messagehub.enums;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum ChannelProviderCodeEnum {
|
||||
|
||||
SPUG("SPUG", ChannelTypeEnum.SMS.getCode(), "Spug短信"),
|
||||
MOCK_SMS("MOCK_SMS", ChannelTypeEnum.SMS.getCode(), "开发Mock短信"),
|
||||
GMAIL("GMAIL", ChannelTypeEnum.EMAIL.getCode(), "Gmail SMTP"),
|
||||
QQMAIL("QQMAIL", ChannelTypeEnum.EMAIL.getCode(), "QQ邮箱 SMTP"),
|
||||
NETEASE_163("NETEASE_163", ChannelTypeEnum.EMAIL.getCode(), "网易 163 邮箱 SMTP"),
|
||||
NETEASE_126("NETEASE_126", ChannelTypeEnum.EMAIL.getCode(), "网易 126 邮箱 SMTP"),
|
||||
OUTLOOK("OUTLOOK", ChannelTypeEnum.EMAIL.getCode(), "Outlook SMTP"),
|
||||
HOTMAIL("HOTMAIL", ChannelTypeEnum.EMAIL.getCode(), "Hotmail SMTP"),
|
||||
ALIYUN_ENTERPRISE("ALIYUN_ENTERPRISE", ChannelTypeEnum.EMAIL.getCode(), "阿里企业邮箱 SMTP"),
|
||||
TENCENT_ENTERPRISE("TENCENT_ENTERPRISE", ChannelTypeEnum.EMAIL.getCode(), "腾讯企业邮箱 SMTP"),
|
||||
SMTP_GENERIC("SMTP_GENERIC", ChannelTypeEnum.EMAIL.getCode(), "通用 SMTP"),
|
||||
MOCK_EMAIL("MOCK_EMAIL", ChannelTypeEnum.EMAIL.getCode(), "开发Mock邮件"),
|
||||
QQAUTO("QQAUTO", ChannelTypeEnum.QQ.getCode(), "QQAuto"),
|
||||
MOCK_QQ("MOCK_QQ", ChannelTypeEnum.QQ.getCode(), "开发Mock QQ");
|
||||
|
||||
private final String code;
|
||||
|
||||
private final String channelType;
|
||||
|
||||
private final String label;
|
||||
|
||||
public static ChannelProviderCodeEnum fromCode(String code) {
|
||||
for (ChannelProviderCodeEnum value : values()) {
|
||||
if (value.code.equalsIgnoreCase(code)) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("不支持的通道提供方: " + code);
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package com.xiaowang.messagehub.enums;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum ChannelTypeEnum {
|
||||
|
||||
SMS("SMS", "短信"),
|
||||
EMAIL("EMAIL", "邮件"),
|
||||
QQ("QQ", "QQ");
|
||||
|
||||
private final String code;
|
||||
|
||||
private final String label;
|
||||
|
||||
public static ChannelTypeEnum fromCode(String code) {
|
||||
for (ChannelTypeEnum value : values()) {
|
||||
if (value.code.equalsIgnoreCase(code)) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("不支持的通道类型: " + code);
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
package com.xiaowang.messagehub.enums;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
public enum DispatchStatusEnum {
|
||||
ACCEPTED(0),
|
||||
PENDING(0),
|
||||
SUCCESS(1),
|
||||
FAILED(2);
|
||||
|
||||
private final int legacyStatus;
|
||||
|
||||
DispatchStatusEnum(int legacyStatus) {
|
||||
this.legacyStatus = legacyStatus;
|
||||
}
|
||||
|
||||
public int getLegacyStatus() {
|
||||
return legacyStatus;
|
||||
}
|
||||
|
||||
public static DispatchStatusEnum fromCode(String code) {
|
||||
if (code == null || code.trim().isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
String normalized = code.trim().toUpperCase(Locale.ROOT);
|
||||
for (DispatchStatusEnum item : values()) {
|
||||
if (item.name().equals(normalized)) {
|
||||
return item;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Unsupported dispatch status: " + code);
|
||||
}
|
||||
|
||||
public static DispatchStatusEnum fromLegacyStatus(Integer status) {
|
||||
if (status == null) {
|
||||
return ACCEPTED;
|
||||
}
|
||||
if (status == 1) {
|
||||
return SUCCESS;
|
||||
}
|
||||
if (status == 2) {
|
||||
return FAILED;
|
||||
}
|
||||
return PENDING;
|
||||
}
|
||||
|
||||
public static String normalize(String code, Integer legacyStatus) {
|
||||
DispatchStatusEnum status = fromCode(code);
|
||||
if (status != null) {
|
||||
return status.name();
|
||||
}
|
||||
return fromLegacyStatus(legacyStatus).name();
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.xiaowang.messagehub.enums;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
public enum EmailBodyTypeEnum {
|
||||
|
||||
TEXT,
|
||||
HTML;
|
||||
|
||||
public static EmailBodyTypeEnum fromCode(String code) {
|
||||
if (code == null || code.trim().isEmpty()) {
|
||||
return TEXT;
|
||||
}
|
||||
return valueOf(code.trim().toUpperCase(Locale.ROOT));
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
package com.xiaowang.messagehub.health;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* 连接健康检查类
|
||||
* 用于检查系统中各个关键服务的连接状态,包括MySQL、RabbitMQ和Nacos
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@Component
|
||||
public class ConnectionHealthChecker {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ConnectionHealthChecker.class); // 使用Logback日志框架
|
||||
|
||||
@Autowired
|
||||
private ConnectionFactory rabbitMQConnectionFactory; // RabbitMQ连接工厂,用于创建RabbitMQ连接
|
||||
|
||||
// MySQL连接配置参数
|
||||
private String mysqlUrl;
|
||||
private String mysqlUsername;
|
||||
private String mysqlPassword;
|
||||
private String nacosServerAddr; // Nacos服务器地址
|
||||
|
||||
/**
|
||||
* 通过Spring Environment注入MySQL和Nacos的配置信息
|
||||
* @param env Spring环境对象,用于获取配置属性
|
||||
*/
|
||||
@Autowired
|
||||
public void setMysqlConfig(org.springframework.core.env.Environment env) {
|
||||
this.mysqlUrl = env.getProperty("spring.datasource.url");
|
||||
this.mysqlUsername = env.getProperty("spring.datasource.username");
|
||||
this.mysqlPassword = env.getProperty("spring.datasource.password");
|
||||
this.nacosServerAddr = env.getProperty("spring.cloud.nacos.discovery.server-addr");
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查MySQL数据库连接
|
||||
* @return 如果连接成功返回true,否则返回false
|
||||
*/
|
||||
public boolean checkMySQL() {
|
||||
logger.info("开始检查MySQL连接...");
|
||||
try (java.sql.Connection conn = DriverManager.getConnection(mysqlUrl, mysqlUsername, mysqlPassword)) {
|
||||
if (conn.isValid(5)) { // 设置5秒超时验证连接
|
||||
logger.info("MySQL连接成功 - URL: {}", mysqlUrl);
|
||||
return true;
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.error("MySQL连接失败 - URL: {}, 错误: {}", mysqlUrl, e.getMessage(), e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查RabbitMQ消息队列连接
|
||||
* @return 如果连接成功返回true,否则返回false
|
||||
*/
|
||||
public boolean checkRabbitMQ() {
|
||||
logger.info("开始检查RabbitMQ连接...");
|
||||
try {
|
||||
org.springframework.amqp.rabbit.connection.Connection connection = rabbitMQConnectionFactory.createConnection();
|
||||
if (connection.isOpen()) {
|
||||
logger.info("RabbitMQ连接成功 - Host: {}, Port: {}",
|
||||
rabbitMQConnectionFactory.getHost(), rabbitMQConnectionFactory.getPort());
|
||||
connection.close(); // 完成检查后关闭连接
|
||||
return true;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("RabbitMQ连接失败 - Host: {}, Port: {}, 错误: {}",
|
||||
rabbitMQConnectionFactory.getHost(), rabbitMQConnectionFactory.getPort(), e.getMessage(), e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查Nacos服务发现连接
|
||||
* @return 总是返回true,因为Nacos连接在应用启动时自动建立
|
||||
*/
|
||||
public boolean checkNacos() {
|
||||
logger.info("开始检查Nacos连接...");
|
||||
logger.info("Nacos配置 - ServerAddr: {}, Namespace: MessageHub", nacosServerAddr);
|
||||
logger.info("Nacos连接检查完成(Nacos客户端会在启动时自动连接)");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
-76
@@ -1,76 +0,0 @@
|
||||
package com.xiaowang.messagehub.listener;
|
||||
|
||||
import com.xiaowang.messagehub.health.ConnectionHealthChecker;
|
||||
import com.xiaowang.messagehub.service.channel.MessageChannelService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.ApplicationListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class ApplicationStartupListener implements ApplicationListener<ApplicationReadyEvent> {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ApplicationStartupListener.class);
|
||||
|
||||
@Autowired
|
||||
private ConnectionHealthChecker connectionHealthChecker;
|
||||
|
||||
@Autowired
|
||||
private MessageChannelService messageChannelService;
|
||||
|
||||
@Override
|
||||
public void onApplicationEvent(ApplicationReadyEvent event) {
|
||||
logger.info("========================================");
|
||||
logger.info("MessageHub 服务启动完成,开始检查关键依赖...");
|
||||
logger.info("========================================");
|
||||
|
||||
boolean allSuccess = true;
|
||||
|
||||
logger.info("");
|
||||
logger.info("[1/3] 检查 MySQL 连接...");
|
||||
if (connectionHealthChecker.checkMySQL()) {
|
||||
logger.info("MySQL 连接检查通过");
|
||||
} else {
|
||||
logger.error("MySQL 连接检查失败");
|
||||
allSuccess = false;
|
||||
}
|
||||
|
||||
logger.info("");
|
||||
logger.info("[2/3] 检查 RabbitMQ 连接...");
|
||||
if (connectionHealthChecker.checkRabbitMQ()) {
|
||||
logger.info("RabbitMQ 连接检查通过");
|
||||
} else {
|
||||
logger.error("RabbitMQ 连接检查失败");
|
||||
allSuccess = false;
|
||||
}
|
||||
|
||||
logger.info("");
|
||||
logger.info("[3/3] 检查 Nacos 连接...");
|
||||
if (connectionHealthChecker.checkNacos()) {
|
||||
logger.info("Nacos 连接检查通过");
|
||||
} else {
|
||||
logger.error("Nacos 连接检查失败");
|
||||
allSuccess = false;
|
||||
}
|
||||
|
||||
try {
|
||||
messageChannelService.bootstrapMockChannelsIfNecessary();
|
||||
messageChannelService.runStartupHealthChecks();
|
||||
logger.info("消息通道初始化与健康检查完成");
|
||||
} catch (Exception exception) {
|
||||
logger.warn("消息通道初始化或健康检查失败: {}", exception.getMessage());
|
||||
}
|
||||
|
||||
logger.info("");
|
||||
logger.info("========================================");
|
||||
if (allSuccess) {
|
||||
logger.info("基础依赖连接检查完成,状态:全部成功");
|
||||
logger.info("MessageHub 服务已就绪");
|
||||
} else {
|
||||
logger.error("部分基础依赖连接检查失败,请检查日志与配置");
|
||||
}
|
||||
logger.info("========================================");
|
||||
}
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
package com.xiaowang.messagehub.listener;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.rabbitmq.client.Channel;
|
||||
import com.xiaowang.messagehub.config.RabbitMQConfig;
|
||||
import com.xiaowang.messagehub.dto.EmailMessageDTO;
|
||||
import com.xiaowang.messagehub.service.impl.MessageHandleService;
|
||||
import com.xiaowang.messagehub.service.ingress.MessageDispatchService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.core.Message;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class EmailQueueListener {
|
||||
|
||||
private final MessageHandleService messageHandleService;
|
||||
private final MessageDispatchService messageDispatchService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
|
||||
public EmailQueueListener(MessageHandleService messageHandleService,
|
||||
MessageDispatchService messageDispatchService,
|
||||
ObjectMapper objectMapper,
|
||||
RabbitTemplate rabbitTemplate) {
|
||||
this.messageHandleService = messageHandleService;
|
||||
this.messageDispatchService = messageDispatchService;
|
||||
this.objectMapper = objectMapper;
|
||||
this.rabbitTemplate = rabbitTemplate;
|
||||
}
|
||||
|
||||
@RabbitListener(queues = "emailQueue", containerFactory = "manualAckRabbitListenerContainerFactory")
|
||||
public void handleEmailMessage(Message message, Channel channel) {
|
||||
String messageId = message.getMessageProperties().getMessageId();
|
||||
LocalDateTime sendTime = LocalDateTime.now();
|
||||
long deliveryTag = message.getMessageProperties().getDeliveryTag();
|
||||
|
||||
try {
|
||||
String messageBody = new String(message.getBody(), StandardCharsets.UTF_8);
|
||||
log.info("收到邮件消息, messageId: {}, body: {}", messageId, messageBody);
|
||||
|
||||
EmailMessageDTO messageDTO = objectMapper.readValue(messageBody, EmailMessageDTO.class);
|
||||
MessageDispatchService.DispatchOutcome outcome =
|
||||
messageDispatchService.dispatch(messageDTO, messageId, messageBody);
|
||||
if (!outcome.processed()) {
|
||||
log.warn("Legacy email message skipped, messageId: {}, reason: {}", messageId, outcome.reason());
|
||||
acknowledge(channel, deliveryTag);
|
||||
return;
|
||||
}
|
||||
|
||||
log.info("邮件消息处理完成, messageId: {}, receiver: {}", messageId, messageDTO.getReceiver());
|
||||
acknowledge(channel, deliveryTag);
|
||||
} catch (JsonProcessingException exception) {
|
||||
log.error("邮件消息解析失败,消息ID: {}", messageId, exception);
|
||||
messageHandleService.markMessageRejected(messageId, "EMAIL", sendTime, "消息体解析失败: " + exception.getOriginalMessage());
|
||||
reject(channel, deliveryTag);
|
||||
} catch (Exception exception) {
|
||||
log.error("处理邮件消息时发生异常,消息ID: {}", messageId, exception);
|
||||
MessageHandleService.MessageRetryDecision retryDecision =
|
||||
messageHandleService.recordSendFailure(messageId, "EMAIL", sendTime, exception);
|
||||
if (retryDecision.shouldRetry()) {
|
||||
log.warn("邮件消息准备重试,messageId: {}, retryCount: {}, reason: {}",
|
||||
messageId, retryDecision.retryCount(), retryDecision.failReason());
|
||||
requeue(channel, deliveryTag);
|
||||
return;
|
||||
}
|
||||
|
||||
messageHandleService.markMessageRejected(messageId, "EMAIL", sendTime, retryDecision.failReason());
|
||||
publishDeadLetter(message, RabbitMQConfig.EMAIL_DEAD_LETTER_ROUTING_KEY, retryDecision.failReason());
|
||||
acknowledge(channel, deliveryTag);
|
||||
}
|
||||
}
|
||||
|
||||
private void acknowledge(Channel channel, long deliveryTag) {
|
||||
try {
|
||||
channel.basicAck(deliveryTag, false);
|
||||
} catch (Exception ackException) {
|
||||
log.error("邮件消息确认失败", ackException);
|
||||
}
|
||||
}
|
||||
|
||||
private void requeue(Channel channel, long deliveryTag) {
|
||||
try {
|
||||
channel.basicNack(deliveryTag, false, true);
|
||||
} catch (Exception nackException) {
|
||||
log.error("邮件消息重新入队失败", nackException);
|
||||
}
|
||||
}
|
||||
|
||||
private void reject(Channel channel, long deliveryTag) {
|
||||
try {
|
||||
channel.basicReject(deliveryTag, false);
|
||||
} catch (Exception rejectException) {
|
||||
log.error("邮件消息拒绝失败", rejectException);
|
||||
}
|
||||
}
|
||||
|
||||
private void publishDeadLetter(Message message, String routingKey, String reason) {
|
||||
try {
|
||||
message.getMessageProperties().setHeader("x-messagehub-dead-letter-reason", reason);
|
||||
rabbitTemplate.send(RabbitMQConfig.DEAD_LETTER_EXCHANGE, routingKey, message);
|
||||
} catch (Exception exception) {
|
||||
log.error("邮件消息投递死信队列失败", exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
-158
@@ -1,158 +0,0 @@
|
||||
package com.xiaowang.messagehub.listener;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.rabbitmq.client.Channel;
|
||||
import com.xiaowang.messagehub.config.RabbitMQConfig;
|
||||
import com.xiaowang.messagehub.dto.MessageDTO;
|
||||
import com.xiaowang.messagehub.dto.api.MessageIngressEnvelope;
|
||||
import com.xiaowang.messagehub.service.impl.MessageHandleService;
|
||||
import com.xiaowang.messagehub.service.ingress.MessageDispatchService;
|
||||
import com.xiaowang.messagehub.service.ingress.MessageIngressEnvelopeMapper;
|
||||
import com.xiaowang.messagehub.service.source.MessageSourceSystemService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.core.Message;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class MessageIngressQueueListener {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final MessageIngressEnvelopeMapper envelopeMapper;
|
||||
private final MessageSourceSystemService sourceSystemService;
|
||||
private final MessageDispatchService messageDispatchService;
|
||||
private final MessageHandleService messageHandleService;
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
|
||||
public MessageIngressQueueListener(ObjectMapper objectMapper,
|
||||
MessageIngressEnvelopeMapper envelopeMapper,
|
||||
MessageSourceSystemService sourceSystemService,
|
||||
MessageDispatchService messageDispatchService,
|
||||
MessageHandleService messageHandleService,
|
||||
RabbitTemplate rabbitTemplate) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.envelopeMapper = envelopeMapper;
|
||||
this.sourceSystemService = sourceSystemService;
|
||||
this.messageDispatchService = messageDispatchService;
|
||||
this.messageHandleService = messageHandleService;
|
||||
this.rabbitTemplate = rabbitTemplate;
|
||||
}
|
||||
|
||||
@RabbitListener(queues = RabbitMQConfig.INGRESS_QUEUE, containerFactory = "manualAckRabbitListenerContainerFactory")
|
||||
public void handleIngressMessage(Message message, Channel channel) {
|
||||
String headerMessageId = message.getMessageProperties().getMessageId();
|
||||
LocalDateTime sendTime = LocalDateTime.now();
|
||||
long deliveryTag = message.getMessageProperties().getDeliveryTag();
|
||||
MessageIngressEnvelope envelope = null;
|
||||
boolean reservationValidated = false;
|
||||
|
||||
try {
|
||||
String messageBody = new String(message.getBody(), StandardCharsets.UTF_8);
|
||||
envelope = objectMapper.readValue(messageBody, MessageIngressEnvelope.class);
|
||||
String accessToken = readAccessToken(message);
|
||||
sourceSystemService.authenticateSourceSystem(envelope.getSourceSystem(), accessToken);
|
||||
messageHandleService.requireIngressReservation(envelope.getMessageId(), envelope.getSourceSystem());
|
||||
reservationValidated = true;
|
||||
sourceSystemService.requirePlatformPermission(envelope.getSourceSystem(), envelope.getPlatform());
|
||||
|
||||
MessageDTO messageDTO = envelopeMapper.toMessageDTO(envelope);
|
||||
MessageDispatchService.DispatchOutcome outcome =
|
||||
messageDispatchService.dispatch(messageDTO, envelope.getMessageId(), messageBody);
|
||||
if (!outcome.processed()) {
|
||||
log.warn("Ingress message skipped, messageId: {}, reason: {}", envelope.getMessageId(), outcome.reason());
|
||||
}
|
||||
acknowledge(channel, deliveryTag);
|
||||
} catch (JsonProcessingException exception) {
|
||||
String reason = "Ingress message body parse failed: " + exception.getOriginalMessage();
|
||||
log.error(reason, exception);
|
||||
publishDeadLetter(message, reason);
|
||||
acknowledge(channel, deliveryTag);
|
||||
} catch (IllegalArgumentException exception) {
|
||||
String messageId = resolveMessageId(envelope, headerMessageId);
|
||||
String platform = resolvePlatform(envelope);
|
||||
log.error("Ingress message rejected, messageId: {}, reason: {}", messageId, exception.getMessage());
|
||||
if (reservationValidated) {
|
||||
markRejectedIfPossible(messageId, platform, sendTime, exception.getMessage());
|
||||
}
|
||||
publishDeadLetter(message, exception.getMessage());
|
||||
acknowledge(channel, deliveryTag);
|
||||
} catch (Exception exception) {
|
||||
String messageId = resolveMessageId(envelope, headerMessageId);
|
||||
String platform = resolvePlatform(envelope);
|
||||
log.error("Ingress message handling failed, messageId: {}", messageId, exception);
|
||||
MessageHandleService.MessageRetryDecision retryDecision =
|
||||
messageHandleService.recordSendFailure(messageId, platform, sendTime, exception);
|
||||
if (retryDecision.shouldRetry()) {
|
||||
log.warn("Ingress message will retry, messageId: {}, retryCount: {}, reason: {}",
|
||||
messageId, retryDecision.retryCount(), retryDecision.failReason());
|
||||
requeue(channel, deliveryTag);
|
||||
return;
|
||||
}
|
||||
|
||||
messageHandleService.markMessageRejected(messageId, platform, sendTime, retryDecision.failReason());
|
||||
publishDeadLetter(message, retryDecision.failReason());
|
||||
acknowledge(channel, deliveryTag);
|
||||
}
|
||||
}
|
||||
|
||||
private String readAccessToken(Message message) {
|
||||
Object value = message.getMessageProperties().getHeaders().get(MessageSourceSystemService.ACCESS_TOKEN_HEADER);
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
return String.valueOf(value);
|
||||
}
|
||||
|
||||
private String resolveMessageId(MessageIngressEnvelope envelope, String headerMessageId) {
|
||||
if (envelope != null && StringUtils.hasText(envelope.getMessageId())) {
|
||||
return envelope.getMessageId();
|
||||
}
|
||||
return headerMessageId;
|
||||
}
|
||||
|
||||
private String resolvePlatform(MessageIngressEnvelope envelope) {
|
||||
if (envelope != null && StringUtils.hasText(envelope.getPlatform())) {
|
||||
return envelope.getPlatform();
|
||||
}
|
||||
return "UNKNOWN";
|
||||
}
|
||||
|
||||
private void markRejectedIfPossible(String messageId, String platform, LocalDateTime sendTime, String reason) {
|
||||
if (!StringUtils.hasText(messageId)) {
|
||||
return;
|
||||
}
|
||||
messageHandleService.markMessageRejected(messageId, platform, sendTime, reason);
|
||||
}
|
||||
|
||||
private void acknowledge(Channel channel, long deliveryTag) {
|
||||
try {
|
||||
channel.basicAck(deliveryTag, false);
|
||||
} catch (Exception ackException) {
|
||||
log.error("Ingress message ack failed", ackException);
|
||||
}
|
||||
}
|
||||
|
||||
private void requeue(Channel channel, long deliveryTag) {
|
||||
try {
|
||||
channel.basicNack(deliveryTag, false, true);
|
||||
} catch (Exception nackException) {
|
||||
log.error("Ingress message requeue failed", nackException);
|
||||
}
|
||||
}
|
||||
|
||||
private void publishDeadLetter(Message message, String reason) {
|
||||
try {
|
||||
message.getMessageProperties().setHeader("x-messagehub-dead-letter-reason", reason);
|
||||
rabbitTemplate.send(RabbitMQConfig.DEAD_LETTER_EXCHANGE, RabbitMQConfig.INGRESS_DEAD_LETTER_ROUTING_KEY, message);
|
||||
} catch (Exception exception) {
|
||||
log.error("Ingress message dead-letter publish failed", exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
package com.xiaowang.messagehub.listener;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.rabbitmq.client.Channel;
|
||||
import com.xiaowang.messagehub.config.RabbitMQConfig;
|
||||
import com.xiaowang.messagehub.dto.QqMessageDTO;
|
||||
import com.xiaowang.messagehub.service.impl.MessageHandleService;
|
||||
import com.xiaowang.messagehub.service.ingress.MessageDispatchService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.core.Message;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class QqQueueListener {
|
||||
|
||||
private final MessageHandleService messageHandleService;
|
||||
private final MessageDispatchService messageDispatchService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
|
||||
public QqQueueListener(MessageHandleService messageHandleService,
|
||||
MessageDispatchService messageDispatchService,
|
||||
ObjectMapper objectMapper,
|
||||
RabbitTemplate rabbitTemplate) {
|
||||
this.messageHandleService = messageHandleService;
|
||||
this.messageDispatchService = messageDispatchService;
|
||||
this.objectMapper = objectMapper;
|
||||
this.rabbitTemplate = rabbitTemplate;
|
||||
}
|
||||
|
||||
@RabbitListener(queues = "qqQueue", containerFactory = "manualAckRabbitListenerContainerFactory")
|
||||
public void handleQqMessage(Message message, Channel channel) {
|
||||
String messageId = message.getMessageProperties().getMessageId();
|
||||
LocalDateTime sendTime = LocalDateTime.now();
|
||||
long deliveryTag = message.getMessageProperties().getDeliveryTag();
|
||||
|
||||
try {
|
||||
String messageBody = new String(message.getBody(), StandardCharsets.UTF_8);
|
||||
log.info("Received QQ message, messageId: {}, body: {}", messageId, messageBody);
|
||||
|
||||
QqMessageDTO messageDTO = objectMapper.readValue(messageBody, QqMessageDTO.class);
|
||||
MessageDispatchService.DispatchOutcome outcome =
|
||||
messageDispatchService.dispatch(messageDTO, messageId, messageBody);
|
||||
if (!outcome.processed()) {
|
||||
log.warn("Legacy QQ message skipped, messageId: {}, reason: {}", messageId, outcome.reason());
|
||||
acknowledge(channel, deliveryTag);
|
||||
return;
|
||||
}
|
||||
|
||||
log.info("QQ message handled, messageId: {}, receiver: {}", messageId, messageDTO.getReceiver());
|
||||
acknowledge(channel, deliveryTag);
|
||||
} catch (JsonProcessingException exception) {
|
||||
log.error("QQ message JSON parse failed, messageId: {}", messageId, exception);
|
||||
messageHandleService.markMessageRejected(messageId, "QQ", sendTime, "Message body parse failed: " + exception.getOriginalMessage());
|
||||
reject(channel, deliveryTag);
|
||||
} catch (Exception exception) {
|
||||
log.error("QQ message handling failed, messageId: {}", messageId, exception);
|
||||
MessageHandleService.MessageRetryDecision retryDecision =
|
||||
messageHandleService.recordSendFailure(messageId, "QQ", sendTime, exception);
|
||||
if (retryDecision.shouldRetry()) {
|
||||
log.warn("QQ message will retry, messageId: {}, retryCount: {}, reason: {}",
|
||||
messageId, retryDecision.retryCount(), retryDecision.failReason());
|
||||
requeue(channel, deliveryTag);
|
||||
return;
|
||||
}
|
||||
|
||||
messageHandleService.markMessageRejected(messageId, "QQ", sendTime, retryDecision.failReason());
|
||||
publishDeadLetter(message, RabbitMQConfig.QQ_DEAD_LETTER_ROUTING_KEY, retryDecision.failReason());
|
||||
acknowledge(channel, deliveryTag);
|
||||
}
|
||||
}
|
||||
|
||||
private void acknowledge(Channel channel, long deliveryTag) {
|
||||
try {
|
||||
channel.basicAck(deliveryTag, false);
|
||||
} catch (Exception ackException) {
|
||||
log.error("QQ message ack failed", ackException);
|
||||
}
|
||||
}
|
||||
|
||||
private void requeue(Channel channel, long deliveryTag) {
|
||||
try {
|
||||
channel.basicNack(deliveryTag, false, true);
|
||||
} catch (Exception nackException) {
|
||||
log.error("QQ message requeue failed", nackException);
|
||||
}
|
||||
}
|
||||
|
||||
private void reject(Channel channel, long deliveryTag) {
|
||||
try {
|
||||
channel.basicReject(deliveryTag, false);
|
||||
} catch (Exception rejectException) {
|
||||
log.error("QQ message reject failed", rejectException);
|
||||
}
|
||||
}
|
||||
|
||||
private void publishDeadLetter(Message message, String routingKey, String reason) {
|
||||
try {
|
||||
message.getMessageProperties().setHeader("x-messagehub-dead-letter-reason", reason);
|
||||
rabbitTemplate.send(RabbitMQConfig.DEAD_LETTER_EXCHANGE, routingKey, message);
|
||||
} catch (Exception exception) {
|
||||
log.error("QQ message dead-letter publish failed", exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
package com.xiaowang.messagehub.listener;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.rabbitmq.client.Channel;
|
||||
import com.xiaowang.messagehub.config.RabbitMQConfig;
|
||||
import com.xiaowang.messagehub.dto.SmsMessageDTO;
|
||||
import com.xiaowang.messagehub.service.SmsSendService;
|
||||
import com.xiaowang.messagehub.service.impl.MessageHandleService;
|
||||
import com.xiaowang.messagehub.service.ingress.MessageDispatchService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.amqp.core.Message;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Component
|
||||
public class SmsQueueListener {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(SmsQueueListener.class);
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final SmsSendService smsSendService;
|
||||
private final MessageHandleService messageHandleService;
|
||||
private final MessageDispatchService messageDispatchService;
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
|
||||
public SmsQueueListener(ObjectMapper objectMapper,
|
||||
SmsSendService smsSendService,
|
||||
MessageHandleService messageHandleService,
|
||||
MessageDispatchService messageDispatchService,
|
||||
RabbitTemplate rabbitTemplate) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.smsSendService = smsSendService;
|
||||
this.messageHandleService = messageHandleService;
|
||||
this.messageDispatchService = messageDispatchService;
|
||||
this.rabbitTemplate = rabbitTemplate;
|
||||
}
|
||||
|
||||
@RabbitListener(queues = "smsQueue", containerFactory = "manualAckRabbitListenerContainerFactory")
|
||||
public void handleSmsMessage(Message message, Channel channel) {
|
||||
String messageId = message.getMessageProperties().getMessageId();
|
||||
LocalDateTime sendTime = LocalDateTime.now();
|
||||
long deliveryTag = message.getMessageProperties().getDeliveryTag();
|
||||
|
||||
try {
|
||||
String messageBody = new String(message.getBody(), StandardCharsets.UTF_8);
|
||||
logger.info("========================================");
|
||||
logger.info("收到短信消息");
|
||||
logger.info("消息ID: {}", messageId);
|
||||
logger.info("消息内容: {}", messageBody);
|
||||
logger.info("========================================");
|
||||
|
||||
SmsMessageDTO smsMessageDTO = objectMapper.readValue(messageBody, SmsMessageDTO.class);
|
||||
MessageDispatchService.DispatchOutcome outcome =
|
||||
messageDispatchService.dispatch(smsMessageDTO, messageId, messageBody);
|
||||
if (!outcome.processed()) {
|
||||
logger.warn("Legacy SMS message skipped, messageId: {}, reason: {}", messageId, outcome.reason());
|
||||
acknowledge(channel, deliveryTag);
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info("========================================");
|
||||
logger.info("短信消息处理完成");
|
||||
logger.info("消息ID: {}", messageId);
|
||||
logger.info("手机号码: {}", smsMessageDTO.getReceiver());
|
||||
logger.info("发送方式: {}", smsMessageDTO.getSendMethod());
|
||||
logger.info("========================================");
|
||||
acknowledge(channel, deliveryTag);
|
||||
} catch (JsonProcessingException exception) {
|
||||
logger.error("短信消息解析失败,消息ID: {}", messageId, exception);
|
||||
messageHandleService.markMessageRejected(messageId, "SMS", sendTime, "消息体解析失败: " + exception.getOriginalMessage());
|
||||
reject(channel, deliveryTag);
|
||||
} catch (Exception exception) {
|
||||
logger.error("处理短信消息时发生异常,消息ID: {}", messageId, exception);
|
||||
MessageHandleService.MessageRetryDecision retryDecision =
|
||||
messageHandleService.recordSendFailure(messageId, "SMS", sendTime, exception);
|
||||
if (retryDecision.shouldRetry()) {
|
||||
logger.warn("短信消息准备重试,messageId: {}, retryCount: {}, reason: {}",
|
||||
messageId, retryDecision.retryCount(), retryDecision.failReason());
|
||||
requeue(channel, deliveryTag);
|
||||
return;
|
||||
}
|
||||
|
||||
messageHandleService.markMessageRejected(messageId, "SMS", sendTime, retryDecision.failReason());
|
||||
publishDeadLetter(message, RabbitMQConfig.SMS_DEAD_LETTER_ROUTING_KEY, retryDecision.failReason());
|
||||
acknowledge(channel, deliveryTag);
|
||||
}
|
||||
}
|
||||
|
||||
private void acknowledge(Channel channel, long deliveryTag) {
|
||||
try {
|
||||
channel.basicAck(deliveryTag, false);
|
||||
} catch (Exception ackException) {
|
||||
logger.error("短信消息确认失败", ackException);
|
||||
}
|
||||
}
|
||||
|
||||
private void requeue(Channel channel, long deliveryTag) {
|
||||
try {
|
||||
channel.basicNack(deliveryTag, false, true);
|
||||
} catch (Exception nackException) {
|
||||
logger.error("短信消息重新入队失败", nackException);
|
||||
}
|
||||
}
|
||||
|
||||
private void reject(Channel channel, long deliveryTag) {
|
||||
try {
|
||||
channel.basicReject(deliveryTag, false);
|
||||
} catch (Exception rejectException) {
|
||||
logger.error("短信消息拒绝失败", rejectException);
|
||||
}
|
||||
}
|
||||
|
||||
private void publishDeadLetter(Message message, String routingKey, String reason) {
|
||||
try {
|
||||
message.getMessageProperties().setHeader("x-messagehub-dead-letter-reason", reason);
|
||||
rabbitTemplate.send(RabbitMQConfig.DEAD_LETTER_EXCHANGE, routingKey, message);
|
||||
} catch (Exception exception) {
|
||||
logger.error("短信消息投递死信队列失败", exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.xiaowang.messagehub.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.messagehub.entity.EmailAttachmentDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface EmailAttachmentMapper extends BaseMapper<EmailAttachmentDO> {
|
||||
}
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
package com.xiaowang.messagehub.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.messagehub.entity.EmailAttachmentPolicyDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface EmailAttachmentPolicyMapper extends BaseMapper<EmailAttachmentPolicyDO> {
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.xiaowang.messagehub.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.messagehub.entity.EmailTemplateDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface EmailTemplateMapper extends BaseMapper<EmailTemplateDO> {
|
||||
|
||||
@Select("SELECT * FROM email_template WHERE template_code = #{templateCode} LIMIT 1")
|
||||
EmailTemplateDO selectByTemplateCode(@Param("templateCode") String templateCode);
|
||||
|
||||
@Select("SELECT * FROM email_template ORDER BY create_time DESC")
|
||||
List<EmailTemplateDO> selectAllTemplates();
|
||||
|
||||
@Select("SELECT * FROM email_template WHERE is_enable = 1 ORDER BY create_time DESC")
|
||||
List<EmailTemplateDO> selectEnabledTemplates();
|
||||
}
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
package com.xiaowang.messagehub.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.messagehub.entity.MessageChannelConfigDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface MessageChannelConfigMapper extends BaseMapper<MessageChannelConfigDO> {
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
package com.xiaowang.messagehub.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.xiaowang.messagehub.entity.MessageDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import org.apache.ibatis.annotations.Update;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 消息Mapper接口
|
||||
* 继承BaseMapper,提供MessageDO的基础数据库操作
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@Mapper // MyBatis-Plus的注解,标记为Mapper接口
|
||||
public interface MessageMapper extends BaseMapper<MessageDO> { // 继承BaseMapper,获得基础CRUD功能
|
||||
|
||||
/**
|
||||
* 根据主题分页查询消息
|
||||
* @param topic 主题名称
|
||||
* @param limit 限制返回的记录数
|
||||
* @return 消息列表
|
||||
*/
|
||||
@Select("SELECT * FROM message WHERE topic = #{topic} AND deleted = 0 ORDER BY create_time DESC LIMIT #{limit}")
|
||||
List<MessageDO> selectByTopicWithLimit(@Param("topic") String topic, @Param("limit") int limit);
|
||||
|
||||
/**
|
||||
* 根据状态分页查询消息
|
||||
* @param status 消息状态
|
||||
* @param limit 限制返回的记录数
|
||||
* @return 消息列表
|
||||
*/
|
||||
@Select("SELECT * FROM message WHERE status = #{status} AND deleted = 0 ORDER BY create_time DESC LIMIT #{limit}")
|
||||
List<MessageDO> selectByStatusWithLimit(@Param("status") Integer status, @Param("limit") int limit);
|
||||
|
||||
/**
|
||||
* 根据主题和状态查询消息
|
||||
* @param topic 主题名称
|
||||
* @param status 消息状态
|
||||
* @return 消息列表
|
||||
*/
|
||||
@Select("SELECT * FROM message WHERE topic = #{topic} AND status = #{status} AND deleted = 0 ORDER BY create_time DESC")
|
||||
List<MessageDO> selectByTopicAndStatus(@Param("topic") String topic, @Param("status") Integer status);
|
||||
|
||||
/**
|
||||
* 批量更新消息状态
|
||||
* @param ids 消息ID集合,用逗号分隔
|
||||
* @param status 新的状态
|
||||
* @param updateTime 更新时间
|
||||
* @return 更新的记录数
|
||||
*/
|
||||
@Update("UPDATE message SET status = #{status}, update_time = #{updateTime} WHERE id IN (${ids}) AND deleted = 0")
|
||||
int batchUpdateStatus(@Param("ids") String ids, @Param("status") Integer status, @Param("updateTime") LocalDateTime updateTime);
|
||||
|
||||
/**
|
||||
* 统计指定主题的消息数量
|
||||
* @param topic 主题名称
|
||||
* @return 消息数量
|
||||
*/
|
||||
@Select("SELECT COUNT(*) FROM message WHERE topic = #{topic} AND deleted = 0")
|
||||
long countByTopic(@Param("topic") String topic);
|
||||
|
||||
/**
|
||||
* 统计指定状态的消息数量
|
||||
* @param status 消息状态
|
||||
* @return 消息数量
|
||||
*/
|
||||
@Select("SELECT COUNT(*) FROM message WHERE status = #{status} AND deleted = 0")
|
||||
long countByStatus(@Param("status") Integer status);
|
||||
|
||||
/**
|
||||
* 分页查询所有消息
|
||||
* @param page 分页参数
|
||||
* @return 分页结果
|
||||
*/
|
||||
@Select("SELECT * FROM message WHERE deleted = 0 ORDER BY create_time DESC")
|
||||
IPage<MessageDO> selectPage(Page<MessageDO> page);
|
||||
|
||||
/**
|
||||
* 根据主题分页查询消息
|
||||
* @param page 分页参数
|
||||
* @param topic 主题名称
|
||||
* @return 分页结果
|
||||
*/
|
||||
@Select("SELECT * FROM message WHERE topic = #{topic} AND deleted = 0 ORDER BY create_time DESC")
|
||||
IPage<MessageDO> selectPageByTopic(Page<MessageDO> page, @Param("topic") String topic);
|
||||
|
||||
/**
|
||||
* 根据时间范围查询消息
|
||||
* @param startTime 开始时间
|
||||
* @param endTime 结束时间
|
||||
* @return 消息列表
|
||||
*/
|
||||
@Select("SELECT * FROM message WHERE create_time >= #{startTime} AND create_time <= #{endTime} AND deleted = 0 ORDER BY create_time DESC")
|
||||
List<MessageDO> selectByTimeRange(@Param("startTime") LocalDateTime startTime, @Param("endTime") LocalDateTime endTime);
|
||||
|
||||
/**
|
||||
* 根据内容关键词搜索消息
|
||||
* @param keyword 搜索关键词
|
||||
* @param limit 限制返回的记录数
|
||||
* @return 匹配的消息列表
|
||||
*/
|
||||
@Select("SELECT * FROM message WHERE content LIKE CONCAT('%', #{keyword}, '%') AND deleted = 0 ORDER BY create_time DESC LIMIT #{limit}")
|
||||
List<MessageDO> searchByContent(@Param("keyword") String keyword, @Param("limit") int limit);
|
||||
}
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
package com.xiaowang.messagehub.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.messagehub.entity.MessageSourceSystemChannelDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface MessageSourceSystemChannelMapper extends BaseMapper<MessageSourceSystemChannelDO> {
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.xiaowang.messagehub.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.messagehub.entity.MessageSourceSystemDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface MessageSourceSystemMapper extends BaseMapper<MessageSourceSystemDO> {
|
||||
}
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
package com.xiaowang.messagehub.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.xiaowang.messagehub.entity.MessageSourceSystemPermissionDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface MessageSourceSystemPermissionMapper extends BaseMapper<MessageSourceSystemPermissionDO> {
|
||||
}
|
||||
@@ -1,164 +0,0 @@
|
||||
package com.xiaowang.messagehub.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.xiaowang.messagehub.entity.PushLogDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import org.apache.ibatis.annotations.Update;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 推送日志Mapper接口
|
||||
* 该接口继承BaseMapper,提供了对推送日志数据的基本操作方法
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@Mapper // MyBatis-Plus的注解,表示这是一个Mapper接口
|
||||
public interface PushLogMapper extends BaseMapper<PushLogDO> {
|
||||
|
||||
/**
|
||||
* 根据来源系统查询推送日志,并限制返回结果数量
|
||||
* @param sourceSystem 来源系统名称
|
||||
* @param limit 限制返回的记录数
|
||||
* @return 推送日志列表
|
||||
*/
|
||||
@Select("SELECT * FROM push_log WHERE source_system = #{sourceSystem} ORDER BY create_time DESC LIMIT #{limit}")
|
||||
List<PushLogDO> selectBySourceSystemWithLimit(@Param("sourceSystem") String sourceSystem, @Param("limit") int limit);
|
||||
|
||||
/**
|
||||
* 根据接收者查询推送日志,并限制返回结果数量
|
||||
* @param receiver 接收者
|
||||
* @param limit 限制返回的记录数
|
||||
* @return 推送日志列表
|
||||
*/
|
||||
@Select("SELECT * FROM push_log WHERE receiver = #{receiver} ORDER BY create_time DESC LIMIT #{limit}")
|
||||
List<PushLogDO> selectByReceiverWithLimit(@Param("receiver") String receiver, @Param("limit") int limit);
|
||||
|
||||
/**
|
||||
* 根据渠道类型查询推送日志,并限制返回结果数量
|
||||
* @param channelType 渠道类型
|
||||
* @param limit 限制返回的记录数
|
||||
* @return 推送日志列表
|
||||
*/
|
||||
@Select("SELECT * FROM push_log WHERE channel_type = #{channelType} ORDER BY create_time DESC LIMIT #{limit}")
|
||||
List<PushLogDO> selectByChannelTypeWithLimit(@Param("channelType") String channelType, @Param("limit") int limit);
|
||||
|
||||
/**
|
||||
* 根据状态查询推送日志,并限制返回结果数量
|
||||
* @param status 状态
|
||||
* @param limit 限制返回的记录数
|
||||
* @return 推送日志列表
|
||||
*/
|
||||
@Select("SELECT * FROM push_log WHERE status = #{status} ORDER BY create_time DESC LIMIT #{limit}")
|
||||
List<PushLogDO> selectByStatusWithLimit(@Param("status") Integer status, @Param("limit") int limit);
|
||||
|
||||
/**
|
||||
* 根据来源系统和状态查询推送日志
|
||||
* @param sourceSystem 来源系统名称
|
||||
* @param status 状态
|
||||
* @return 推送日志列表
|
||||
*/
|
||||
@Select("SELECT * FROM push_log WHERE source_system = #{sourceSystem} AND status = #{status} ORDER BY create_time DESC")
|
||||
List<PushLogDO> selectBySourceSystemAndStatus(@Param("sourceSystem") String sourceSystem, @Param("status") Integer status);
|
||||
|
||||
/**
|
||||
* 根据唯一ID查询推送日志
|
||||
* @param uniqueId 唯一标识符
|
||||
* @return 推送日志对象
|
||||
*/
|
||||
@Select("SELECT * FROM push_log WHERE unique_id = #{uniqueId} ORDER BY create_time DESC LIMIT 1")
|
||||
PushLogDO selectByUniqueId(@Param("uniqueId") String uniqueId);
|
||||
|
||||
@Select("SELECT * FROM push_log WHERE source_system = #{sourceSystem} AND unique_id = #{uniqueId} ORDER BY create_time DESC LIMIT 1")
|
||||
PushLogDO selectBySourceSystemAndUniqueId(@Param("sourceSystem") String sourceSystem, @Param("uniqueId") String uniqueId);
|
||||
|
||||
/**
|
||||
* 更新推送日志的重试状态
|
||||
* @param ID 日志ID
|
||||
* @param status 状态
|
||||
* @param failReason 失败原因
|
||||
* @return 更新的记录数
|
||||
*/
|
||||
@Update("UPDATE push_log SET status = #{status}, dispatch_status = #{dispatchStatus}, retry_count = retry_count + 1, fail_reason = #{failReason}, next_retry_time = #{nextRetryTime}, dead_letter_reason = #{deadLetterReason} WHERE id = #{id}")
|
||||
int updateRetryStatus(@Param("id") String id,
|
||||
@Param("status") Integer status,
|
||||
@Param("dispatchStatus") String dispatchStatus,
|
||||
@Param("failReason") String failReason,
|
||||
@Param("nextRetryTime") LocalDateTime nextRetryTime,
|
||||
@Param("deadLetterReason") String deadLetterReason);
|
||||
|
||||
/**
|
||||
* 更新推送日志的最终内容
|
||||
* @param id 日志ID
|
||||
* @param finalContent 最终内容
|
||||
* @return 更新的记录数
|
||||
*/
|
||||
@Update("UPDATE push_log SET final_content = #{finalContent} WHERE id = #{id}")
|
||||
int updateFinalContent(@Param("id") String id, @Param("finalContent") String finalContent);
|
||||
|
||||
/**
|
||||
* 更新推送日志的发送时间
|
||||
* @param id 日志ID
|
||||
* @param sendTime 发送时间
|
||||
* @return 更新的记录数
|
||||
*/
|
||||
@Update("UPDATE push_log SET send_time = #{sendTime} WHERE id = #{id}")
|
||||
int updateSendTime(@Param("id") String id, @Param("sendTime") LocalDateTime sendTime);
|
||||
|
||||
/**
|
||||
* 统计指定来源系统的推送日志数量
|
||||
* @param sourceSystem 来源系统名称
|
||||
* @return 日志数量
|
||||
*/
|
||||
@Select("SELECT COUNT(*) FROM push_log WHERE source_system = #{sourceSystem}")
|
||||
long countBySourceSystem(@Param("sourceSystem") String sourceSystem);
|
||||
|
||||
/**
|
||||
* 统计指定状态的推送日志数量
|
||||
* @param status 状态
|
||||
* @return 日志数量
|
||||
*/
|
||||
@Select("SELECT COUNT(*) FROM push_log WHERE status = #{status}")
|
||||
long countByStatus(@Param("status") Integer status);
|
||||
|
||||
/**
|
||||
* 分页查询推送日志
|
||||
* @param page 分页参数
|
||||
* @return 分页结果
|
||||
*/
|
||||
@Select("SELECT * FROM push_log ORDER BY create_time DESC")
|
||||
IPage<PushLogDO> selectPage(Page<PushLogDO> page);
|
||||
|
||||
/**
|
||||
* 根据来源系统分页查询推送日志
|
||||
* @param page 分页参数
|
||||
* @param sourceSystem 来源系统名称
|
||||
* @return 分页结果
|
||||
*/
|
||||
@Select("SELECT * FROM push_log WHERE source_system = #{sourceSystem} ORDER BY create_time DESC")
|
||||
IPage<PushLogDO> selectPageBySourceSystem(Page<PushLogDO> page, @Param("sourceSystem") String sourceSystem);
|
||||
|
||||
/**
|
||||
* 根据时间范围查询推送日志
|
||||
* @param startTime 开始时间
|
||||
* @param endTime 结束时间
|
||||
* @return 推送日志列表
|
||||
*/
|
||||
@Select("SELECT * FROM push_log WHERE create_time >= #{startTime} AND create_time <= #{endTime} ORDER BY create_time DESC")
|
||||
List<PushLogDO> selectByTimeRange(@Param("startTime") LocalDateTime startTime, @Param("endTime") LocalDateTime endTime);
|
||||
|
||||
/**
|
||||
* 根据关键词搜索推送日志内容
|
||||
* @param keyword 搜索关键词
|
||||
* @param limit 限制返回的记录数
|
||||
* @return 推送日志列表
|
||||
*/
|
||||
@Select("SELECT * FROM push_log WHERE final_content LIKE CONCAT('%', #{keyword}, '%') ORDER BY create_time DESC LIMIT #{limit}")
|
||||
List<PushLogDO> searchByContent(@Param("keyword") String keyword, @Param("limit") int limit);
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
package com.xiaowang.messagehub.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.xiaowang.messagehub.entity.PushTemplateDO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import org.apache.ibatis.annotations.Update;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 推送模板Mapper接口
|
||||
* 继承BaseMapper,提供基础的数据库操作能力
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@Mapper // MyBatis的注解,表示这是一个Mapper接口
|
||||
public interface PushTemplateMapper extends BaseMapper<PushTemplateDO> {
|
||||
|
||||
/**
|
||||
* 根据模板代码查询推送模板
|
||||
* @param templateCode 模板代码
|
||||
* @return 返回查找到的推送模板对象
|
||||
*/
|
||||
@Select("SELECT * FROM push_template WHERE template_code = #{templateCode}")
|
||||
PushTemplateDO selectByTemplateCode(@Param("templateCode") String templateCode);
|
||||
|
||||
/**
|
||||
* 根据渠道类型查询推送模板列表
|
||||
* 按创建时间降序排列
|
||||
* @param channelType 渠道类型
|
||||
* @return 返回指定渠道类型的推送模板列表
|
||||
*/
|
||||
@Select("SELECT * FROM push_template WHERE channel_type = #{channelType} ORDER BY create_time DESC")
|
||||
List<PushTemplateDO> selectByChannelType(@Param("channelType") String channelType);
|
||||
|
||||
/**
|
||||
* 查询所有启用的推送模板
|
||||
* 按创建时间降序排列
|
||||
* @return 返回启用的推送模板列表
|
||||
*/
|
||||
@Select("SELECT * FROM push_template WHERE is_enable = 1 ORDER BY create_time DESC")
|
||||
List<PushTemplateDO> selectEnabledTemplates();
|
||||
|
||||
/**
|
||||
* 根据渠道类型查询启用的推送模板
|
||||
* 按创建时间降序排列
|
||||
* @param channelType 渠道类型
|
||||
* @return 返回指定渠道类型且启用的推送模板列表
|
||||
*/
|
||||
@Select("SELECT * FROM push_template WHERE channel_type = #{channelType} AND is_enable = 1 ORDER BY create_time DESC")
|
||||
List<PushTemplateDO> selectEnabledByChannelType(@Param("channelType") String channelType);
|
||||
|
||||
/**
|
||||
* 更新推送模板的启用状态
|
||||
* @param id 模板ID
|
||||
* @param isEnable 启用状态(0:禁用,1:启用)
|
||||
* @return 返回受影响的行数
|
||||
*/
|
||||
@Update("UPDATE push_template SET is_enable = #{isEnable} WHERE id = #{id}")
|
||||
int updateEnableStatus(@Param("id") Long id, @Param("isEnable") Integer isEnable);
|
||||
|
||||
/**
|
||||
* 统计指定渠道类型的模板数量
|
||||
* @param channelType 渠道类型
|
||||
* @return 返回指定渠道类型的模板数量
|
||||
*/
|
||||
@Select("SELECT COUNT(*) FROM push_template WHERE channel_type = #{channelType}")
|
||||
long countByChannelType(@Param("channelType") String channelType);
|
||||
|
||||
/**
|
||||
* 统计已启用的模板数量
|
||||
* @return 返回已启用的模板数量
|
||||
*/
|
||||
@Select("SELECT COUNT(*) FROM push_template WHERE is_enable = 1")
|
||||
long countEnabledTemplates();
|
||||
|
||||
/**
|
||||
* 分页查询推送模板
|
||||
* 按创建时间降序排列
|
||||
* @param page 分页参数
|
||||
* @return 返回分页结果
|
||||
*/
|
||||
@Select("SELECT * FROM push_template ORDER BY create_time DESC")
|
||||
IPage<PushTemplateDO> selectPage(Page<PushTemplateDO> page);
|
||||
|
||||
/**
|
||||
* 根据渠道类型分页查询推送模板
|
||||
* 按创建时间降序排列
|
||||
* @param page 分页参数
|
||||
* @param channelType 渠道类型
|
||||
* @return 返回分页结果
|
||||
*/
|
||||
@Select("SELECT * FROM push_template WHERE channel_type = #{channelType} ORDER BY create_time DESC")
|
||||
IPage<PushTemplateDO> selectPageByChannelType(Page<PushTemplateDO> page, @Param("channelType") String channelType);
|
||||
|
||||
/**
|
||||
* 根据关键词搜索推送模板
|
||||
* 在模板名称和描述中搜索匹配的关键词
|
||||
* @param keyword 搜索关键词
|
||||
* @return 返回匹配的推送模板列表
|
||||
*/
|
||||
@Select("SELECT * FROM push_template WHERE template_name LIKE CONCAT('%', #{keyword}, '%') OR description LIKE CONCAT('%', #{keyword}, '%')")
|
||||
List<PushTemplateDO> searchByKeyword(@Param("keyword") String keyword);
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package com.xiaowang.messagehub.model;
|
||||
|
||||
import com.xiaowang.messagehub.enums.ChannelHealthStatusEnum;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class ChannelHealthCheckResult {
|
||||
|
||||
private String status;
|
||||
|
||||
private String message;
|
||||
|
||||
public static ChannelHealthCheckResult healthy(String message) {
|
||||
return new ChannelHealthCheckResult(ChannelHealthStatusEnum.HEALTHY.getCode(), message);
|
||||
}
|
||||
|
||||
public static ChannelHealthCheckResult unhealthy(String message) {
|
||||
return new ChannelHealthCheckResult(ChannelHealthStatusEnum.UNHEALTHY.getCode(), message);
|
||||
}
|
||||
|
||||
public static ChannelHealthCheckResult unknown(String message) {
|
||||
return new ChannelHealthCheckResult(ChannelHealthStatusEnum.UNKNOWN.getCode(), message);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package com.xiaowang.messagehub.model;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
public record EmailAttachmentResource(
|
||||
Long id,
|
||||
String originalFileName,
|
||||
String contentType,
|
||||
long fileSize,
|
||||
Path storagePath
|
||||
) {
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
package com.xiaowang.messagehub.model;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
public class EmailDispatchRequest {
|
||||
|
||||
private String receiver;
|
||||
|
||||
private String subject;
|
||||
|
||||
private String content;
|
||||
|
||||
private String bodyType;
|
||||
|
||||
private String emailTemplateCode;
|
||||
|
||||
private String legacyTemplateCode;
|
||||
|
||||
private Map<String, Object> templateParams = new LinkedHashMap<>();
|
||||
|
||||
private Long channelId;
|
||||
|
||||
private String sourceSystem;
|
||||
|
||||
private List<Long> attachmentIds = new ArrayList<>();
|
||||
|
||||
private List<EmailAttachmentResource> attachments = new ArrayList<>();
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.xiaowang.messagehub.model;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class EmailRenderResult {
|
||||
|
||||
private String subject;
|
||||
|
||||
private String content;
|
||||
|
||||
private String bodyType;
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
package com.xiaowang.messagehub.model;
|
||||
|
||||
import com.xiaowang.messagehub.entity.MessageChannelConfigDO;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
|
||||
public record ManagedChannelConfig(
|
||||
MessageChannelConfigDO entity,
|
||||
Map<String, Object> config,
|
||||
Map<String, Object> secretConfig
|
||||
) {
|
||||
|
||||
public ManagedChannelConfig {
|
||||
config = config == null ? Collections.emptyMap() : config;
|
||||
secretConfig = secretConfig == null ? Collections.emptyMap() : secretConfig;
|
||||
}
|
||||
|
||||
public String getStringConfig(String key) {
|
||||
Object value = config.get(key);
|
||||
return value == null ? null : String.valueOf(value).trim();
|
||||
}
|
||||
|
||||
public String getStringSecret(String key) {
|
||||
Object value = secretConfig.get(key);
|
||||
return value == null ? null : String.valueOf(value).trim();
|
||||
}
|
||||
|
||||
public boolean getBooleanConfig(String key, boolean defaultValue) {
|
||||
Object value = config.get(key);
|
||||
if (value == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
if (value instanceof Boolean booleanValue) {
|
||||
return booleanValue;
|
||||
}
|
||||
return Boolean.parseBoolean(String.valueOf(value));
|
||||
}
|
||||
|
||||
public int getIntConfig(String key, int defaultValue) {
|
||||
Object value = config.get(key);
|
||||
if (value == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
if (value instanceof Number number) {
|
||||
return number.intValue();
|
||||
}
|
||||
try {
|
||||
return Integer.parseInt(String.valueOf(value));
|
||||
} catch (NumberFormatException exception) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package com.xiaowang.messagehub.model;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
public class QqDispatchRequest {
|
||||
|
||||
private String receiver;
|
||||
|
||||
private String targetType;
|
||||
|
||||
private String content;
|
||||
|
||||
private String contentMode;
|
||||
|
||||
private String templateCode;
|
||||
|
||||
private Map<String, Object> templateParams = new LinkedHashMap<>();
|
||||
|
||||
private Long channelId;
|
||||
|
||||
private String sourceSystem;
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.xiaowang.messagehub.model;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class QqSendResult {
|
||||
|
||||
private String requestId;
|
||||
|
||||
private String messageId;
|
||||
|
||||
private String message;
|
||||
|
||||
private String rawResponse;
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.xiaowang.messagehub.model;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
public class SmsDispatchRequest {
|
||||
|
||||
private String receiver;
|
||||
|
||||
private String templateCode;
|
||||
|
||||
private String templateExternalId;
|
||||
|
||||
private String content;
|
||||
|
||||
private Long channelId;
|
||||
|
||||
private String sourceSystem;
|
||||
|
||||
private Map<String, Object> templateParams = new LinkedHashMap<>();
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
package com.xiaowang.messagehub.model;
|
||||
|
||||
public record SmsDispatchResult(ManagedChannelConfig channelConfig, SmsSendResult sendResult, String finalContent) {
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.xiaowang.messagehub.model;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class SmsSendResult {
|
||||
|
||||
private String requestId;
|
||||
|
||||
private String message;
|
||||
|
||||
private String rawResponse;
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package com.xiaowang.messagehub.service;
|
||||
|
||||
import com.xiaowang.messagehub.model.EmailDispatchRequest;
|
||||
import com.xiaowang.messagehub.model.ManagedChannelConfig;
|
||||
import com.xiaowang.messagehub.service.channel.MessageChannelService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class EmailSendService {
|
||||
|
||||
private final MessageChannelService messageChannelService;
|
||||
|
||||
public EmailSendService(MessageChannelService messageChannelService) {
|
||||
this.messageChannelService = messageChannelService;
|
||||
}
|
||||
|
||||
public void sendEmail(String to, String subject, String content) {
|
||||
sendEmail(to, subject, content, null);
|
||||
}
|
||||
|
||||
public void sendEmail(String to, String subject, String content, Long channelId) {
|
||||
log.info("Preparing email dispatch, receiver: {}, subject: {}, channelId: {}", to, subject, channelId);
|
||||
messageChannelService.sendEmail(to, subject, content, channelId);
|
||||
}
|
||||
|
||||
public void sendEmail(String to, String subject, String content, Long channelId, String sourceSystem) {
|
||||
log.info("Preparing email dispatch, receiver: {}, subject: {}, channelId: {}, sourceSystem: {}",
|
||||
to, subject, channelId, sourceSystem);
|
||||
messageChannelService.sendEmail(to, subject, content, channelId, sourceSystem);
|
||||
}
|
||||
|
||||
public ManagedChannelConfig sendEmail(EmailDispatchRequest request) {
|
||||
log.info("Preparing email dispatch, receiver: {}, subject: {}, channelId: {}, sourceSystem: {}, attachments: {}",
|
||||
request.getReceiver(),
|
||||
request.getSubject(),
|
||||
request.getChannelId(),
|
||||
request.getSourceSystem(),
|
||||
request.getAttachmentIds());
|
||||
return messageChannelService.sendEmail(request);
|
||||
}
|
||||
}
|
||||
@@ -1,233 +0,0 @@
|
||||
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.QqMessageDTO;
|
||||
import com.xiaowang.messagehub.dto.SmsMessageDTO;
|
||||
import com.xiaowang.messagehub.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.core.Message;
|
||||
import org.springframework.amqp.core.MessageBuilder;
|
||||
import org.springframework.amqp.core.MessageProperties;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* 消息生产者服务类
|
||||
* 使用 RabbitMQ 发送短信、邮件、微信和推送消息。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class MessageProducerService {
|
||||
|
||||
@Autowired
|
||||
private RabbitTemplate rabbitTemplate;
|
||||
|
||||
@Autowired
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@Autowired
|
||||
private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
|
||||
|
||||
/**
|
||||
* 发送短信消息。
|
||||
*/
|
||||
public void sendSmsMessage(SmsMessageDTO messageDTO) {
|
||||
try {
|
||||
String messageId = snowflakeIdGenerator.nextIdString();
|
||||
ensureUniqueId(messageDTO, 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,
|
||||
"sms." + messageDTO.getMsgType().toLowerCase(),
|
||||
message
|
||||
);
|
||||
|
||||
log.info("短信消息已发送到队列,消息ID: {}, 手机号: {}, 消息类型: {}",
|
||||
messageId, messageDTO.getReceiver(), messageDTO.getMsgType());
|
||||
} catch (Exception exception) {
|
||||
log.error("发送短信消息失败", exception);
|
||||
throw new RuntimeException("发送短信消息失败: " + exception.getMessage(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送邮件消息。
|
||||
*/
|
||||
public void sendEmailMessage(MessageDTO messageDTO) {
|
||||
try {
|
||||
String messageId = snowflakeIdGenerator.nextIdString();
|
||||
ensureUniqueId(messageDTO, 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 exception) {
|
||||
log.error("发送邮件消息失败", exception);
|
||||
throw new RuntimeException("发送邮件消息失败: " + exception.getMessage(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送 QQ 消息。
|
||||
*/
|
||||
public void sendQqMessage(QqMessageDTO messageDTO) {
|
||||
try {
|
||||
String messageId = snowflakeIdGenerator.nextIdString();
|
||||
ensureUniqueId(messageDTO, 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,
|
||||
"qq." + messageDTO.getMsgType().toLowerCase(),
|
||||
message
|
||||
);
|
||||
|
||||
log.info("QQ message sent to queue, messageId: {}, receiver: {}, msgType: {}",
|
||||
messageId, messageDTO.getReceiver(), messageDTO.getMsgType());
|
||||
} catch (Exception exception) {
|
||||
log.error("Failed to send QQ message", exception);
|
||||
throw new RuntimeException("Failed to send QQ message: " + exception.getMessage(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送微信消息。
|
||||
*/
|
||||
public void sendWeChatMessage(MessageDTO messageDTO) {
|
||||
try {
|
||||
String messageId = snowflakeIdGenerator.nextIdString();
|
||||
ensureUniqueId(messageDTO, 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 exception) {
|
||||
log.error("发送微信消息失败", exception);
|
||||
throw new RuntimeException("发送微信消息失败: " + exception.getMessage(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送推送消息。
|
||||
*/
|
||||
public void sendPushMessage(MessageDTO messageDTO) {
|
||||
try {
|
||||
String messageId = snowflakeIdGenerator.nextIdString();
|
||||
ensureUniqueId(messageDTO, 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 exception) {
|
||||
log.error("发送推送消息失败", exception);
|
||||
throw new RuntimeException("发送推送消息失败: " + exception.getMessage(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通用发送消息方法。
|
||||
*/
|
||||
public void sendMessage(MessageDTO messageDTO) {
|
||||
try {
|
||||
String messageId = snowflakeIdGenerator.nextIdString();
|
||||
ensureUniqueId(messageDTO, 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 ("QQ".equalsIgnoreCase(channelType)) {
|
||||
routingKey = "qq." + 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 exception) {
|
||||
log.error("发送消息失败", exception);
|
||||
throw new RuntimeException("发送消息失败: " + exception.getMessage(), exception);
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureUniqueId(MessageDTO messageDTO, String fallbackMessageId) {
|
||||
if (messageDTO != null && !StringUtils.hasText(messageDTO.getUniqueId())) {
|
||||
messageDTO.setUniqueId(fallbackMessageId);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package com.xiaowang.messagehub.service;
|
||||
|
||||
import com.xiaowang.messagehub.model.ManagedChannelConfig;
|
||||
import com.xiaowang.messagehub.model.QqDispatchRequest;
|
||||
import com.xiaowang.messagehub.model.QqSendResult;
|
||||
import com.xiaowang.messagehub.service.channel.MessageChannelService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class QqSendService {
|
||||
|
||||
private final MessageChannelService messageChannelService;
|
||||
|
||||
public QqSendService(MessageChannelService messageChannelService) {
|
||||
this.messageChannelService = messageChannelService;
|
||||
}
|
||||
|
||||
public QqDispatchResult sendQq(QqDispatchRequest request) {
|
||||
log.info("Preparing QQ dispatch, receiver: {}, targetType: {}, channelId: {}, sourceSystem: {}",
|
||||
request.getReceiver(),
|
||||
request.getTargetType(),
|
||||
request.getChannelId(),
|
||||
request.getSourceSystem());
|
||||
return messageChannelService.sendQq(request);
|
||||
}
|
||||
|
||||
public record QqDispatchResult(ManagedChannelConfig channelConfig, QqSendResult sendResult, String finalContent) {
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.xiaowang.messagehub.service;
|
||||
|
||||
import com.xiaowang.messagehub.dto.SmsMessageDTO;
|
||||
|
||||
/**
|
||||
* 短信发送服务接口
|
||||
* 该接口定义了短信发送服务所需的基本方法
|
||||
*/
|
||||
public interface SmsSendService {
|
||||
/**
|
||||
* 发送短信
|
||||
*
|
||||
* @param smsMessage 参数
|
||||
* @return 发送结果
|
||||
*/
|
||||
void sendSms(SmsMessageDTO smsMessage);
|
||||
}
|
||||
-80
@@ -1,80 +0,0 @@
|
||||
package com.xiaowang.messagehub.service.admin;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.xiaowang.messagehub.dto.admin.PushLogView;
|
||||
import com.xiaowang.messagehub.entity.PushLogDO;
|
||||
import com.xiaowang.messagehub.enums.DispatchStatusEnum;
|
||||
import com.xiaowang.messagehub.mapper.PushLogMapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class PushLogAdminService {
|
||||
|
||||
private final PushLogMapper pushLogMapper;
|
||||
|
||||
public PushLogAdminService(PushLogMapper pushLogMapper) {
|
||||
this.pushLogMapper = pushLogMapper;
|
||||
}
|
||||
|
||||
public List<PushLogView> listLogs(String sourceSystem,
|
||||
String channelType,
|
||||
Integer status,
|
||||
String keyword,
|
||||
Boolean deadLetter,
|
||||
int limit) {
|
||||
LambdaQueryWrapper<PushLogDO> wrapper = new LambdaQueryWrapper<>();
|
||||
if (StringUtils.hasText(sourceSystem)) {
|
||||
wrapper.eq(PushLogDO::getSourceSystem, sourceSystem.trim());
|
||||
}
|
||||
if (StringUtils.hasText(channelType)) {
|
||||
wrapper.eq(PushLogDO::getChannelType, channelType.trim().toUpperCase());
|
||||
}
|
||||
if (status != null) {
|
||||
wrapper.eq(PushLogDO::getStatus, status);
|
||||
}
|
||||
if (Boolean.TRUE.equals(deadLetter)) {
|
||||
wrapper.isNotNull(PushLogDO::getDeadLetterReason);
|
||||
}
|
||||
if (StringUtils.hasText(keyword)) {
|
||||
String value = keyword.trim();
|
||||
wrapper.and(item -> item.like(PushLogDO::getReceiver, value)
|
||||
.or()
|
||||
.like(PushLogDO::getUniqueId, value)
|
||||
.or()
|
||||
.like(PushLogDO::getTemplateCode, value)
|
||||
.or()
|
||||
.like(PushLogDO::getFailReason, value)
|
||||
.or()
|
||||
.like(PushLogDO::getDeadLetterReason, value));
|
||||
}
|
||||
wrapper.orderByDesc(PushLogDO::getCreateTime).last("LIMIT " + Math.max(1, Math.min(limit, 200)));
|
||||
return pushLogMapper.selectList(wrapper).stream().map(this::toView).toList();
|
||||
}
|
||||
|
||||
private PushLogView toView(PushLogDO entity) {
|
||||
PushLogView view = new PushLogView();
|
||||
view.setId(entity.getId());
|
||||
view.setSourceSystem(entity.getSourceSystem());
|
||||
view.setUniqueId(entity.getUniqueId());
|
||||
view.setReceiver(entity.getReceiver());
|
||||
view.setChannelType(entity.getChannelType());
|
||||
view.setChannelId(entity.getChannelId());
|
||||
view.setProviderCode(entity.getProviderCode());
|
||||
view.setMsgType(entity.getMsgType());
|
||||
view.setTemplateCode(entity.getTemplateCode());
|
||||
view.setFinalContent(entity.getFinalContent());
|
||||
view.setStatus(entity.getStatus());
|
||||
view.setDispatchStatus(DispatchStatusEnum.normalize(entity.getDispatchStatus(), entity.getStatus()));
|
||||
view.setRetryCount(entity.getRetryCount());
|
||||
view.setNextRetryTime(entity.getNextRetryTime());
|
||||
view.setFailReason(entity.getFailReason());
|
||||
view.setDeadLetterReason(entity.getDeadLetterReason());
|
||||
view.setSendTime(entity.getSendTime());
|
||||
view.setCreateTime(entity.getCreateTime());
|
||||
view.setUpdateTime(entity.getUpdateTime());
|
||||
return view;
|
||||
}
|
||||
}
|
||||
-148
@@ -1,148 +0,0 @@
|
||||
package com.xiaowang.messagehub.service.api;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.xiaowang.messagehub.dto.api.MessageIdReserveResponse;
|
||||
import com.xiaowang.messagehub.dto.api.MessageStatusResponse;
|
||||
import com.xiaowang.messagehub.dto.api.PlatformCapabilityView;
|
||||
import com.xiaowang.messagehub.entity.MessageChannelConfigDO;
|
||||
import com.xiaowang.messagehub.entity.PushLogDO;
|
||||
import com.xiaowang.messagehub.enums.ChannelHealthStatusEnum;
|
||||
import com.xiaowang.messagehub.enums.ChannelTypeEnum;
|
||||
import com.xiaowang.messagehub.enums.DispatchStatusEnum;
|
||||
import com.xiaowang.messagehub.mapper.MessageChannelConfigMapper;
|
||||
import com.xiaowang.messagehub.service.impl.MessageHandleService;
|
||||
import com.xiaowang.messagehub.service.source.MessageSourceSystemService;
|
||||
import com.xiaowang.messagehub.support.id.TimeOrderedSnowflakeIdGenerator;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
@Service
|
||||
public class MessageHubPublicService {
|
||||
|
||||
private static final int PROVIDER_RESPONSE_LIMIT = 4000;
|
||||
|
||||
private final MessageSourceSystemService sourceSystemService;
|
||||
private final MessageHandleService messageHandleService;
|
||||
private final MessageChannelConfigMapper channelConfigMapper;
|
||||
private final TimeOrderedSnowflakeIdGenerator idGenerator;
|
||||
|
||||
public MessageHubPublicService(MessageSourceSystemService sourceSystemService,
|
||||
MessageHandleService messageHandleService,
|
||||
MessageChannelConfigMapper channelConfigMapper,
|
||||
TimeOrderedSnowflakeIdGenerator idGenerator) {
|
||||
this.sourceSystemService = sourceSystemService;
|
||||
this.messageHandleService = messageHandleService;
|
||||
this.channelConfigMapper = channelConfigMapper;
|
||||
this.idGenerator = idGenerator;
|
||||
}
|
||||
|
||||
public MessageIdReserveResponse reserveMessageId(String sourceSystem, String accessToken) {
|
||||
sourceSystemService.authenticateSourceSystem(sourceSystem, accessToken);
|
||||
String messageId = idGenerator.nextIdString();
|
||||
messageHandleService.reserveAcceptedLog(messageId, sourceSystem);
|
||||
|
||||
MessageIdReserveResponse response = new MessageIdReserveResponse();
|
||||
response.setMessageId(messageId);
|
||||
response.setDispatchStatus(DispatchStatusEnum.ACCEPTED.name());
|
||||
return response;
|
||||
}
|
||||
|
||||
public List<PlatformCapabilityView> listPlatforms(String sourceSystem, String accessToken) {
|
||||
sourceSystemService.authenticateSourceSystem(sourceSystem, accessToken);
|
||||
Set<String> allowedPlatforms = sourceSystemService.listAllowedPlatforms(sourceSystem);
|
||||
return allowedPlatforms.stream()
|
||||
.map(this::toPlatformView)
|
||||
.filter(PlatformCapabilityView::isAvailable)
|
||||
.toList();
|
||||
}
|
||||
|
||||
public MessageStatusResponse getStatus(String messageId, String sourceSystem, String accessToken) {
|
||||
sourceSystemService.authenticateSourceSystem(sourceSystem, accessToken);
|
||||
PushLogDO pushLog = messageHandleService.getPushLog(messageId);
|
||||
if (pushLog == null) {
|
||||
throw new IllegalArgumentException("messageId not found: " + messageId);
|
||||
}
|
||||
if (!StringUtils.hasText(pushLog.getSourceSystem())
|
||||
|| !pushLog.getSourceSystem().equalsIgnoreCase(sourceSystem.trim())) {
|
||||
throw new IllegalArgumentException("messageId does not belong to sourceSystem: " + sourceSystem);
|
||||
}
|
||||
return toStatusResponse(pushLog);
|
||||
}
|
||||
|
||||
private PlatformCapabilityView toPlatformView(String platform) {
|
||||
ChannelTypeEnum channelType = ChannelTypeEnum.fromCode(platform);
|
||||
List<MessageChannelConfigDO> enabledChannels = listEnabledChannels(channelType.getCode());
|
||||
|
||||
PlatformCapabilityView view = new PlatformCapabilityView();
|
||||
view.setPlatform(channelType.getCode());
|
||||
view.setName(channelType.getLabel());
|
||||
view.setEnabledChannelCount(enabledChannels.size());
|
||||
view.setAvailable(!enabledChannels.isEmpty());
|
||||
view.setPlatformParams(platformParams(channelType));
|
||||
return view;
|
||||
}
|
||||
|
||||
private List<MessageChannelConfigDO> listEnabledChannels(String platform) {
|
||||
LambdaQueryWrapper<MessageChannelConfigDO> queryWrapper = new LambdaQueryWrapper<>();
|
||||
queryWrapper.eq(MessageChannelConfigDO::getChannelType, platform)
|
||||
.eq(MessageChannelConfigDO::getEnabled, 1)
|
||||
.orderByDesc(MessageChannelConfigDO::getIsDefault)
|
||||
.orderByDesc(MessageChannelConfigDO::getUpdateTime);
|
||||
return channelConfigMapper.selectList(queryWrapper).stream()
|
||||
.filter(item -> !ChannelHealthStatusEnum.UNHEALTHY.getCode().equalsIgnoreCase(item.getHealthStatus()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private Map<String, String> platformParams(ChannelTypeEnum channelType) {
|
||||
Map<String, String> params = new LinkedHashMap<>();
|
||||
switch (channelType) {
|
||||
case SMS -> params.put("sendMethod", "SPUG or OTHER; optional, defaults to OTHER");
|
||||
case EMAIL -> {
|
||||
params.put("subject", "Email subject; optional when emailTemplateCode/templateCode is provided");
|
||||
params.put("content", "Email body; optional when emailTemplateCode/templateCode is provided");
|
||||
params.put("bodyType", "TEXT or HTML");
|
||||
params.put("emailTemplateCode", "Email template code");
|
||||
params.put("attachmentIds", "Array of uploaded attachment ids");
|
||||
}
|
||||
case QQ -> {
|
||||
params.put("targetType", "FRIEND or GROUP");
|
||||
params.put("content", "Text or OneBot JSON content");
|
||||
params.put("contentMode", "TEXT or ONEBOT_JSON");
|
||||
}
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
private MessageStatusResponse toStatusResponse(PushLogDO entity) {
|
||||
MessageStatusResponse response = new MessageStatusResponse();
|
||||
response.setMessageId(entity.getId());
|
||||
response.setSourceSystem(entity.getSourceSystem());
|
||||
response.setUniqueId(entity.getUniqueId());
|
||||
response.setPlatform(entity.getChannelType());
|
||||
response.setReceiver(entity.getReceiver());
|
||||
response.setMsgType(entity.getMsgType());
|
||||
response.setDispatchStatus(DispatchStatusEnum.normalize(entity.getDispatchStatus(), entity.getStatus()));
|
||||
response.setLegacyStatus(entity.getStatus());
|
||||
response.setChannelId(entity.getChannelId());
|
||||
response.setProviderCode(entity.getProviderCode());
|
||||
response.setRetryCount(entity.getRetryCount());
|
||||
response.setFailReason(entity.getFailReason());
|
||||
response.setProviderResponse(truncate(entity.getProviderResponse(), PROVIDER_RESPONSE_LIMIT));
|
||||
response.setSendTime(entity.getSendTime());
|
||||
response.setCreateTime(entity.getCreateTime());
|
||||
response.setUpdateTime(entity.getUpdateTime());
|
||||
return response;
|
||||
}
|
||||
|
||||
private String truncate(String value, int limit) {
|
||||
if (value == null || value.length() <= limit) {
|
||||
return value;
|
||||
}
|
||||
return value.substring(0, limit) + "...";
|
||||
}
|
||||
}
|
||||
-89
@@ -1,89 +0,0 @@
|
||||
package com.xiaowang.messagehub.service.channel;
|
||||
|
||||
import com.xiaowang.messagehub.config.MessageChannelProperties;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
|
||||
@Service
|
||||
public class ChannelCryptoService {
|
||||
|
||||
private static final String PREFIX = "v1:";
|
||||
private static final int GCM_TAG_LENGTH = 128;
|
||||
private static final int GCM_IV_LENGTH = 12;
|
||||
|
||||
private final MessageChannelProperties properties;
|
||||
|
||||
private final SecureRandom secureRandom = new SecureRandom();
|
||||
|
||||
public ChannelCryptoService(MessageChannelProperties properties) {
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
public String encrypt(String plaintext) {
|
||||
if (!StringUtils.hasText(plaintext)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
byte[] iv = new byte[GCM_IV_LENGTH];
|
||||
secureRandom.nextBytes(iv);
|
||||
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, buildSecretKey(), new GCMParameterSpec(GCM_TAG_LENGTH, iv));
|
||||
byte[] encrypted = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
byte[] payload = new byte[iv.length + encrypted.length];
|
||||
System.arraycopy(iv, 0, payload, 0, iv.length);
|
||||
System.arraycopy(encrypted, 0, payload, iv.length, encrypted.length);
|
||||
return PREFIX + Base64.getEncoder().encodeToString(payload);
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException("通道敏感配置加密失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
public String decrypt(String ciphertext) {
|
||||
if (!StringUtils.hasText(ciphertext)) {
|
||||
return null;
|
||||
}
|
||||
if (!ciphertext.startsWith(PREFIX)) {
|
||||
return ciphertext;
|
||||
}
|
||||
try {
|
||||
byte[] payload = Base64.getDecoder().decode(ciphertext.substring(PREFIX.length()));
|
||||
byte[] iv = Arrays.copyOfRange(payload, 0, GCM_IV_LENGTH);
|
||||
byte[] encrypted = Arrays.copyOfRange(payload, GCM_IV_LENGTH, payload.length);
|
||||
|
||||
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, buildSecretKey(), new GCMParameterSpec(GCM_TAG_LENGTH, iv));
|
||||
byte[] decrypted = cipher.doFinal(encrypted);
|
||||
return new String(decrypted, StandardCharsets.UTF_8);
|
||||
} catch (Exception exception) {
|
||||
throw new IllegalStateException("通道敏感配置解密失败", exception);
|
||||
}
|
||||
}
|
||||
|
||||
public String mask(String value) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
return "";
|
||||
}
|
||||
if (value.length() <= 4) {
|
||||
return "****";
|
||||
}
|
||||
return value.substring(0, 2) + "****" + value.substring(value.length() - 2);
|
||||
}
|
||||
|
||||
private SecretKeySpec buildSecretKey() throws Exception {
|
||||
String key = properties.getSecurity().getEncryptionKey();
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
byte[] hashed = digest.digest(key.getBytes(StandardCharsets.UTF_8));
|
||||
return new SecretKeySpec(Arrays.copyOf(hashed, 16), "AES");
|
||||
}
|
||||
}
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
package com.xiaowang.messagehub.service.channel;
|
||||
|
||||
import com.xiaowang.messagehub.config.MessageChannelProperties;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class ChannelEnvironmentService {
|
||||
|
||||
private final Environment environment;
|
||||
|
||||
private final MessageChannelProperties properties;
|
||||
|
||||
public ChannelEnvironmentService(Environment environment, MessageChannelProperties properties) {
|
||||
this.environment = environment;
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
public boolean isDevelopmentEnvironment() {
|
||||
String[] activeProfiles = environment.getActiveProfiles();
|
||||
if (activeProfiles == null || activeProfiles.length == 0) {
|
||||
return true;
|
||||
}
|
||||
Set<String> devProfiles = properties.getMock().getProfiles().stream()
|
||||
.map(profile -> profile.toLowerCase(Locale.ROOT))
|
||||
.collect(Collectors.toSet());
|
||||
return Arrays.stream(activeProfiles)
|
||||
.map(profile -> profile.toLowerCase(Locale.ROOT))
|
||||
.anyMatch(devProfiles::contains);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user