diff --git a/MessageHub/pom.xml b/MessageHub/pom.xml index 7f6dc919..bf9cde96 100644 --- a/MessageHub/pom.xml +++ b/MessageHub/pom.xml @@ -102,6 +102,17 @@ 1.2.23 + + org.springframework.boot + spring-boot-starter-validation + + + + org.projectlombok + lombok + true + + org.springframework.boot spring-boot-starter-test diff --git a/MessageHub/src/main/java/com/xiaowang/messagehub/MessageHubApplication.java b/MessageHub/src/main/java/com/xiaowang/messagehub/MessageHubApplication.java index 7d590399..e6bec69e 100644 --- a/MessageHub/src/main/java/com/xiaowang/messagehub/MessageHubApplication.java +++ b/MessageHub/src/main/java/com/xiaowang/messagehub/MessageHubApplication.java @@ -3,6 +3,12 @@ package com.xiaowang.messagehub; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +/** + * MessageHub应用启动类 + * + * @author xiaowang + * @date 2023-03-21 + */ @SpringBootApplication public class MessageHubApplication { diff --git a/MessageHub/src/main/java/com/xiaowang/messagehub/config/FanoutConfig.java b/MessageHub/src/main/java/com/xiaowang/messagehub/config/FanoutConfig.java new file mode 100644 index 00000000..7ccbf634 --- /dev/null +++ b/MessageHub/src/main/java/com/xiaowang/messagehub/config/FanoutConfig.java @@ -0,0 +1,33 @@ +package com.xiaowang.messagehub.config; + +import org.springframework.amqp.core.Binding; +import org.springframework.amqp.core.BindingBuilder; +import org.springframework.amqp.core.FanoutExchange; +import org.springframework.amqp.core.Queue; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * 交换机队列配置 + * + * @author xiaowang + * @date 2023-03-21 + */ +@Configuration +public class FanoutConfig { + @Bean + public FanoutExchange fanoutExchange() { + return new FanoutExchange("fanout.sms"); + } + + + @Bean + public Queue smsQueue() { + return new Queue("smsQueue"); + } + + @Bean + public Binding fanoutBinding() { + return BindingBuilder.bind(smsQueue()).to(fanoutExchange()); + } +} diff --git a/MessageHub/src/main/java/com/xiaowang/messagehub/config/MyBatisPlusConfig.java b/MessageHub/src/main/java/com/xiaowang/messagehub/config/MyBatisPlusConfig.java index 6947483d..edfba627 100644 --- a/MessageHub/src/main/java/com/xiaowang/messagehub/config/MyBatisPlusConfig.java +++ b/MessageHub/src/main/java/com/xiaowang/messagehub/config/MyBatisPlusConfig.java @@ -9,6 +9,12 @@ import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +/** + * MyBatis-Plus配置类 + * + * @author xiaowang + * @date 2023-03-21 + */ @Configuration @MapperScan("com.xiaowang.messagehub.mapper") public class MyBatisPlusConfig { diff --git a/MessageHub/src/main/java/com/xiaowang/messagehub/config/MyMetaObjectHandler.java b/MessageHub/src/main/java/com/xiaowang/messagehub/config/MyMetaObjectHandler.java index b5d89d2d..4dce9977 100644 --- a/MessageHub/src/main/java/com/xiaowang/messagehub/config/MyMetaObjectHandler.java +++ b/MessageHub/src/main/java/com/xiaowang/messagehub/config/MyMetaObjectHandler.java @@ -6,6 +6,12 @@ import org.springframework.stereotype.Component; import java.time.LocalDateTime; +/** + * MyBatis-Plus元数据处理器 + * + * @author xiaowang + * @date 2023-03-21 + */ @Component public class MyMetaObjectHandler implements MetaObjectHandler { diff --git a/MessageHub/src/main/java/com/xiaowang/messagehub/config/RabbitMQConfig.java b/MessageHub/src/main/java/com/xiaowang/messagehub/config/RabbitMQConfig.java index 497950f3..983899cf 100644 --- a/MessageHub/src/main/java/com/xiaowang/messagehub/config/RabbitMQConfig.java +++ b/MessageHub/src/main/java/com/xiaowang/messagehub/config/RabbitMQConfig.java @@ -8,6 +8,12 @@ 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 + */ @Configuration public class RabbitMQConfig { diff --git a/MessageHub/src/main/java/com/xiaowang/messagehub/config/ValidationConfig.java b/MessageHub/src/main/java/com/xiaowang/messagehub/config/ValidationConfig.java new file mode 100644 index 00000000..c288f890 --- /dev/null +++ b/MessageHub/src/main/java/com/xiaowang/messagehub/config/ValidationConfig.java @@ -0,0 +1,30 @@ +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; + +/** + * 校验配置类 + * + * @author xiaowang + * @date 2023-03-21 + */ +@Configuration +public class ValidationConfig { + + @Bean + public Validator validator() { + return new LocalValidatorFactoryBean(); + } + + @Bean + public MethodValidationPostProcessor methodValidationPostProcessor() { + MethodValidationPostProcessor processor = new MethodValidationPostProcessor(); + processor.setValidator(validator()); + return processor; + } +} diff --git a/MessageHub/src/main/java/com/xiaowang/messagehub/dto/MessageDTO.java b/MessageHub/src/main/java/com/xiaowang/messagehub/dto/MessageDTO.java new file mode 100644 index 00000000..dc84bc5d --- /dev/null +++ b/MessageHub/src/main/java/com/xiaowang/messagehub/dto/MessageDTO.java @@ -0,0 +1,44 @@ +package com.xiaowang.messagehub.dto; + +import lombok.Data; +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; +import java.util.Map; + +/** + * 消息队列中推送消息实体类 + * + * @author xiaowang + * @date 2023-03-21 + */ +@Data +public class MessageDTO { + + @NotBlank(message = "接收者不能为空") + @Email(message = "接收者必须是有效的邮箱地址") + private String receiver; + + @NotBlank(message = "渠道类型不能为空") + @Pattern(regexp = "^(EMAIL|SMS|PUSH|WECHAT)$", message = "渠道类型必须是EMAIL、SMS、PUSH或WECHAT") + private String channelType; + + @NotBlank(message = "消息类型不能为空") + @Pattern(regexp = "^(NOTIFICATION|VERIFICATION|PROMOTION|ALERT)$", message = "消息类型必须是NOTIFICATION、VERIFICATION、PROMOTION或ALERT") + private String msgType; + + @NotBlank(message = "模板编码不能为空") + @Size(max = 50, message = "模板编码长度不能超过50") + private String templateCode; + + private Map templateParams; + + @NotBlank(message = "来源系统不能为空") + @Size(max = 50, message = "来源系统长度不能超过50") + private String sourceSystem; + + @NotBlank(message = "唯一标识不能为空") + @Size(max = 100, message = "唯一标识长度不能超过100") + private String uniqueId; +} diff --git a/MessageHub/src/main/java/com/xiaowang/messagehub/entity/Message.java b/MessageHub/src/main/java/com/xiaowang/messagehub/entity/Message.java deleted file mode 100644 index 737dd1b1..00000000 --- a/MessageHub/src/main/java/com/xiaowang/messagehub/entity/Message.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.xiaowang.messagehub.entity; - -import com.baomidou.mybatisplus.annotation.*; -import java.time.LocalDateTime; - -@TableName("message") -public class Message { - @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; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getContent() { - return content; - } - - public void setContent(String content) { - this.content = content; - } - - public String getTopic() { - return topic; - } - - public void setTopic(String topic) { - this.topic = topic; - } - - public Integer getStatus() { - return status; - } - - public void setStatus(Integer status) { - this.status = status; - } - - public LocalDateTime getCreateTime() { - return createTime; - } - - public void setCreateTime(LocalDateTime createTime) { - this.createTime = createTime; - } - - public LocalDateTime getUpdateTime() { - return updateTime; - } - - public void setUpdateTime(LocalDateTime updateTime) { - this.updateTime = updateTime; - } - - public Integer getDeleted() { - return deleted; - } - - public void setDeleted(Integer deleted) { - this.deleted = deleted; - } -} diff --git a/MessageHub/src/main/java/com/xiaowang/messagehub/entity/MessageDO.java b/MessageHub/src/main/java/com/xiaowang/messagehub/entity/MessageDO.java new file mode 100644 index 00000000..2a17ee3d --- /dev/null +++ b/MessageHub/src/main/java/com/xiaowang/messagehub/entity/MessageDO.java @@ -0,0 +1,37 @@ +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("message") +public class MessageDO { + @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; +} diff --git a/MessageHub/src/main/java/com/xiaowang/messagehub/entity/PushLog.java b/MessageHub/src/main/java/com/xiaowang/messagehub/entity/PushLog.java deleted file mode 100644 index de178018..00000000 --- a/MessageHub/src/main/java/com/xiaowang/messagehub/entity/PushLog.java +++ /dev/null @@ -1,161 +0,0 @@ -package com.xiaowang.messagehub.entity; - -import com.baomidou.mybatisplus.annotation.*; -import java.time.LocalDateTime; - -@TableName("push_log") -public class PushLog { - @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("msg_type") - private String msgType; - - @TableField("template_code") - private String templateCode; - - @TableField("template_params") - private String templateParams; - - @TableField("final_content") - private String finalContent; - - @TableField("status") - private Integer status; - - @TableField("retry_count") - private Integer retryCount; - - @TableField("fail_reason") - private String failReason; - - @TableField("send_time") - private LocalDateTime sendTime; - - @TableField(value = "create_time", fill = FieldFill.INSERT) - private LocalDateTime createTime; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getSourceSystem() { - return sourceSystem; - } - - public void setSourceSystem(String sourceSystem) { - this.sourceSystem = sourceSystem; - } - - public String getUniqueId() { - return uniqueId; - } - - public void setUniqueId(String uniqueId) { - this.uniqueId = uniqueId; - } - - public String getReceiver() { - return receiver; - } - - public void setReceiver(String receiver) { - this.receiver = receiver; - } - - public String getChannelType() { - return channelType; - } - - public void setChannelType(String channelType) { - this.channelType = channelType; - } - - public String getMsgType() { - return msgType; - } - - public void setMsgType(String msgType) { - this.msgType = msgType; - } - - public String getTemplateCode() { - return templateCode; - } - - public void setTemplateCode(String templateCode) { - this.templateCode = templateCode; - } - - public String getTemplateParams() { - return templateParams; - } - - public void setTemplateParams(String templateParams) { - this.templateParams = templateParams; - } - - public String getFinalContent() { - return finalContent; - } - - public void setFinalContent(String finalContent) { - this.finalContent = finalContent; - } - - public Integer getStatus() { - return status; - } - - public void setStatus(Integer status) { - this.status = status; - } - - public Integer getRetryCount() { - return retryCount; - } - - public void setRetryCount(Integer retryCount) { - this.retryCount = retryCount; - } - - public String getFailReason() { - return failReason; - } - - public void setFailReason(String failReason) { - this.failReason = failReason; - } - - public LocalDateTime getSendTime() { - return sendTime; - } - - public void setSendTime(LocalDateTime sendTime) { - this.sendTime = sendTime; - } - - public LocalDateTime getCreateTime() { - return createTime; - } - - public void setCreateTime(LocalDateTime createTime) { - this.createTime = createTime; - } -} diff --git a/MessageHub/src/main/java/com/xiaowang/messagehub/entity/PushLogDO.java b/MessageHub/src/main/java/com/xiaowang/messagehub/entity/PushLogDO.java new file mode 100644 index 00000000..d38f5ab8 --- /dev/null +++ b/MessageHub/src/main/java/com/xiaowang/messagehub/entity/PushLogDO.java @@ -0,0 +1,57 @@ +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_log") +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("msg_type") + private String msgType; + + @TableField("template_code") + private String templateCode; + + @TableField("template_params") + private String templateParams; + + @TableField("final_content") + private String finalContent; + + @TableField("status") + private Integer status; + + @TableField("retry_count") + private Integer retryCount; + + @TableField("fail_reason") + private String failReason; + + @TableField("send_time") + private LocalDateTime sendTime; + + @TableField(value = "create_time", fill = FieldFill.INSERT) + private LocalDateTime createTime; +} diff --git a/MessageHub/src/main/java/com/xiaowang/messagehub/entity/PushTemplate.java b/MessageHub/src/main/java/com/xiaowang/messagehub/entity/PushTemplate.java deleted file mode 100644 index f5ed6e1c..00000000 --- a/MessageHub/src/main/java/com/xiaowang/messagehub/entity/PushTemplate.java +++ /dev/null @@ -1,139 +0,0 @@ -package com.xiaowang.messagehub.entity; - -import com.baomidou.mybatisplus.annotation.*; -import java.time.LocalDateTime; - -@TableName("push_template") -public class PushTemplate { - @TableId(value = "id", type = IdType.AUTO) - private Long id; - - @TableField("template_code") - private String templateCode; - - @TableField("template_name") - private String templateName; - - @TableField("channel_type") - private String channelType; - - @TableField("msg_type") - private Integer msgType; - - @TableField("external_id") - private String externalId; - - @TableField("content_pattern") - private String contentPattern; - - @TableField("msg_category") - private Integer msgCategory; - - @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; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getTemplateCode() { - return templateCode; - } - - public void setTemplateCode(String templateCode) { - this.templateCode = templateCode; - } - - public String getTemplateName() { - return templateName; - } - - public void setTemplateName(String templateName) { - this.templateName = templateName; - } - - public String getChannelType() { - return channelType; - } - - public void setChannelType(String channelType) { - this.channelType = channelType; - } - - public Integer getMsgType() { - return msgType; - } - - public void setMsgType(Integer msgType) { - this.msgType = msgType; - } - - public String getExternalId() { - return externalId; - } - - public void setExternalId(String externalId) { - this.externalId = externalId; - } - - public String getContentPattern() { - return contentPattern; - } - - public void setContentPattern(String contentPattern) { - this.contentPattern = contentPattern; - } - - public Integer getMsgCategory() { - return msgCategory; - } - - public void setMsgCategory(Integer msgCategory) { - this.msgCategory = msgCategory; - } - - public Integer getIsEnable() { - return isEnable; - } - - public void setIsEnable(Integer isEnable) { - this.isEnable = isEnable; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public LocalDateTime getCreateTime() { - return createTime; - } - - public void setCreateTime(LocalDateTime createTime) { - this.createTime = createTime; - } - - public LocalDateTime getUpdateTime() { - return updateTime; - } - - public void setUpdateTime(LocalDateTime updateTime) { - this.updateTime = updateTime; - } -} diff --git a/MessageHub/src/main/java/com/xiaowang/messagehub/entity/PushTemplateDO.java b/MessageHub/src/main/java/com/xiaowang/messagehub/entity/PushTemplateDO.java new file mode 100644 index 00000000..03982b59 --- /dev/null +++ b/MessageHub/src/main/java/com/xiaowang/messagehub/entity/PushTemplateDO.java @@ -0,0 +1,51 @@ +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 { + @TableId(value = "id", type = IdType.AUTO) + private Long id; + + @TableField("template_code") + private String templateCode; + + @TableField("template_name") + private String templateName; + + @TableField("channel_type") + private String channelType; + + @TableField("msg_type") + private Integer msgType; + + @TableField("external_id") + private String externalId; + + @TableField("content_pattern") + private String contentPattern; + + @TableField("msg_category") + private Integer msgCategory; + + @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; +} diff --git a/MessageHub/src/main/java/com/xiaowang/messagehub/health/ConnectionHealthChecker.java b/MessageHub/src/main/java/com/xiaowang/messagehub/health/ConnectionHealthChecker.java index 379d4e49..c2aa8b4b 100644 --- a/MessageHub/src/main/java/com/xiaowang/messagehub/health/ConnectionHealthChecker.java +++ b/MessageHub/src/main/java/com/xiaowang/messagehub/health/ConnectionHealthChecker.java @@ -6,10 +6,15 @@ import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; +/** + * 连接健康检查类 + * + * @author xiaowang + * @date 2023-03-21 + */ @Component public class ConnectionHealthChecker { diff --git a/MessageHub/src/main/java/com/xiaowang/messagehub/listener/ApplicationStartupListener.java b/MessageHub/src/main/java/com/xiaowang/messagehub/listener/ApplicationStartupListener.java index dfe9f923..6a92c5e8 100644 --- a/MessageHub/src/main/java/com/xiaowang/messagehub/listener/ApplicationStartupListener.java +++ b/MessageHub/src/main/java/com/xiaowang/messagehub/listener/ApplicationStartupListener.java @@ -8,6 +8,12 @@ import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; +/** + * 应用启动监听器 + * + * @author xiaowang + * @date 2023-03-21 + */ @Component public class ApplicationStartupListener implements ApplicationListener { diff --git a/MessageHub/src/main/java/com/xiaowang/messagehub/listener/SmsQueueListener.java b/MessageHub/src/main/java/com/xiaowang/messagehub/listener/SmsQueueListener.java new file mode 100644 index 00000000..637f4057 --- /dev/null +++ b/MessageHub/src/main/java/com/xiaowang/messagehub/listener/SmsQueueListener.java @@ -0,0 +1,70 @@ +package com.xiaowang.messagehub.listener; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.rabbitmq.client.Channel; +import com.xiaowang.messagehub.dto.MessageDTO; +import com.xiaowang.messagehub.service.MessageService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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 java.time.LocalDateTime; + +/** + * 短信队列监听器 + * + * @author xiaowang + * @date 2023-03-21 + */ +@Component +public class SmsQueueListener { + + private static final Logger logger = LoggerFactory.getLogger(SmsQueueListener.class); + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private MessageService messageService; + + @RabbitListener(queues = "smsQueue") + public void handleSmsMessage(Message message, Channel channel) { + String messageId = message.getMessageProperties().getMessageId(); + LocalDateTime sendTime = LocalDateTime.now(); + + try { + String messageBody = new String(message.getBody(), "UTF-8"); + logger.info("========================================"); + logger.info("收到短信消息"); + logger.info("消息ID: {}", messageId); + logger.info("消息内容: {}", messageBody); + logger.info("接收时间: {}", sendTime); + logger.info("========================================"); + + MessageDTO messageDTO = objectMapper.readValue(messageBody, MessageDTO.class); + + boolean isValid = messageService.validateAndSaveLog(messageDTO, messageId, sendTime); + + long deliveryTag = message.getMessageProperties().getDeliveryTag(); + channel.basicAck(deliveryTag, false); + + if (isValid) { + logger.info("消息处理成功,消息ID: {}", messageId); + } else { + logger.warn("消息校验失败,消息ID: {}", messageId); + } + } catch (Exception e) { + logger.error("处理短信消息时发生异常,消息ID: {}", messageId, e); + + try { + long deliveryTag = message.getMessageProperties().getDeliveryTag(); + channel.basicAck(deliveryTag, false); + } catch (Exception ackException) { + logger.error("消息确认失败", ackException); + } + } + } +} diff --git a/MessageHub/src/main/java/com/xiaowang/messagehub/mapper/MessageMapper.java b/MessageHub/src/main/java/com/xiaowang/messagehub/mapper/MessageMapper.java index 5d740ac9..4406ba56 100644 --- a/MessageHub/src/main/java/com/xiaowang/messagehub/mapper/MessageMapper.java +++ b/MessageHub/src/main/java/com/xiaowang/messagehub/mapper/MessageMapper.java @@ -3,7 +3,7 @@ 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.Message; +import com.xiaowang.messagehub.entity.MessageDO; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; @@ -12,17 +12,23 @@ import org.apache.ibatis.annotations.Update; import java.time.LocalDateTime; import java.util.List; +/** + * 消息Mapper接口 + * + * @author xiaowang + * @date 2023-03-21 + */ @Mapper -public interface MessageMapper extends BaseMapper { +public interface MessageMapper extends BaseMapper { @Select("SELECT * FROM message WHERE topic = #{topic} AND deleted = 0 ORDER BY create_time DESC LIMIT #{limit}") - List selectByTopicWithLimit(@Param("topic") String topic, @Param("limit") int limit); + List selectByTopicWithLimit(@Param("topic") String topic, @Param("limit") int limit); @Select("SELECT * FROM message WHERE status = #{status} AND deleted = 0 ORDER BY create_time DESC LIMIT #{limit}") - List selectByStatusWithLimit(@Param("status") Integer status, @Param("limit") int limit); + List selectByStatusWithLimit(@Param("status") Integer status, @Param("limit") int limit); @Select("SELECT * FROM message WHERE topic = #{topic} AND status = #{status} AND deleted = 0 ORDER BY create_time DESC") - List selectByTopicAndStatus(@Param("topic") String topic, @Param("status") Integer status); + List selectByTopicAndStatus(@Param("topic") String topic, @Param("status") Integer status); @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); @@ -34,15 +40,14 @@ public interface MessageMapper extends BaseMapper { long countByStatus(@Param("status") Integer status); @Select("SELECT * FROM message WHERE deleted = 0 ORDER BY create_time DESC") - IPage selectPage(Page page); + IPage selectPage(Page page); @Select("SELECT * FROM message WHERE topic = #{topic} AND deleted = 0 ORDER BY create_time DESC") - IPage selectPageByTopic(Page page, @Param("topic") String topic); + IPage selectPageByTopic(Page page, @Param("topic") String topic); @Select("SELECT * FROM message WHERE create_time >= #{startTime} AND create_time <= #{endTime} AND deleted = 0 ORDER BY create_time DESC") - List selectByTimeRange(@Param("startTime") LocalDateTime startTime, @Param("endTime") LocalDateTime endTime); + List selectByTimeRange(@Param("startTime") LocalDateTime startTime, @Param("endTime") LocalDateTime endTime); @Select("SELECT * FROM message WHERE content LIKE CONCAT('%', #{keyword}, '%') AND deleted = 0 ORDER BY create_time DESC LIMIT #{limit}") - List searchByContent(@Param("keyword") String keyword, @Param("limit") int limit); + List searchByContent(@Param("keyword") String keyword, @Param("limit") int limit); } - diff --git a/MessageHub/src/main/java/com/xiaowang/messagehub/mapper/PushLogMapper.java b/MessageHub/src/main/java/com/xiaowang/messagehub/mapper/PushLogMapper.java index 94a5d155..d9eddc33 100644 --- a/MessageHub/src/main/java/com/xiaowang/messagehub/mapper/PushLogMapper.java +++ b/MessageHub/src/main/java/com/xiaowang/messagehub/mapper/PushLogMapper.java @@ -3,7 +3,7 @@ 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.PushLog; +import com.xiaowang.messagehub.entity.PushLogDO; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; @@ -12,26 +12,32 @@ import org.apache.ibatis.annotations.Update; import java.time.LocalDateTime; import java.util.List; +/** + * 推送日志Mapper接口 + * + * @author xiaowang + * @date 2023-03-21 + */ @Mapper -public interface PushLogMapper extends BaseMapper { +public interface PushLogMapper extends BaseMapper { @Select("SELECT * FROM push_log WHERE source_system = #{sourceSystem} ORDER BY create_time DESC LIMIT #{limit}") - List selectBySourceSystemWithLimit(@Param("sourceSystem") String sourceSystem, @Param("limit") int limit); + List selectBySourceSystemWithLimit(@Param("sourceSystem") String sourceSystem, @Param("limit") int limit); @Select("SELECT * FROM push_log WHERE receiver = #{receiver} ORDER BY create_time DESC LIMIT #{limit}") - List selectByReceiverWithLimit(@Param("receiver") String receiver, @Param("limit") int limit); + List selectByReceiverWithLimit(@Param("receiver") String receiver, @Param("limit") int limit); @Select("SELECT * FROM push_log WHERE channel_type = #{channelType} ORDER BY create_time DESC LIMIT #{limit}") - List selectByChannelTypeWithLimit(@Param("channelType") String channelType, @Param("limit") int limit); + List selectByChannelTypeWithLimit(@Param("channelType") String channelType, @Param("limit") int limit); @Select("SELECT * FROM push_log WHERE status = #{status} ORDER BY create_time DESC LIMIT #{limit}") - List selectByStatusWithLimit(@Param("status") Integer status, @Param("limit") int limit); + List selectByStatusWithLimit(@Param("status") Integer status, @Param("limit") int limit); @Select("SELECT * FROM push_log WHERE source_system = #{sourceSystem} AND status = #{status} ORDER BY create_time DESC") - List selectBySourceSystemAndStatus(@Param("sourceSystem") String sourceSystem, @Param("status") Integer status); + List selectBySourceSystemAndStatus(@Param("sourceSystem") String sourceSystem, @Param("status") Integer status); @Select("SELECT * FROM push_log WHERE unique_id = #{uniqueId}") - PushLog selectByUniqueId(@Param("uniqueId") String uniqueId); + PushLogDO selectByUniqueId(@Param("uniqueId") String uniqueId); @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); @@ -46,14 +52,14 @@ public interface PushLogMapper extends BaseMapper { long countByStatus(@Param("status") Integer status); @Select("SELECT * FROM push_log ORDER BY create_time DESC") - IPage selectPage(Page page); + IPage selectPage(Page page); @Select("SELECT * FROM push_log WHERE source_system = #{sourceSystem} ORDER BY create_time DESC") - IPage selectPageBySourceSystem(Page page, @Param("sourceSystem") String sourceSystem); + IPage selectPageBySourceSystem(Page page, @Param("sourceSystem") String sourceSystem); @Select("SELECT * FROM push_log WHERE create_time >= #{startTime} AND create_time <= #{endTime} ORDER BY create_time DESC") - List selectByTimeRange(@Param("startTime") LocalDateTime startTime, @Param("endTime") LocalDateTime endTime); + List selectByTimeRange(@Param("startTime") LocalDateTime startTime, @Param("endTime") LocalDateTime endTime); @Select("SELECT * FROM push_log WHERE final_content LIKE CONCAT('%', #{keyword}, '%') ORDER BY create_time DESC LIMIT #{limit}") - List searchByContent(@Param("keyword") String keyword, @Param("limit") int limit); + List searchByContent(@Param("keyword") String keyword, @Param("limit") int limit); } diff --git a/MessageHub/src/main/java/com/xiaowang/messagehub/mapper/PushTemplateMapper.java b/MessageHub/src/main/java/com/xiaowang/messagehub/mapper/PushTemplateMapper.java index 59106d05..4b20aff9 100644 --- a/MessageHub/src/main/java/com/xiaowang/messagehub/mapper/PushTemplateMapper.java +++ b/MessageHub/src/main/java/com/xiaowang/messagehub/mapper/PushTemplateMapper.java @@ -3,7 +3,7 @@ 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.PushTemplate; +import com.xiaowang.messagehub.entity.PushTemplateDO; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; @@ -11,20 +11,26 @@ import org.apache.ibatis.annotations.Update; import java.util.List; +/** + * 推送模板Mapper接口 + * + * @author xiaowang + * @date 2023-03-21 + */ @Mapper -public interface PushTemplateMapper extends BaseMapper { +public interface PushTemplateMapper extends BaseMapper { @Select("SELECT * FROM push_template WHERE template_code = #{templateCode}") - PushTemplate selectByTemplateCode(@Param("templateCode") String templateCode); + PushTemplateDO selectByTemplateCode(@Param("templateCode") String templateCode); @Select("SELECT * FROM push_template WHERE channel_type = #{channelType} ORDER BY create_time DESC") - List selectByChannelType(@Param("channelType") String channelType); + List selectByChannelType(@Param("channelType") String channelType); @Select("SELECT * FROM push_template WHERE is_enable = 1 ORDER BY create_time DESC") - List selectEnabledTemplates(); + List selectEnabledTemplates(); @Select("SELECT * FROM push_template WHERE channel_type = #{channelType} AND is_enable = 1 ORDER BY create_time DESC") - List selectEnabledByChannelType(@Param("channelType") String channelType); + List selectEnabledByChannelType(@Param("channelType") String channelType); @Update("UPDATE push_template SET is_enable = #{isEnable} WHERE id = #{id}") int updateEnableStatus(@Param("id") Long id, @Param("isEnable") Integer isEnable); @@ -36,11 +42,11 @@ public interface PushTemplateMapper extends BaseMapper { long countEnabledTemplates(); @Select("SELECT * FROM push_template ORDER BY create_time DESC") - IPage selectPage(Page page); + IPage selectPage(Page page); @Select("SELECT * FROM push_template WHERE channel_type = #{channelType} ORDER BY create_time DESC") - IPage selectPageByChannelType(Page page, @Param("channelType") String channelType); + IPage selectPageByChannelType(Page page, @Param("channelType") String channelType); @Select("SELECT * FROM push_template WHERE template_name LIKE CONCAT('%', #{keyword}, '%') OR description LIKE CONCAT('%', #{keyword}, '%')") - List searchByKeyword(@Param("keyword") String keyword); + List searchByKeyword(@Param("keyword") String keyword); } diff --git a/MessageHub/src/main/java/com/xiaowang/messagehub/service/MessageService.java b/MessageHub/src/main/java/com/xiaowang/messagehub/service/MessageService.java new file mode 100644 index 00000000..bdf35b13 --- /dev/null +++ b/MessageHub/src/main/java/com/xiaowang/messagehub/service/MessageService.java @@ -0,0 +1,88 @@ +package com.xiaowang.messagehub.service; + +import com.xiaowang.messagehub.dto.MessageDTO; +import com.xiaowang.messagehub.entity.PushLogDO; +import com.xiaowang.messagehub.mapper.PushLogMapper; +import com.xiaowang.messagehub.mapper.PushTemplateMapper; +import com.xiaowang.messagehub.entity.PushTemplateDO; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.validation.ConstraintViolation; +import javax.validation.Validator; +import java.time.LocalDateTime; +import java.util.Set; + +/** + * 消息服务类 + * + * @author xiaowang + * @date 2023-03-21 + */ +@Service +public class MessageService { + + private static final Logger logger = LoggerFactory.getLogger(MessageService.class); + + @Autowired + private Validator validator; + + @Autowired + private PushLogMapper pushLogMapper; + + @Autowired + private PushTemplateMapper pushTemplateMapper; + + public boolean validateAndSaveLog(MessageDTO messageDTO, String messageId, LocalDateTime sendTime) { + Set> violations = validator.validate(messageDTO); + + PushLogDO pushLog = new PushLogDO(); + pushLog.setId(messageId); + pushLog.setSourceSystem(messageDTO.getSourceSystem()); + pushLog.setUniqueId(messageDTO.getUniqueId()); + pushLog.setReceiver(messageDTO.getReceiver()); + pushLog.setChannelType(messageDTO.getChannelType()); + pushLog.setMsgType(messageDTO.getMsgType()); + pushLog.setTemplateCode(messageDTO.getTemplateCode()); + pushLog.setTemplateParams(messageDTO.getTemplateParams() != null ? messageDTO.getTemplateParams().toString() : null); + pushLog.setSendTime(sendTime); + pushLog.setRetryCount(0); + + if (violations.isEmpty()) { + pushLog.setStatus(0); + pushLog.setFailReason(null); + pushLogMapper.insert(pushLog); + logger.info("参数校验通过,消息ID: {}", messageId); + return true; + } else { + StringBuilder errorBuilder = new StringBuilder(); + for (ConstraintViolation violation : violations) { + errorBuilder.append(violation.getMessage()).append("; "); + } + String failReason = errorBuilder.toString(); + pushLog.setStatus(2); + pushLog.setFailReason(failReason); + pushLogMapper.insert(pushLog); + logger.error("参数校验失败,消息ID: {}, 错误: {}", messageId, failReason); + return false; + } + } + + public PushTemplateDO getTemplateByCode(String templateCode) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(PushTemplateDO::getTemplateCode, templateCode) + .eq(PushTemplateDO::getIsEnable, 1); + return pushTemplateMapper.selectOne(wrapper); + } + + public void updatePushLogStatus(String messageId, Integer status, String failReason) { + PushLogDO pushLog = new PushLogDO(); + pushLog.setId(messageId); + pushLog.setStatus(status); + pushLog.setFailReason(failReason); + pushLogMapper.updateById(pushLog); + } +} diff --git a/MessageHub/src/main/resources/sql/init.sql b/MessageHub/src/main/resources/sql/init.sql index 7c6a0a04..ecd30c2d 100644 --- a/MessageHub/src/main/resources/sql/init.sql +++ b/MessageHub/src/main/resources/sql/init.sql @@ -2,7 +2,7 @@ CREATE DATABASE IF NOT EXISTS messagehub DEFAULT CHARACTER SET utf8mb4 COLLATE u USE messagehub; -CREATE TABLE IF NOT EXISTS message ( +CREATE TABLE IF NOT EXISTS messageDO ( id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID', content TEXT NOT NULL COMMENT '消息内容', topic VARCHAR(255) NOT NULL COMMENT '消息主题',