功能:新增消息队列监听器和参数校验

This commit is contained in:
xiaowang
2026-02-11 09:49:11 +08:00
parent da7a7b9889
commit a9a8ba2806
22 changed files with 506 additions and 418 deletions
+11
View File
@@ -102,6 +102,17 @@
<version>1.2.23</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
@@ -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 {
@@ -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());
}
}
@@ -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 {
@@ -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 {
@@ -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 {
@@ -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;
}
}
@@ -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<String, Object> templateParams;
@NotBlank(message = "来源系统不能为空")
@Size(max = 50, message = "来源系统长度不能超过50")
private String sourceSystem;
@NotBlank(message = "唯一标识不能为空")
@Size(max = 100, message = "唯一标识长度不能超过100")
private String uniqueId;
}
@@ -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;
}
}
@@ -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;
}
@@ -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;
}
}
@@ -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;
}
@@ -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;
}
}
@@ -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;
}
@@ -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 {
@@ -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<ApplicationReadyEvent> {
@@ -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);
}
}
}
}
@@ -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<Message> {
public interface MessageMapper extends BaseMapper<MessageDO> {
@Select("SELECT * FROM message WHERE topic = #{topic} AND deleted = 0 ORDER BY create_time DESC LIMIT #{limit}")
List<Message> selectByTopicWithLimit(@Param("topic") String topic, @Param("limit") int limit);
List<MessageDO> 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<Message> selectByStatusWithLimit(@Param("status") Integer status, @Param("limit") int limit);
List<MessageDO> 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<Message> selectByTopicAndStatus(@Param("topic") String topic, @Param("status") Integer status);
List<MessageDO> 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<Message> {
long countByStatus(@Param("status") Integer status);
@Select("SELECT * FROM message WHERE deleted = 0 ORDER BY create_time DESC")
IPage<Message> selectPage(Page<Message> page);
IPage<MessageDO> selectPage(Page<MessageDO> page);
@Select("SELECT * FROM message WHERE topic = #{topic} AND deleted = 0 ORDER BY create_time DESC")
IPage<Message> selectPageByTopic(Page<Message> page, @Param("topic") String topic);
IPage<MessageDO> selectPageByTopic(Page<MessageDO> 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<Message> selectByTimeRange(@Param("startTime") LocalDateTime startTime, @Param("endTime") LocalDateTime endTime);
List<MessageDO> 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<Message> searchByContent(@Param("keyword") String keyword, @Param("limit") int limit);
List<MessageDO> searchByContent(@Param("keyword") String keyword, @Param("limit") int limit);
}
@@ -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<PushLog> {
public interface PushLogMapper extends BaseMapper<PushLogDO> {
@Select("SELECT * FROM push_log WHERE source_system = #{sourceSystem} ORDER BY create_time DESC LIMIT #{limit}")
List<PushLog> selectBySourceSystemWithLimit(@Param("sourceSystem") String sourceSystem, @Param("limit") int limit);
List<PushLogDO> 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<PushLog> selectByReceiverWithLimit(@Param("receiver") String receiver, @Param("limit") int limit);
List<PushLogDO> 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<PushLog> selectByChannelTypeWithLimit(@Param("channelType") String channelType, @Param("limit") int limit);
List<PushLogDO> 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<PushLog> selectByStatusWithLimit(@Param("status") Integer status, @Param("limit") int limit);
List<PushLogDO> 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<PushLog> selectBySourceSystemAndStatus(@Param("sourceSystem") String sourceSystem, @Param("status") Integer status);
List<PushLogDO> 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<PushLog> {
long countByStatus(@Param("status") Integer status);
@Select("SELECT * FROM push_log ORDER BY create_time DESC")
IPage<PushLog> selectPage(Page<PushLog> page);
IPage<PushLogDO> selectPage(Page<PushLogDO> page);
@Select("SELECT * FROM push_log WHERE source_system = #{sourceSystem} ORDER BY create_time DESC")
IPage<PushLog> selectPageBySourceSystem(Page<PushLog> page, @Param("sourceSystem") String sourceSystem);
IPage<PushLogDO> selectPageBySourceSystem(Page<PushLogDO> page, @Param("sourceSystem") String sourceSystem);
@Select("SELECT * FROM push_log WHERE create_time >= #{startTime} AND create_time <= #{endTime} ORDER BY create_time DESC")
List<PushLog> selectByTimeRange(@Param("startTime") LocalDateTime startTime, @Param("endTime") LocalDateTime endTime);
List<PushLogDO> 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<PushLog> searchByContent(@Param("keyword") String keyword, @Param("limit") int limit);
List<PushLogDO> searchByContent(@Param("keyword") String keyword, @Param("limit") int limit);
}
@@ -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<PushTemplate> {
public interface PushTemplateMapper extends BaseMapper<PushTemplateDO> {
@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<PushTemplate> selectByChannelType(@Param("channelType") String channelType);
List<PushTemplateDO> selectByChannelType(@Param("channelType") String channelType);
@Select("SELECT * FROM push_template WHERE is_enable = 1 ORDER BY create_time DESC")
List<PushTemplate> selectEnabledTemplates();
List<PushTemplateDO> selectEnabledTemplates();
@Select("SELECT * FROM push_template WHERE channel_type = #{channelType} AND is_enable = 1 ORDER BY create_time DESC")
List<PushTemplate> selectEnabledByChannelType(@Param("channelType") String channelType);
List<PushTemplateDO> 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<PushTemplate> {
long countEnabledTemplates();
@Select("SELECT * FROM push_template ORDER BY create_time DESC")
IPage<PushTemplate> selectPage(Page<PushTemplate> page);
IPage<PushTemplateDO> selectPage(Page<PushTemplateDO> page);
@Select("SELECT * FROM push_template WHERE channel_type = #{channelType} ORDER BY create_time DESC")
IPage<PushTemplate> selectPageByChannelType(Page<PushTemplate> page, @Param("channelType") String channelType);
IPage<PushTemplateDO> selectPageByChannelType(Page<PushTemplateDO> page, @Param("channelType") String channelType);
@Select("SELECT * FROM push_template WHERE template_name LIKE CONCAT('%', #{keyword}, '%') OR description LIKE CONCAT('%', #{keyword}, '%')")
List<PushTemplate> searchByKeyword(@Param("keyword") String keyword);
List<PushTemplateDO> searchByKeyword(@Param("keyword") String keyword);
}
@@ -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<ConstraintViolation<MessageDTO>> 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<MessageDTO> 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<PushTemplateDO> 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);
}
}
+1 -1
View File
@@ -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 '消息主题',