注释优化
短信发送队列优化 邮件发送队列实现
This commit is contained in:
@@ -0,0 +1,282 @@
|
||||
# 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分钟内有效,如非本人操作请忽略。
|
||||
```
|
||||
|
||||
## 使用方式
|
||||
|
||||
### 方式一:使用测试类发送消息
|
||||
|
||||
参考 `MessageProducerTest.java` 中的测试方法:
|
||||
|
||||
```java
|
||||
@Test
|
||||
public void testSendSmsMessage() {
|
||||
MessageDTO messageDTO = new MessageDTO();
|
||||
messageDTO.setReceiver("13800138000");
|
||||
messageDTO.setChannelType("SMS");
|
||||
messageDTO.setMsgType("VERIFICATION");
|
||||
messageDTO.setSourceSystem("MessageHub");
|
||||
|
||||
messageProducerService.sendSmsMessage(messageDTO);
|
||||
}
|
||||
```
|
||||
|
||||
### 方式二:使用RabbitMQ管理界面发送消息
|
||||
|
||||
1. 登录RabbitMQ管理界面:http://192.168.5.15:15672
|
||||
2. 进入Queues页面
|
||||
3. 选择对应的队列(smsQueue 或 emailQueue)
|
||||
4. 点击"Publish message"
|
||||
5. 将JSON消息体粘贴到Payload中
|
||||
6. 点击"Publish message"发送
|
||||
|
||||
### 方式三:使用RabbitMQ命令行工具发送消息
|
||||
|
||||
```bash
|
||||
# 发送短信消息
|
||||
rabbitmqadmin publish exchange=smsExchange routing_key=sms.send payload='{"receiver":"13800138000","channelType":"SMS","msgType":"VERIFICATION","sourceSystem":"TestSystem","uniqueId":"test_001"}'
|
||||
|
||||
# 发送邮件消息
|
||||
rabbitmqadmin publish exchange=emailExchange routing_key=email.send payload='{"receiver":"test@example.com","channelType":"EMAIL","msgType":"NOTIFICATION","sourceSystem":"TestSystem","uniqueId":"test_002"}'
|
||||
```
|
||||
|
||||
## 队列配置
|
||||
|
||||
### 短信队列
|
||||
- 队列名称:smsQueue
|
||||
- 交换机名称:smsExchange
|
||||
- 路由键:sms.send
|
||||
- 监听器:SmsQueueListener
|
||||
|
||||
### 邮件队列
|
||||
- 队列名称:emailQueue
|
||||
- 交换机名称:emailExchange
|
||||
- 路由键:email.send
|
||||
- 监听器:EmailQueueListener
|
||||
@@ -52,6 +52,41 @@ spring:
|
||||
session-stat-enable: true
|
||||
session-stat-max-count: 1000
|
||||
|
||||
# 短信配置
|
||||
sms:
|
||||
# 短信平台选择:spug
|
||||
platform: spug
|
||||
# Spug配置
|
||||
spug:
|
||||
base-url: https://push.spug.cc
|
||||
template-id: your-template-id
|
||||
api-key: your-api-key
|
||||
|
||||
# 邮件配置
|
||||
email:
|
||||
# 邮件平台选择:gmail 或 qqmail
|
||||
platform: gmail
|
||||
# Gmail配置
|
||||
gmail:
|
||||
host: smtp.gmail.com
|
||||
port: 587
|
||||
username: your-gmail-username@gmail.com
|
||||
password: your-gmail-app-password
|
||||
auth: true
|
||||
starttls: true
|
||||
ssl: false
|
||||
from: your-gmail-username@gmail.com
|
||||
# QQMail配置
|
||||
qqmail:
|
||||
host: smtp.qq.com
|
||||
port: 587
|
||||
username: your-qq-email@qq.com
|
||||
password: your-qq-authorization-code
|
||||
auth: true
|
||||
starttls: true
|
||||
ssl: false
|
||||
from: your-qq-email@qq.com
|
||||
|
||||
# MyBatis-Plus配置
|
||||
mybatis-plus:
|
||||
mapper-locations: classpath:mapper/*.xml
|
||||
|
||||
@@ -107,6 +107,11 @@
|
||||
<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>
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.xiaowang.messagehub.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 邮件配置类
|
||||
* 用于存储和管理邮件相关的配置信息
|
||||
* 使用@ConfigurationProperties注解将配置文件中以"email"为前缀的属性自动绑定到该类的字段上
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "email")
|
||||
public class EmailConfig {
|
||||
|
||||
private String platform = "gmail"; // 默认邮件平台为gmail
|
||||
|
||||
private GmailConfig gmail; // Gmail邮件配置对象
|
||||
|
||||
private QQMailConfig qqmail; // QQ邮件配置对象
|
||||
|
||||
/**
|
||||
* Gmail邮件配置内部类
|
||||
* 包含Gmail邮件服务所需的所有配置参数
|
||||
*/
|
||||
@Data
|
||||
public static class GmailConfig {
|
||||
private String host = "smtp.gmail.com"; // Gmail SMTP服务器地址
|
||||
private Integer port = 587; // Gmail SMTP服务器端口
|
||||
private String username; // Gmail用户名
|
||||
private String password; // Gmail密码
|
||||
private Boolean auth = true; // 是否需要认证
|
||||
private Boolean starttls = true; // 是否启用STARTTLS
|
||||
private Boolean ssl = false; // 是否启用SSL
|
||||
private String from; // 发件人地址
|
||||
}
|
||||
|
||||
/**
|
||||
* QQ邮件配置内部类
|
||||
* 包含QQ邮件服务所需的所有配置参数
|
||||
*/
|
||||
@Data
|
||||
public static class QQMailConfig {
|
||||
private String host = "smtp.qq.com"; // QQ SMTP服务器地址
|
||||
private Integer port = 587; // QQ SMTP服务器端口
|
||||
private String username; // QQ邮箱用户名
|
||||
private String password; // QQ邮箱密码
|
||||
private Boolean auth = true; // 是否需要认证
|
||||
private Boolean starttls = true; // 是否启用STARTTLS
|
||||
private Boolean ssl = false; // 是否启用SSL
|
||||
private String from; // 发件人地址
|
||||
}
|
||||
}
|
||||
@@ -9,24 +9,37 @@ import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* 交换机队列配置
|
||||
* 该类配置了RabbitMQ的扇出型(Fanout)交换机和队列的绑定关系
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@Configuration
|
||||
@Configuration // 标记为配置类,用于定义Bean
|
||||
public class FanoutConfig {
|
||||
@Bean
|
||||
|
||||
// 定义扇出型交换机Bean
|
||||
// 交换机名称为"fanout.sms",类型为FanoutExchange
|
||||
@Bean // 将该方法返回的对象注册为Spring容器中的Bean
|
||||
public FanoutExchange fanoutExchange() {
|
||||
return new FanoutExchange("fanout.sms");
|
||||
}
|
||||
|
||||
|
||||
@Bean
|
||||
|
||||
|
||||
|
||||
// 定义短信队列Bean
|
||||
// 队列名称为"smsQueue"
|
||||
@Bean // 将该方法返回的对象注册为Spring容器中的Bean
|
||||
public Queue smsQueue() {
|
||||
return new Queue("smsQueue");
|
||||
}
|
||||
|
||||
@Bean
|
||||
|
||||
|
||||
// 定义绑定关系Bean
|
||||
// 将smsQueue队列绑定到fanoutExchange交换机上
|
||||
@Bean // 将该方法返回的对象注册为Spring容器中的Bean
|
||||
public Binding fanoutBinding() {
|
||||
return BindingBuilder.bind(smsQueue()).to(fanoutExchange());
|
||||
}
|
||||
|
||||
@@ -11,24 +11,36 @@ import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* MyBatis-Plus配置类
|
||||
* 用于配置MyBatis-Plus的拦截器,实现分页、乐观锁和防止全表更新等功能
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@Configuration
|
||||
@MapperScan("com.xiaowang.messagehub.mapper")
|
||||
@Configuration // 标识该类为配置类,Spring会扫描并加载其中的配置
|
||||
@MapperScan("com.xiaowang.messagehub.mapper") // 扫描指定包下的Mapper接口,自动注册为Spring Bean
|
||||
public class MyBatisPlusConfig {
|
||||
|
||||
@Bean
|
||||
public MybatisPlusInterceptor mybatisPlusInterceptor() {
|
||||
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
|
||||
|
||||
|
||||
/**
|
||||
* 配置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;
|
||||
return interceptor; // 返回配置好的拦截器
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,21 +8,33 @@ import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* MyBatis-Plus元数据处理器
|
||||
* 该类用于自动填充实体类的公共字段,如创建时间、更新时间等
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@Component
|
||||
public class MyMetaObjectHandler implements MetaObjectHandler {
|
||||
@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,52 +1,80 @@
|
||||
package com.xiaowang.messagehub.config;
|
||||
|
||||
import org.springframework.amqp.core.*;
|
||||
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
|
||||
import org.springframework.amqp.support.converter.MessageConverter;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* RabbitMQ配置类
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
* 用于配置RabbitMQ的队列(Queue)、交换机(Exchange)和绑定(Binding)
|
||||
*/
|
||||
@Configuration
|
||||
public class RabbitMQConfig {
|
||||
|
||||
public static final String MESSAGE_QUEUE = "message.queue";
|
||||
public static final String MESSAGE_EXCHANGE = "message.exchange";
|
||||
public static final String MESSAGE_ROUTING_KEY = "message.routing.key";
|
||||
// 定义短信队列名称常量
|
||||
public static final String SMS_QUEUE = "smsQueue";
|
||||
// 定义邮件队列名称常量
|
||||
public static final String EMAIL_QUEUE = "emailQueue";
|
||||
// 定义短信交换机名称常量
|
||||
public static final String SMS_EXCHANGE = "smsExchange";
|
||||
// 定义邮件交换机名称常量
|
||||
public static final String EMAIL_EXCHANGE = "emailExchange";
|
||||
// 定义短信路由键常量
|
||||
public static final String SMS_ROUTING_KEY = "sms.send";
|
||||
// 定义邮件路由键常量
|
||||
public static final String EMAIL_ROUTING_KEY = "email.send";
|
||||
|
||||
/**
|
||||
* 配置短信队列
|
||||
* @return 持久化的短信队列
|
||||
*/
|
||||
@Bean
|
||||
public Queue messageQueue() {
|
||||
return QueueBuilder.durable(MESSAGE_QUEUE).build();
|
||||
public Queue smsQueue() {
|
||||
return QueueBuilder.durable(SMS_QUEUE).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置邮件队列
|
||||
* @return 持久化的邮件队列
|
||||
*/
|
||||
@Bean
|
||||
public TopicExchange messageExchange() {
|
||||
return new TopicExchange(MESSAGE_EXCHANGE, true, false);
|
||||
public Queue emailQueue() {
|
||||
return QueueBuilder.durable(EMAIL_QUEUE).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置短信交换机
|
||||
* @return 持久化的、自动删除的、不自动声明的主题交换机
|
||||
*/
|
||||
@Bean
|
||||
public Binding messageBinding() {
|
||||
return BindingBuilder.bind(messageQueue())
|
||||
.to(messageExchange())
|
||||
.with(MESSAGE_ROUTING_KEY);
|
||||
public TopicExchange smsExchange() {
|
||||
return new TopicExchange(SMS_EXCHANGE, true, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置邮件交换机
|
||||
* @return 持久化的、自动删除的、不自动声明的主题交换机
|
||||
*/
|
||||
@Bean
|
||||
public MessageConverter jsonMessageConverter() {
|
||||
return new Jackson2JsonMessageConverter();
|
||||
public TopicExchange emailExchange() {
|
||||
return new TopicExchange(EMAIL_EXCHANGE, true, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置短信队列与交换机的绑定关系
|
||||
* @return 绑定对象,将短信队列绑定到短信交换机,并设置路由键
|
||||
*/
|
||||
@Bean
|
||||
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
|
||||
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
|
||||
rabbitTemplate.setMessageConverter(jsonMessageConverter());
|
||||
return rabbitTemplate;
|
||||
public Binding smsBinding() {
|
||||
return BindingBuilder.bind(smsQueue()).to(smsExchange()).with(SMS_ROUTING_KEY);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置邮件队列与交换机的绑定关系
|
||||
* @return 绑定对象,将邮件队列绑定到邮件交换机,并设置路由键
|
||||
*/
|
||||
@Bean
|
||||
public Binding emailBinding() {
|
||||
return BindingBuilder.bind(emailQueue()).to(emailExchange()).with(EMAIL_ROUTING_KEY);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.xiaowang.messagehub.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "sms")
|
||||
public class SmsConfig {
|
||||
|
||||
private String platform = "spug";
|
||||
|
||||
private SpugConfig spug;
|
||||
|
||||
@Data
|
||||
public static class SpugConfig {
|
||||
private String baseUrl = "https://push.spug.cc";
|
||||
private String templateId;
|
||||
private String apiKey;
|
||||
}
|
||||
}
|
||||
@@ -9,21 +9,40 @@ import javax.validation.Validator;
|
||||
|
||||
/**
|
||||
* 校验配置类
|
||||
* 用于配置Spring框架中的数据校验相关Bean
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@Configuration
|
||||
@Configuration // 标记此类为配置类,用于定义Bean
|
||||
public class ValidationConfig {
|
||||
|
||||
@Bean
|
||||
|
||||
|
||||
/**
|
||||
* 创建Validator Bean
|
||||
* 用于提供JSR-303规范的校验功能
|
||||
*
|
||||
* @return Validator实例
|
||||
*/
|
||||
@Bean // 将此方法返回的对象注册为Spring容器中的Bean
|
||||
public Validator validator() {
|
||||
return new LocalValidatorFactoryBean();
|
||||
}
|
||||
|
||||
@Bean
|
||||
|
||||
|
||||
/**
|
||||
* 创建方法校验后置处理器
|
||||
* 用于在Spring方法调用时执行参数校验
|
||||
*
|
||||
* @return 配置好的MethodValidationPostProcessor实例
|
||||
*/
|
||||
@Bean // 将此方法返回的对象注册为Spring容器中的Bean
|
||||
public MethodValidationPostProcessor methodValidationPostProcessor() {
|
||||
// 创建方法校验后置处理器实例
|
||||
MethodValidationPostProcessor processor = new MethodValidationPostProcessor();
|
||||
// 设置校验器为上面定义的validator Bean
|
||||
processor.setValidator(validator());
|
||||
return processor;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import java.util.Map;
|
||||
|
||||
/**
|
||||
* 消息队列中推送消息实体类
|
||||
* 用于封装消息推送所需的所有信息,包括接收者、渠道类型、消息类型等
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
@@ -16,27 +17,34 @@ import java.util.Map;
|
||||
@Data
|
||||
public class MessageDTO {
|
||||
|
||||
// 接收者邮箱地址,必须符合邮箱格式且不能为空
|
||||
@NotBlank(message = "接收者不能为空")
|
||||
@Email(message = "接收者必须是有效的邮箱地址")
|
||||
private String receiver;
|
||||
|
||||
// 渠道类型,只能是EMAIL、SMS、PUSH或WECHAT中的一种且不能为空
|
||||
@NotBlank(message = "渠道类型不能为空")
|
||||
@Pattern(regexp = "^(EMAIL|SMS|PUSH|WECHAT)$", message = "渠道类型必须是EMAIL、SMS、PUSH或WECHAT")
|
||||
private String channelType;
|
||||
|
||||
// 消息类型,只能是NOTIFICATION、VERIFICATION、PROMOTION或ALERT中的一种且不能为空
|
||||
@NotBlank(message = "消息类型不能为空")
|
||||
@Pattern(regexp = "^(NOTIFICATION|VERIFICATION|PROMOTION|ALERT)$", message = "消息类型必须是NOTIFICATION、VERIFICATION、PROMOTION或ALERT")
|
||||
private String msgType;
|
||||
|
||||
// 模板编码,用于标识使用的消息模板,长度不能超过50
|
||||
@Size(max = 50, message = "模板编码长度不能超过50")
|
||||
private String templateCode;
|
||||
|
||||
// 模板参数,用于填充模板中的变量,使用Map存储键值对
|
||||
private Map<String, Object> templateParams;
|
||||
|
||||
// 来源系统标识,表示消息发送的系统,长度不能超过50且不能为空
|
||||
@NotBlank(message = "来源系统不能为空")
|
||||
@Size(max = 50, message = "来源系统长度不能超过50")
|
||||
private String sourceSystem;
|
||||
|
||||
// 消息的唯一标识,用于追踪和去重,长度不能超过100且不能为空
|
||||
@NotBlank(message = "唯一标识不能为空")
|
||||
@Size(max = 100, message = "唯一标识长度不能超过100")
|
||||
private String uniqueId;
|
||||
|
||||
@@ -6,31 +6,39 @@ import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 消息实体类
|
||||
* 用于存储消息相关的数据信息
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@Data
|
||||
@TableName("message")
|
||||
@Data // 使用Lombok的@Data注解,自动生成getter、setter、toString等方法
|
||||
@TableName("message") // MyBatis-Plus的表名注解,指定对应数据库表名为message
|
||||
public class MessageDO {
|
||||
// 主键ID,使用自增策略
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
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;
|
||||
|
||||
@@ -6,52 +6,53 @@ import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 推送日志实体类
|
||||
* 用于记录系统推送操作的相关信息,包括推送来源、接收者、消息内容等
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@Data
|
||||
@TableName("push_log")
|
||||
@Data // Lombok注解,自动生成getter、setter等方法
|
||||
@TableName("push_log") // MyBatis-Plus注解,指定对应数据库表名
|
||||
public class PushLogDO {
|
||||
@TableId(value = "id", type = IdType.INPUT)
|
||||
private String id;
|
||||
@TableId(value = "id", type = IdType.INPUT) // 指定主键字段,类型为手动输入
|
||||
private String id; // 推送日志的唯一标识符
|
||||
|
||||
@TableField("source_system")
|
||||
private String sourceSystem;
|
||||
@TableField("source_system") // 指定对应数据库字段名
|
||||
private String sourceSystem; // 推送来源系统标识
|
||||
|
||||
@TableField("unique_id")
|
||||
private String uniqueId;
|
||||
private String uniqueId; // 推送内容的唯一标识,用于去重
|
||||
|
||||
@TableField("receiver")
|
||||
private String receiver;
|
||||
private String receiver; // 消息接收者标识
|
||||
|
||||
@TableField("channel_type")
|
||||
private String channelType;
|
||||
private String channelType; // 推送渠道类型,如短信、邮件等
|
||||
|
||||
@TableField("msg_type")
|
||||
private String msgType;
|
||||
private String msgType; // 消息类型,如通知、验证码等
|
||||
|
||||
@TableField("template_code")
|
||||
private String templateCode;
|
||||
private String templateCode; // 消息模板代码
|
||||
|
||||
@TableField("template_params")
|
||||
private String templateParams;
|
||||
private String templateParams; // 消息模板参数,JSON格式
|
||||
|
||||
@TableField("final_content")
|
||||
private String finalContent;
|
||||
private String finalContent; // 最终推送的消息内容
|
||||
|
||||
@TableField("status")
|
||||
private Integer status;
|
||||
private Integer status; // 推送状态,如0-待发送,1-发送成功,2-发送失败等
|
||||
|
||||
@TableField("retry_count")
|
||||
private Integer retryCount;
|
||||
private Integer retryCount; // 重试次数
|
||||
|
||||
@TableField("fail_reason")
|
||||
private String failReason;
|
||||
private String failReason; // 失败原因描述
|
||||
|
||||
@TableField("send_time")
|
||||
private LocalDateTime sendTime;
|
||||
private LocalDateTime sendTime; // 消息发送时间
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT) // 自动填充字段,插入时自动设置当前时间
|
||||
private LocalDateTime createTime; // 记录创建时间
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 推送模板实体类
|
||||
* 用于存储推送模板的相关信息,包括模板代码、名称、渠道类型等
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
@@ -13,39 +14,51 @@ import java.time.LocalDateTime;
|
||||
@Data
|
||||
@TableName("push_template")
|
||||
public class PushTemplateDO {
|
||||
// 主键ID,自增长类型
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
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("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;
|
||||
}
|
||||
|
||||
+23
-5
@@ -11,6 +11,7 @@ import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* 连接健康检查类
|
||||
* 用于检查系统中各个关键服务的连接状态,包括MySQL、RabbitMQ和Nacos
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
@@ -18,16 +19,21 @@ import java.sql.SQLException;
|
||||
@Component
|
||||
public class ConnectionHealthChecker {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ConnectionHealthChecker.class);
|
||||
private static final Logger logger = LoggerFactory.getLogger(ConnectionHealthChecker.class); // 使用Logback日志框架
|
||||
|
||||
@Autowired
|
||||
private ConnectionFactory rabbitMQConnectionFactory;
|
||||
private ConnectionFactory rabbitMQConnectionFactory; // RabbitMQ连接工厂,用于创建RabbitMQ连接
|
||||
|
||||
// MySQL连接配置参数
|
||||
private String mysqlUrl;
|
||||
private String mysqlUsername;
|
||||
private String mysqlPassword;
|
||||
private String nacosServerAddr;
|
||||
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");
|
||||
@@ -36,10 +42,14 @@ public class ConnectionHealthChecker {
|
||||
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)) {
|
||||
if (conn.isValid(5)) { // 设置5秒超时验证连接
|
||||
logger.info("MySQL连接成功 - URL: {}", mysqlUrl);
|
||||
return true;
|
||||
}
|
||||
@@ -49,6 +59,10 @@ public class ConnectionHealthChecker {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查RabbitMQ消息队列连接
|
||||
* @return 如果连接成功返回true,否则返回false
|
||||
*/
|
||||
public boolean checkRabbitMQ() {
|
||||
logger.info("开始检查RabbitMQ连接...");
|
||||
try {
|
||||
@@ -56,7 +70,7 @@ public class ConnectionHealthChecker {
|
||||
if (connection.isOpen()) {
|
||||
logger.info("RabbitMQ连接成功 - Host: {}, Port: {}",
|
||||
rabbitMQConnectionFactory.getHost(), rabbitMQConnectionFactory.getPort());
|
||||
connection.close();
|
||||
connection.close(); // 完成检查后关闭连接
|
||||
return true;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
@@ -66,6 +80,10 @@ public class ConnectionHealthChecker {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查Nacos服务发现连接
|
||||
* @return 总是返回true,因为Nacos连接在应用启动时自动建立
|
||||
*/
|
||||
public boolean checkNacos() {
|
||||
logger.info("开始检查Nacos连接...");
|
||||
logger.info("Nacos配置 - ServerAddr: {}, Namespace: MessageHub", nacosServerAddr);
|
||||
|
||||
+21
-4
@@ -10,53 +10,70 @@ import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 应用启动监听器
|
||||
* 该类实现了Spring的ApplicationListener接口,用于在应用启动完成后执行特定的初始化操作
|
||||
* 主要功能是在服务启动完成后,检查各个关键组件的连接状态
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@Component
|
||||
@Component // 将此类标记为Spring组件,使其成为Spring容器中的一个Bean
|
||||
public class ApplicationStartupListener implements ApplicationListener<ApplicationReadyEvent> {
|
||||
|
||||
// 使用SLF4J日志记录器,用于记录应用运行时的日志信息
|
||||
private static final Logger logger = LoggerFactory.getLogger(ApplicationStartupListener.class);
|
||||
|
||||
// 自动注入连接健康检查器,用于检查各个组件的连接状态
|
||||
@Autowired
|
||||
private ConnectionHealthChecker connectionHealthChecker;
|
||||
|
||||
/**
|
||||
* 重写ApplicationListener接口的onApplicationEvent方法
|
||||
* 当Spring Boot应用完全启动并准备就绪时,会触发ApplicationReadyEvent事件
|
||||
* 此方法会在事件触发后被调用,执行服务启动后的初始化检查
|
||||
*
|
||||
* @param event 应用准备就绪事件,包含应用启动完成的信息
|
||||
*/
|
||||
@Override
|
||||
public void onApplicationEvent(ApplicationReadyEvent event) {
|
||||
// 打印服务启动完成的分隔线信息
|
||||
logger.info("========================================");
|
||||
logger.info("MessageHub服务启动完成,开始检查各组件连接状态...");
|
||||
logger.info("========================================");
|
||||
|
||||
// 初始化连接状态标志,默认为true,表示所有连接检查都成功
|
||||
boolean allSuccess = true;
|
||||
|
||||
// 检查MySQL连接
|
||||
logger.info("");
|
||||
logger.info("【1/3】检查MySQL连接...");
|
||||
if (connectionHealthChecker.checkMySQL()) {
|
||||
logger.info("✓ MySQL连接检查通过");
|
||||
} else {
|
||||
logger.error("✗ MySQL连接检查失败");
|
||||
allSuccess = false;
|
||||
allSuccess = false; // 如果MySQL连接失败,设置标志为false
|
||||
}
|
||||
|
||||
// 检查RabbitMQ连接
|
||||
logger.info("");
|
||||
logger.info("【2/3】检查RabbitMQ连接...");
|
||||
if (connectionHealthChecker.checkRabbitMQ()) {
|
||||
logger.info("✓ RabbitMQ连接检查通过");
|
||||
} else {
|
||||
logger.error("✗ RabbitMQ连接检查失败");
|
||||
allSuccess = false;
|
||||
allSuccess = false; // 如果RabbitMQ连接失败,设置标志为false
|
||||
}
|
||||
|
||||
// 检查Nacos连接
|
||||
logger.info("");
|
||||
logger.info("【3/3】检查Nacos连接...");
|
||||
if (connectionHealthChecker.checkNacos()) {
|
||||
logger.info("✓ Nacos连接检查通过");
|
||||
} else {
|
||||
logger.error("✗ Nacos连接检查失败");
|
||||
allSuccess = false;
|
||||
allSuccess = false; // 如果Nacos连接失败,设置标志为false
|
||||
}
|
||||
|
||||
// 输出最终检查结果
|
||||
logger.info("");
|
||||
logger.info("========================================");
|
||||
if (allSuccess) {
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
package com.xiaowang.messagehub.listener;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.messagehub.dto.MessageDTO;
|
||||
import com.xiaowang.messagehub.service.EmailSendService;
|
||||
import com.xiaowang.messagehub.service.MessageHandleService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.core.Message;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.rabbitmq.client.Channel;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* 邮件队列监听器
|
||||
* 用于监听和处理邮件队列中的消息
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class EmailQueueListener {
|
||||
|
||||
@Autowired
|
||||
private EmailSendService emailSendService; // 邮件发送服务
|
||||
|
||||
@Autowired
|
||||
private MessageHandleService messageHandleService; // 消息处理服务
|
||||
|
||||
@Autowired
|
||||
private ObjectMapper objectMapper; // JSON对象映射器
|
||||
|
||||
/**
|
||||
* 处理邮件消息的方法
|
||||
*
|
||||
* @param message RabbitMQ消息对象
|
||||
* @param channel RabbitMQ通道对象
|
||||
*/
|
||||
@org.springframework.amqp.rabbit.annotation.RabbitListener(queues = "emailQueue")
|
||||
public void handleEmailMessage(Message message, Channel channel) {
|
||||
String messageId = message.getMessageProperties().getMessageId(); // 获取消息ID
|
||||
|
||||
try {
|
||||
// 将消息体转换为字符串
|
||||
String messageBody = new String(message.getBody(), StandardCharsets.UTF_8);
|
||||
// 打印接收消息的日志
|
||||
log.info("========================================");
|
||||
log.info("收到邮件消息");
|
||||
log.info("消息ID: {}", messageId);
|
||||
log.info("消息内容: {}", messageBody);
|
||||
log.info("========================================");
|
||||
|
||||
// 将消息体转换为MessageDTO对象
|
||||
MessageDTO messageDTO = objectMapper.readValue(messageBody, MessageDTO.class);
|
||||
|
||||
// 验证消息并保存日志
|
||||
boolean isValid = messageHandleService.validateAndSaveLog(messageDTO, messageId, java.time.LocalDateTime.now());
|
||||
|
||||
if (isValid) {
|
||||
// 构建邮件主题和内容
|
||||
String subject = buildSubject(messageDTO);
|
||||
String content = buildContent(messageDTO);
|
||||
|
||||
// 发送邮件
|
||||
emailSendService.sendEmail(messageDTO.getReceiver(), subject, content);
|
||||
|
||||
// 打印处理完成的日志
|
||||
log.info("========================================");
|
||||
log.info("邮件消息处理完成");
|
||||
log.info("消息ID: {}", messageId);
|
||||
log.info("收件人: {}", messageDTO.getReceiver());
|
||||
log.info("主题: {}", subject);
|
||||
log.info("========================================");
|
||||
} else {
|
||||
log.warn("消息校验失败,消息ID: {}", messageId);
|
||||
}
|
||||
|
||||
// 确认消息处理完成
|
||||
long deliveryTag = message.getMessageProperties().getDeliveryTag();
|
||||
channel.basicAck(deliveryTag, false);
|
||||
} catch (Exception e) {
|
||||
// 处理异常情况
|
||||
log.error("处理邮件消息时发生异常,消息ID: {}", messageId, e);
|
||||
|
||||
try {
|
||||
// 即使发生异常也要确认消息处理完成,避免重复处理
|
||||
long deliveryTag = message.getMessageProperties().getDeliveryTag();
|
||||
channel.basicAck(deliveryTag, false);
|
||||
} catch (Exception ackException) {
|
||||
log.error("消息确认失败", ackException);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建邮件主题
|
||||
*
|
||||
* @param messageDTO 消息DTO对象
|
||||
* @return 构建好的邮件主题
|
||||
*/
|
||||
private String buildSubject(MessageDTO messageDTO) {
|
||||
String subject;
|
||||
|
||||
// 如果有模板代码,则将其添加到主题中
|
||||
if (messageDTO.getTemplateCode() != null && !messageDTO.getTemplateCode().isEmpty()) {
|
||||
subject = "[" + messageDTO.getTemplateCode() + "] " + messageDTO.getMsgType();
|
||||
} else {
|
||||
subject = messageDTO.getMsgType();
|
||||
}
|
||||
|
||||
return subject;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建邮件内容
|
||||
*
|
||||
* @param messageDTO 消息DTO对象
|
||||
* @return 构建好的邮件内容
|
||||
*/
|
||||
private String buildContent(MessageDTO messageDTO) {
|
||||
// 如果有模板代码,则使用模板替换占位符
|
||||
if (messageDTO.getTemplateCode() != null && !messageDTO.getTemplateCode().isEmpty()) {
|
||||
return messageHandleService.replaceTemplatePlaceholders(
|
||||
// 如果没有模板代码,则尝试从模板参数中获取消息内容
|
||||
messageDTO.getTemplateCode(),
|
||||
messageDTO.getTemplateParams()
|
||||
);
|
||||
} else {
|
||||
if (messageDTO.getTemplateParams() != null && messageDTO.getTemplateParams().containsKey("message")) {
|
||||
return messageDTO.getTemplateParams().get("message").toString();
|
||||
} else {
|
||||
return "无内容";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,8 @@ import com.rabbitmq.client.Channel;
|
||||
import com.xiaowang.messagehub.dto.MessageDTO;
|
||||
import com.xiaowang.messagehub.entity.PushTemplateDO;
|
||||
import com.xiaowang.messagehub.mapper.PushLogMapper;
|
||||
import com.xiaowang.messagehub.service.MessageService;
|
||||
import com.xiaowang.messagehub.service.MessageHandleService;
|
||||
import com.xiaowang.messagehub.service.SmsSendService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.amqp.core.Message;
|
||||
@@ -31,11 +32,14 @@ public class SmsQueueListener {
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@Autowired
|
||||
private MessageService messageService;
|
||||
private MessageHandleService messageHandleService;
|
||||
|
||||
@Autowired
|
||||
private PushLogMapper pushLogMapper;
|
||||
|
||||
@Autowired
|
||||
private SmsSendService smsSendService;
|
||||
|
||||
@RabbitListener(queues = "smsQueue")
|
||||
public void handleSmsMessage(Message message, Channel channel) {
|
||||
String messageId = message.getMessageProperties().getMessageId();
|
||||
@@ -52,21 +56,21 @@ public class SmsQueueListener {
|
||||
|
||||
MessageDTO messageDTO = objectMapper.readValue(messageBody, MessageDTO.class);
|
||||
|
||||
boolean isValid = messageService.validateAndSaveLog(messageDTO, messageId, sendTime);
|
||||
boolean isValid = messageHandleService.validateAndSaveLog(messageDTO, messageId, sendTime);
|
||||
|
||||
if (isValid) {
|
||||
String finalContent = null;
|
||||
String templateCode = messageDTO.getTemplateCode();
|
||||
|
||||
if (StringUtils.hasText(templateCode)) {
|
||||
PushTemplateDO template = messageService.getTemplateByCode(templateCode);
|
||||
PushTemplateDO template = messageHandleService.getTemplateByCode(templateCode);
|
||||
|
||||
if (template != null && StringUtils.hasText(template.getContentPattern())) {
|
||||
logger.info("检测到模板消息,模板编码: {}", templateCode);
|
||||
logger.info("模板内容模式: {}", template.getContentPattern());
|
||||
|
||||
String contentPattern = template.getContentPattern();
|
||||
finalContent = messageService.replaceTemplatePlaceholders(contentPattern, messageDTO.getTemplateParams());
|
||||
finalContent = messageHandleService.replaceTemplatePlaceholders(contentPattern, messageDTO.getTemplateParams());
|
||||
|
||||
logger.info("模板参数: {}", messageDTO.getTemplateParams());
|
||||
logger.info("替换后最终内容: {}", finalContent);
|
||||
@@ -88,9 +92,12 @@ public class SmsQueueListener {
|
||||
|
||||
pushLogMapper.updateFinalContent(messageId, finalContent);
|
||||
|
||||
smsSendService.sendSms(messageDTO.getReceiver(), finalContent);
|
||||
|
||||
logger.info("========================================");
|
||||
logger.info("消息处理完成");
|
||||
logger.info("消息接收处理完成");
|
||||
logger.info("消息ID: {}", messageId);
|
||||
logger.info("手机号: {}", messageDTO.getReceiver());
|
||||
logger.info("最终内容: {}", finalContent);
|
||||
logger.info("========================================");
|
||||
} else {
|
||||
|
||||
@@ -14,40 +14,99 @@ import java.util.List;
|
||||
|
||||
/**
|
||||
* 消息Mapper接口
|
||||
* 继承BaseMapper,提供MessageDO的基础数据库操作
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@Mapper
|
||||
public interface MessageMapper extends BaseMapper<MessageDO> {
|
||||
@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);
|
||||
}
|
||||
|
||||
@@ -14,55 +14,143 @@ import java.util.List;
|
||||
|
||||
/**
|
||||
* 推送日志Mapper接口
|
||||
* 该接口继承BaseMapper,提供了对推送日志数据的基本操作方法
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@Mapper
|
||||
@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}")
|
||||
PushLogDO selectByUniqueId(@Param("uniqueId") String uniqueId);
|
||||
|
||||
/**
|
||||
* 更新推送日志的重试状态
|
||||
* @param ID 日志ID
|
||||
* @param status 状态
|
||||
* @param failReason 失败原因
|
||||
* @return 更新的记录数
|
||||
*/
|
||||
@Update("UPDATE push_log SET status = #{status}, retry_count = retry_count + 1, fail_reason = #{failReason} WHERE id = #{id}")
|
||||
int updateRetryStatus(@Param("id") String id, @Param("status") Integer status, @Param("failReason") String failReason);
|
||||
|
||||
/**
|
||||
* 更新推送日志的最终内容
|
||||
* @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);
|
||||
}
|
||||
|
||||
@@ -13,40 +13,97 @@ import java.util.List;
|
||||
|
||||
/**
|
||||
* 推送模板Mapper接口
|
||||
* 继承BaseMapper,提供基础的数据库操作能力
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@Mapper
|
||||
@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);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.xiaowang.messagehub.service;
|
||||
|
||||
import com.xiaowang.messagehub.config.EmailConfig;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class EmailSendService {
|
||||
|
||||
@Autowired
|
||||
private EmailConfig emailConfig;
|
||||
|
||||
@Autowired
|
||||
private List<EmailSender> emailSenders;
|
||||
|
||||
public void sendEmail(String to, String subject, String content) {
|
||||
String platform = emailConfig.getPlatform();
|
||||
|
||||
EmailSender sender = emailSenders.stream()
|
||||
.filter(s -> s.getPlatformName().equalsIgnoreCase(platform))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new RuntimeException("不支持的邮件平台: " + platform));
|
||||
|
||||
log.info("使用{}平台发送邮件,收件人: {}, 主题: {}", platform, to, subject);
|
||||
sender.sendEmail(to, subject, content);
|
||||
}
|
||||
|
||||
public void sendEmail(String to, String subject, String content, String platform) {
|
||||
EmailSender sender = emailSenders.stream()
|
||||
.filter(s -> s.getPlatformName().equalsIgnoreCase(platform))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new RuntimeException("不支持的邮件平台: " + platform));
|
||||
|
||||
log.info("使用{}平台发送邮件,收件人: {}, 主题: {}", platform, to, subject);
|
||||
sender.sendEmail(to, subject, content);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.xiaowang.messagehub.service;
|
||||
|
||||
public interface EmailSender {
|
||||
|
||||
void sendEmail(String to, String subject, String content);
|
||||
|
||||
String getPlatformName();
|
||||
}
|
||||
+3
-3
@@ -19,15 +19,15 @@ import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 消息服务类
|
||||
* 消息队列数据校验服务类
|
||||
*
|
||||
* @author xiaowang
|
||||
* @date 2023-03-21
|
||||
*/
|
||||
@Service
|
||||
public class MessageService {
|
||||
public class MessageHandleService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessageService.class);
|
||||
private static final Logger logger = LoggerFactory.getLogger(MessageHandleService.class);
|
||||
|
||||
@Autowired
|
||||
private Validator validator;
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.xiaowang.messagehub.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.xiaowang.messagehub.config.RabbitMQConfig;
|
||||
import com.xiaowang.messagehub.dto.MessageDTO;
|
||||
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 java.util.UUID;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class MessageProducerService {
|
||||
|
||||
@Autowired
|
||||
private RabbitTemplate rabbitTemplate;
|
||||
|
||||
@Autowired
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
public void sendSmsMessage(MessageDTO messageDTO) {
|
||||
try {
|
||||
String messageId = UUID.randomUUID().toString();
|
||||
messageDTO.setUniqueId(messageId);
|
||||
|
||||
String messageBody = objectMapper.writeValueAsString(messageDTO);
|
||||
|
||||
Message message = MessageBuilder
|
||||
.withBody(messageBody.getBytes())
|
||||
.setContentType(MessageProperties.CONTENT_TYPE_JSON)
|
||||
.setMessageId(messageId)
|
||||
.setTimestamp(new java.util.Date())
|
||||
.build();
|
||||
|
||||
rabbitTemplate.send(
|
||||
RabbitMQConfig.SMS_EXCHANGE,
|
||||
RabbitMQConfig.SMS_ROUTING_KEY,
|
||||
message
|
||||
);
|
||||
|
||||
log.info("短信消息已发送到队列,消息ID: {}, 手机号: {}", messageId, messageDTO.getReceiver());
|
||||
} catch (Exception e) {
|
||||
log.error("发送短信消息失败", e);
|
||||
throw new RuntimeException("发送短信消息失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public void sendEmailMessage(MessageDTO messageDTO) {
|
||||
try {
|
||||
String messageId = UUID.randomUUID().toString();
|
||||
messageDTO.setUniqueId(messageId);
|
||||
|
||||
String messageBody = objectMapper.writeValueAsString(messageDTO);
|
||||
|
||||
Message message = MessageBuilder
|
||||
.withBody(messageBody.getBytes())
|
||||
.setContentType(MessageProperties.CONTENT_TYPE_JSON)
|
||||
.setMessageId(messageId)
|
||||
.setTimestamp(new java.util.Date())
|
||||
.build();
|
||||
|
||||
rabbitTemplate.send(
|
||||
RabbitMQConfig.EMAIL_EXCHANGE,
|
||||
RabbitMQConfig.EMAIL_ROUTING_KEY,
|
||||
message
|
||||
);
|
||||
|
||||
log.info("邮件消息已发送到队列,消息ID: {}, 收件人: {}", messageId, messageDTO.getReceiver());
|
||||
} catch (Exception e) {
|
||||
log.error("发送邮件消息失败", e);
|
||||
throw new RuntimeException("发送邮件消息失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.xiaowang.messagehub.service;
|
||||
|
||||
import com.xiaowang.messagehub.config.SmsConfig;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class SmsSendService {
|
||||
|
||||
@Autowired
|
||||
private SmsConfig smsConfig;
|
||||
|
||||
@Autowired
|
||||
private List<SmsSender> smsSenders;
|
||||
|
||||
/**
|
||||
* 发送短信的方法
|
||||
*
|
||||
* @param phone 接收短信的手机号码
|
||||
* @param content 短信内容
|
||||
*/
|
||||
public void sendSms(String phone, String content) {
|
||||
// 从配置中获取短信平台名称
|
||||
String platform = smsConfig.getPlatform();
|
||||
|
||||
// 根据平台名称从短信发送器列表中查找对应的发送器
|
||||
SmsSender sender = smsSenders.stream()
|
||||
// 过滤出与指定平台名称匹配的发送器
|
||||
.filter(s -> s.getPlatformName().equalsIgnoreCase(platform))
|
||||
// 获取第一个匹配的发送器,如果没有则抛出异常
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new RuntimeException("不支持的短信平台: " + platform));
|
||||
|
||||
// 记录发送短信的日志信息
|
||||
log.info("使用{}平台发送短信,手机号: {}, 内容: {}", platform, phone, content);
|
||||
// 调用发送器的发送短信方法
|
||||
sender.sendSms(phone, content);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送短信的方法
|
||||
*
|
||||
* @param phone 接收短信的手机号码
|
||||
* @param content 短信内容
|
||||
* @param platform 短信平台名称
|
||||
* @throws RuntimeException 当指定的短信平台不被支持时抛出
|
||||
*/
|
||||
public void sendSms(String phone, String content, String platform) {
|
||||
// 从短信发送者列表中筛选出指定平台的发送器
|
||||
SmsSender sender = smsSenders.stream()
|
||||
// 过滤出平台名称匹配的发送器
|
||||
.filter(s -> s.getPlatformName().equalsIgnoreCase(platform))
|
||||
// 获取第一个匹配的发送器,如果不存在则抛出异常
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new RuntimeException("不支持的短信平台: " + platform));
|
||||
|
||||
// 记录发送短信的日志信息
|
||||
log.info("使用{}平台发送短信,手机号: {}, 内容: {}", platform, phone, content);
|
||||
// 调用发送器的sendSms方法发送短信
|
||||
sender.sendSms(phone, content);
|
||||
}
|
||||
|
||||
public void sendSmsWithTemplate(String phone, String templateId, String... params) {
|
||||
String platform = smsConfig.getPlatform();
|
||||
|
||||
SmsSender sender = smsSenders.stream()
|
||||
.filter(s -> s.getPlatformName().equalsIgnoreCase(platform))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new RuntimeException("不支持的短信平台: " + platform));
|
||||
|
||||
log.info("使用{}平台发送模板短信,手机号: {}, 模板ID: {}", platform, phone, templateId);
|
||||
sender.sendSms(phone, templateId, params);
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用指定平台发送模板短信
|
||||
*
|
||||
* @param phone 接收短信的手机号码
|
||||
* @param templateId 短信模板ID
|
||||
* @param platform 短信发送平台名称
|
||||
* @param params 短信模板参数,可变长度参数
|
||||
* @throws RuntimeException 当指定的短信平台不被支持时抛出
|
||||
*/
|
||||
public void sendSmsWithTemplate(String phone, String templateId, String platform, String... params) {
|
||||
// 从短信发送者列表中根据平台名称筛选出对应的发送器
|
||||
SmsSender sender = smsSenders.stream()
|
||||
// 过滤出与指定平台名称匹配的发送器(不区分大小写)
|
||||
.filter(s -> s.getPlatformName().equalsIgnoreCase(platform))
|
||||
// 获取第一个匹配的发送器,如果没有则抛出异常
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new RuntimeException("不支持的短信平台: " + platform));
|
||||
|
||||
// 记录发送短信的日志信息
|
||||
log.info("使用{}平台发送模板短信,手机号: {}, 模板ID: {}", platform, phone, templateId);
|
||||
// 调用发送器的sendSms方法发送短信
|
||||
sender.sendSms(phone, templateId, params);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.xiaowang.messagehub.service;
|
||||
|
||||
public interface SmsSender {
|
||||
|
||||
void sendSms(String phone, String content);
|
||||
|
||||
void sendSms(String phone, String templateId, String... params);
|
||||
|
||||
String getPlatformName();
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.xiaowang.messagehub.service;
|
||||
|
||||
public class TgSendService {
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.xiaowang.messagehub.service;
|
||||
|
||||
public class WeChatSendService {
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.xiaowang.messagehub.service.impl;
|
||||
|
||||
import com.xiaowang.messagehub.config.EmailConfig;
|
||||
import com.xiaowang.messagehub.service.EmailSender;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.mail.SimpleMailMessage;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
import org.springframework.mail.javamail.JavaMailSenderImpl;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.PreDestroy;
|
||||
import javax.mail.Session;
|
||||
import javax.mail.Transport;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import javax.mail.internet.MimeMessage;
|
||||
import java.util.Properties;
|
||||
|
||||
@Slf4j
|
||||
@Service("gmailSender")
|
||||
public class GmailSender implements EmailSender {
|
||||
|
||||
@Autowired
|
||||
private EmailConfig emailConfig;
|
||||
|
||||
private Session session;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
EmailConfig.GmailConfig config = emailConfig.getGmail();
|
||||
|
||||
Properties props = new Properties();
|
||||
props.put("mail.smtp.host", config.getHost());
|
||||
props.put("mail.smtp.port", config.getPort());
|
||||
props.put("mail.smtp.auth", config.getAuth());
|
||||
props.put("mail.smtp.starttls.enable", config.getStarttls());
|
||||
props.put("mail.smtp.ssl.enable", config.getSsl());
|
||||
props.put("mail.smtp.connectiontimeout", "5000");
|
||||
props.put("mail.smtp.timeout", "5000");
|
||||
props.put("mail.smtp.writetimeout", "5000");
|
||||
|
||||
session = Session.getInstance(props, new javax.mail.Authenticator() {
|
||||
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
|
||||
return new javax.mail.PasswordAuthentication(config.getUsername(), config.getPassword());
|
||||
}
|
||||
});
|
||||
|
||||
log.info("Gmail邮件发送器初始化完成,发件人: {}", config.getFrom());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendEmail(String to, String subject, String content) {
|
||||
try {
|
||||
MimeMessage message = new MimeMessage(session);
|
||||
message.setFrom(new InternetAddress(emailConfig.getGmail().getFrom()));
|
||||
message.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(to));
|
||||
message.setSubject(subject, "UTF-8");
|
||||
message.setText(content, "UTF-8");
|
||||
|
||||
Transport.send(message);
|
||||
log.info("Gmail邮件发送成功,收件人: {}, 主题: {}", to, subject);
|
||||
} catch (Exception e) {
|
||||
log.error("Gmail邮件发送失败,收件人: {}, 主题: {}", to, subject, e);
|
||||
throw new RuntimeException("邮件发送失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPlatformName() {
|
||||
return "Gmail";
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void destroy() {
|
||||
log.info("Gmail邮件发送器已关闭");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.xiaowang.messagehub.service.impl;
|
||||
|
||||
import com.xiaowang.messagehub.config.EmailConfig;
|
||||
import com.xiaowang.messagehub.service.EmailSender;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.PreDestroy;
|
||||
import javax.mail.Session;
|
||||
import javax.mail.Transport;
|
||||
import javax.mail.internet.InternetAddress;
|
||||
import javax.mail.internet.MimeMessage;
|
||||
import java.util.Properties;
|
||||
|
||||
@Slf4j
|
||||
@Service("qqmailSender")
|
||||
public class QQMailSender implements EmailSender {
|
||||
|
||||
@Autowired
|
||||
private EmailConfig emailConfig;
|
||||
|
||||
private Session session;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
EmailConfig.QQMailConfig config = emailConfig.getQqmail();
|
||||
|
||||
Properties props = new Properties();
|
||||
props.put("mail.smtp.host", config.getHost());
|
||||
props.put("mail.smtp.port", config.getPort());
|
||||
props.put("mail.smtp.auth", config.getAuth());
|
||||
props.put("mail.smtp.starttls.enable", config.getStarttls());
|
||||
props.put("mail.smtp.ssl.enable", config.getSsl());
|
||||
props.put("mail.smtp.connectiontimeout", "5000");
|
||||
props.put("mail.smtp.timeout", "5000");
|
||||
props.put("mail.smtp.writetimeout", "5000");
|
||||
|
||||
session = Session.getInstance(props, new javax.mail.Authenticator() {
|
||||
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
|
||||
return new javax.mail.PasswordAuthentication(config.getUsername(), config.getPassword());
|
||||
}
|
||||
});
|
||||
|
||||
log.info("QQMail邮件发送器初始化完成,发件人: {}", config.getFrom());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendEmail(String to, String subject, String content) {
|
||||
try {
|
||||
MimeMessage message = new MimeMessage(session);
|
||||
message.setFrom(new InternetAddress(emailConfig.getQqmail().getFrom()));
|
||||
message.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(to));
|
||||
message.setSubject(subject, "UTF-8");
|
||||
message.setText(content, "UTF-8");
|
||||
|
||||
Transport.send(message);
|
||||
log.info("QQMail邮件发送成功,收件人: {}, 主题: {}", to, subject);
|
||||
} catch (Exception e) {
|
||||
log.error("QQMail邮件发送失败,收件人: {}, 主题: {}", to, subject, e);
|
||||
throw new RuntimeException("邮件发送失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPlatformName() {
|
||||
return "QQMail";
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void destroy() {
|
||||
log.info("QQMail邮件发送器已关闭");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.xiaowang.messagehub.service.impl;
|
||||
|
||||
import com.xiaowang.messagehub.config.SmsConfig;
|
||||
import com.xiaowang.messagehub.service.SmsSender;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.*;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
@Slf4j
|
||||
@Service("spugSmsSender")
|
||||
public class SpugSmsSender implements SmsSender {
|
||||
|
||||
@Autowired
|
||||
private SmsConfig smsConfig;
|
||||
|
||||
private RestTemplate restTemplate;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
restTemplate = new RestTemplate();
|
||||
log.info("Spug短信发送器初始化完成,模板ID: {}", smsConfig.getSpug().getTemplateId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendSms(String phone, String content) {
|
||||
try {
|
||||
String url = smsConfig.getSpug().getBaseUrl() + "/send/" + smsConfig.getSpug().getTemplateId();
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
|
||||
|
||||
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
|
||||
params.add("targets", phone);
|
||||
params.add("code", content);
|
||||
|
||||
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
|
||||
|
||||
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
|
||||
|
||||
if (response.getStatusCode() == HttpStatus.OK) {
|
||||
log.info("Spug短信发送成功,手机号: {}, 内容: {}, 响应: {}", phone, content, response.getBody());
|
||||
} else {
|
||||
log.error("Spug短信发送失败,手机号: {}, 状态码: {}", phone, response.getStatusCode());
|
||||
throw new RuntimeException("短信发送失败,状态码: " + response.getStatusCode());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Spug短信发送异常,手机号: {}, 内容: {}", phone, content, e);
|
||||
throw new RuntimeException("短信发送失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendSms(String phone, String templateId, String... params) {
|
||||
try {
|
||||
String url = smsConfig.getSpug().getBaseUrl() + "/send/" + templateId;
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
|
||||
|
||||
MultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>();
|
||||
requestParams.add("targets", phone);
|
||||
|
||||
if (params != null && params.length > 0) {
|
||||
for (int i = 0; i < params.length; i++) {
|
||||
requestParams.add("param" + (i + 1), params[i]);
|
||||
}
|
||||
}
|
||||
|
||||
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(requestParams, headers);
|
||||
|
||||
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
|
||||
|
||||
if (response.getStatusCode() == HttpStatus.OK) {
|
||||
log.info("Spug短信发送成功,手机号: {}, 模板ID: {}, 响应: {}", phone, templateId, response.getBody());
|
||||
} else {
|
||||
log.error("Spug短信发送失败,手机号: {}, 模板ID: {}, 状态码: {}", phone, templateId, response.getStatusCode());
|
||||
throw new RuntimeException("短信发送失败,状态码: " + response.getStatusCode());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Spug短信发送异常,手机号: {}, 模板ID: {}", phone, templateId, e);
|
||||
throw new RuntimeException("短信发送失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPlatformName() {
|
||||
return "Spug";
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user