refactor(sms): 重构短信发送功能并优化数据库配置
- 移除旧的短信发送实现和相关依赖 - 引入新的短信发送服务接口和实现 - 添加短信发送记录实体和数据访问层 - 创建短信发送控制器提供REST API - 实现带重试机制的短信发送功能 - 添加系统凭证管理和缓存机制 - 更新数据库连接配置信息 - 修改统计查询接口参数类型 - 清理过时的代码和服务方法
This commit is contained in:
@@ -21,7 +21,7 @@ public class GenerateCode {
|
|||||||
|
|
||||||
private static final String TARGET_DIR = "D://code";
|
private static final String TARGET_DIR = "D://code";
|
||||||
|
|
||||||
private static final String DB_URL = "jdbc:mysql://192.168.1.24:13306/pqsinfo_ln";
|
private static final String DB_URL = "jdbc:mysql://192.168.1.103:13306/pqsinfo_zl";
|
||||||
// private static final String DB_URL = "jdbc:oracle:thin:@192.168.1.170:1521:pqsbase";
|
// private static final String DB_URL = "jdbc:oracle:thin:@192.168.1.170:1521:pqsbase";
|
||||||
|
|
||||||
private static final String USERNAME = "root";
|
private static final String USERNAME = "root";
|
||||||
@@ -30,8 +30,8 @@ public class GenerateCode {
|
|||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
List<Module> modules = Stream.of(
|
List<Module> modules = Stream.of(
|
||||||
new Module("cdf", "com.njcn.device", "", Stream.of(
|
new Module("xy", "com.njcn.csdevice", "", Stream.of(
|
||||||
"pq_icd_path"
|
"cs_alarm_set"
|
||||||
).collect(Collectors.toList()), "")
|
).collect(Collectors.toList()), "")
|
||||||
).collect(Collectors.toList());
|
).collect(Collectors.toList());
|
||||||
generateJavaFile(modules);
|
generateJavaFile(modules);
|
||||||
|
|||||||
@@ -1,16 +1,20 @@
|
|||||||
package com.njcn.system.api;
|
package com.njcn.system.api;
|
||||||
|
|
||||||
|
|
||||||
|
import com.njcn.common.pojo.annotation.OperateInfo;
|
||||||
import com.njcn.common.pojo.constant.ServerInfo;
|
import com.njcn.common.pojo.constant.ServerInfo;
|
||||||
|
import com.njcn.common.pojo.enums.common.LogEnum;
|
||||||
|
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
|
||||||
import com.njcn.common.pojo.response.HttpResult;
|
import com.njcn.common.pojo.response.HttpResult;
|
||||||
|
import com.njcn.common.utils.HttpResultUtil;
|
||||||
import com.njcn.system.api.fallback.CsStatistiacalFeignClientFallbackFactory;
|
import com.njcn.system.api.fallback.CsStatistiacalFeignClientFallbackFactory;
|
||||||
|
import com.njcn.system.pojo.po.CsStatisticalSetPO;
|
||||||
import com.njcn.system.pojo.po.EleEpdPqd;
|
import com.njcn.system.pojo.po.EleEpdPqd;
|
||||||
import com.njcn.system.pojo.vo.CsStatisticalSetVO;
|
import com.njcn.system.pojo.vo.CsStatisticalSetVO;
|
||||||
|
import io.swagger.annotations.ApiOperation;
|
||||||
import org.springframework.cloud.openfeign.FeignClient;
|
import org.springframework.cloud.openfeign.FeignClient;
|
||||||
import org.springframework.web.bind.annotation.PostMapping;
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
import org.springframework.web.bind.annotation.RequestParam;
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -35,10 +39,12 @@ public interface CsStatisticalSetFeignClient {
|
|||||||
HttpResult<CsStatisticalSetVO> queryStatistical(@RequestParam("id")String id);
|
HttpResult<CsStatisticalSetVO> queryStatistical(@RequestParam("id")String id);
|
||||||
|
|
||||||
@PostMapping("/queryStatisticalSelect")
|
@PostMapping("/queryStatisticalSelect")
|
||||||
HttpResult<List<EleEpdPqd>> queryStatisticalSelect(@RequestParam("id")String id);
|
@ApiOperation("根据统计类型id组查询已绑定指标")
|
||||||
|
HttpResult<List<EleEpdPqd>> queryStatisticalSelect(@RequestBody List<String> list);
|
||||||
|
|
||||||
|
|
||||||
|
@PostMapping("/queryStatisticalById")
|
||||||
|
@ApiOperation("根据id查询数据")
|
||||||
|
HttpResult<List<CsStatisticalSetPO>> queryStatisticalById(@RequestBody List<String> list);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,12 +3,8 @@ package com.njcn.system.api.fallback;
|
|||||||
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
|
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
|
||||||
import com.njcn.common.pojo.exception.BusinessException;
|
import com.njcn.common.pojo.exception.BusinessException;
|
||||||
import com.njcn.common.pojo.response.HttpResult;
|
import com.njcn.common.pojo.response.HttpResult;
|
||||||
import com.njcn.system.api.AreaFeignClient;
|
|
||||||
import com.njcn.system.api.ConfigFeignClient;
|
|
||||||
import com.njcn.system.api.CsStatisticalSetFeignClient;
|
import com.njcn.system.api.CsStatisticalSetFeignClient;
|
||||||
import com.njcn.system.pojo.dto.AreaTreeDTO;
|
import com.njcn.system.pojo.po.CsStatisticalSetPO;
|
||||||
import com.njcn.system.pojo.po.Area;
|
|
||||||
import com.njcn.system.pojo.po.Config;
|
|
||||||
import com.njcn.system.pojo.po.EleEpdPqd;
|
import com.njcn.system.pojo.po.EleEpdPqd;
|
||||||
import com.njcn.system.pojo.vo.CsStatisticalSetVO;
|
import com.njcn.system.pojo.vo.CsStatisticalSetVO;
|
||||||
import com.njcn.system.utils.SystemEnumUtil;
|
import com.njcn.system.utils.SystemEnumUtil;
|
||||||
@@ -56,9 +52,16 @@ public class CsStatistiacalFeignClientFallbackFactory implements FallbackFactory
|
|||||||
throw new BusinessException(finalExceptionEnum); }
|
throw new BusinessException(finalExceptionEnum); }
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public HttpResult<List<EleEpdPqd>> queryStatisticalSelect(String id) {
|
public HttpResult<List<EleEpdPqd>> queryStatisticalSelect(List<String> list) {
|
||||||
log.error("{}异常,降级处理,异常为:{}","根据统计类型id查询已绑定指标下拉框",cause.toString());
|
log.error("{}异常,降级处理,异常为:{}","根据统计类型id查询已绑定指标下拉框",cause.toString());
|
||||||
throw new BusinessException(finalExceptionEnum); }
|
throw new BusinessException(finalExceptionEnum);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public HttpResult<List<CsStatisticalSetPO>> queryStatisticalById(List<String> list) {
|
||||||
|
log.error("{}异常,降级处理,异常为:{}","根据id查询数据异常",cause.toString());
|
||||||
|
throw new BusinessException(finalExceptionEnum);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,13 +6,11 @@ import com.njcn.common.pojo.enums.common.LogEnum;
|
|||||||
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
|
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
|
||||||
import com.njcn.common.pojo.response.HttpResult;
|
import com.njcn.common.pojo.response.HttpResult;
|
||||||
import com.njcn.common.utils.HttpResultUtil;
|
import com.njcn.common.utils.HttpResultUtil;
|
||||||
|
|
||||||
import com.njcn.system.pojo.param.CsStatisticalSetAddParam;
|
import com.njcn.system.pojo.param.CsStatisticalSetAddParam;
|
||||||
|
import com.njcn.system.pojo.po.CsStatisticalSetPO;
|
||||||
import com.njcn.system.pojo.po.EleEpdPqd;
|
import com.njcn.system.pojo.po.EleEpdPqd;
|
||||||
import com.njcn.system.pojo.vo.CsStatisticalSetVO;
|
import com.njcn.system.pojo.vo.CsStatisticalSetVO;
|
||||||
|
|
||||||
import com.njcn.system.service.CsStatisticalSetPOService;
|
import com.njcn.system.service.CsStatisticalSetPOService;
|
||||||
|
|
||||||
import com.njcn.web.controller.BaseController;
|
import com.njcn.web.controller.BaseController;
|
||||||
import io.swagger.annotations.Api;
|
import io.swagger.annotations.Api;
|
||||||
import io.swagger.annotations.ApiOperation;
|
import io.swagger.annotations.ApiOperation;
|
||||||
@@ -64,17 +62,22 @@ public class CsStatisticalSetController extends BaseController {
|
|||||||
@PostMapping("/queryStatisticalSelect")
|
@PostMapping("/queryStatisticalSelect")
|
||||||
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
|
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
|
||||||
@ApiOperation("根据统计类型id组查询已绑定指标")
|
@ApiOperation("根据统计类型id组查询已绑定指标")
|
||||||
public HttpResult<List<EleEpdPqd>> queryStatisticalSelect(@RequestParam("id")String id){
|
public HttpResult<List<EleEpdPqd>> queryStatisticalSelect(@RequestBody List<String> list){
|
||||||
log.info("根据模板录入字典数据");
|
log.info("根据模板录入字典数据");
|
||||||
String methodDescribe = getMethodDescribe("EleEpdPqd");
|
String methodDescribe = getMethodDescribe("queryStatisticalSelect");
|
||||||
List<EleEpdPqd> result = csStatisticalSetPOService.queryStatisticalSelect(id);
|
List<EleEpdPqd> result = csStatisticalSetPOService.queryStatisticalSelect(list);
|
||||||
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PostMapping("/queryStatisticalById")
|
||||||
|
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
|
||||||
|
@ApiOperation("根据id查询数据")
|
||||||
|
public HttpResult<List<CsStatisticalSetPO>> queryStatisticalById(@RequestBody List<String> list){
|
||||||
|
log.info("根据模板录入字典数据");
|
||||||
|
String methodDescribe = getMethodDescribe("queryStatisticalById");
|
||||||
|
List<CsStatisticalSetPO> result = csStatisticalSetPOService.queryStatisticalById(list);
|
||||||
|
return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -23,5 +23,7 @@ public interface CsStatisticalSetPOService extends IMppService<CsStatisticalSetP
|
|||||||
|
|
||||||
CsStatisticalSetVO queryStatistical(String id);
|
CsStatisticalSetVO queryStatistical(String id);
|
||||||
|
|
||||||
List<EleEpdPqd> queryStatisticalSelect(String id);
|
List<EleEpdPqd> queryStatisticalSelect(List<String> list);
|
||||||
|
|
||||||
|
List<CsStatisticalSetPO> queryStatisticalById(List<String> list);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,7 +18,10 @@ import org.springframework.stereotype.Service;
|
|||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
import org.springframework.util.CollectionUtils;
|
import org.springframework.util.CollectionUtils;
|
||||||
|
|
||||||
import java.util.*;
|
import java.util.ArrayList;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -108,9 +111,9 @@ public class CsStatisticalSetPOServiceImpl extends MppServiceImpl<CsStatisticalS
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<EleEpdPqd> queryStatisticalSelect(String id) {
|
public List<EleEpdPqd> queryStatisticalSelect(List<String> list) {
|
||||||
QueryWrapper<CsStatisticalSetPO> queryWrap = new QueryWrapper<>();
|
QueryWrapper<CsStatisticalSetPO> queryWrap = new QueryWrapper<>();
|
||||||
queryWrap.lambda().eq(CsStatisticalSetPO::getStatisicalId, id);
|
queryWrap.lambda().in(CsStatisticalSetPO::getStatisicalId, list);
|
||||||
List<CsStatisticalSetPO> result = this.baseMapper.selectList(queryWrap);
|
List<CsStatisticalSetPO> result = this.baseMapper.selectList(queryWrap);
|
||||||
List<String> collect = result.stream().map(CsStatisticalSetPO::getTargetId).collect(Collectors.toList());
|
List<String> collect = result.stream().map(CsStatisticalSetPO::getTargetId).collect(Collectors.toList());
|
||||||
if (CollectionUtils.isEmpty(collect)) {
|
if (CollectionUtils.isEmpty(collect)) {
|
||||||
@@ -118,6 +121,13 @@ public class CsStatisticalSetPOServiceImpl extends MppServiceImpl<CsStatisticalS
|
|||||||
}
|
}
|
||||||
return epdPqdService.listByIds(collect);
|
return epdPqdService.listByIds(collect);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<CsStatisticalSetPO> queryStatisticalById(List<String> list) {
|
||||||
|
QueryWrapper<CsStatisticalSetPO> queryWrap = new QueryWrapper<>();
|
||||||
|
queryWrap.lambda().in(CsStatisticalSetPO::getStatisicalId, list);
|
||||||
|
return this.baseMapper.selectList(queryWrap);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package com.njcn.user.api;
|
||||||
|
|
||||||
|
import com.njcn.common.pojo.constant.ServerInfo;
|
||||||
|
import com.njcn.common.pojo.response.HttpResult;
|
||||||
|
import com.njcn.user.api.fallback.SmsSendClientFallbackFactory;
|
||||||
|
import io.swagger.annotations.ApiOperation;
|
||||||
|
import org.springframework.cloud.openfeign.FeignClient;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author xy
|
||||||
|
*/
|
||||||
|
@FeignClient(value = ServerInfo.USER, path = "/sms", fallbackFactory = SmsSendClientFallbackFactory.class,contextId = "sms")
|
||||||
|
public interface SmsSendFeignClient {
|
||||||
|
|
||||||
|
@PostMapping("/send/simple")
|
||||||
|
@ApiOperation("发送短信(简化参数)")
|
||||||
|
HttpResult<String> sendSmsSimple(@RequestParam("receiver") String receiver
|
||||||
|
, @RequestParam("content") String content
|
||||||
|
, @RequestParam("messageType") String messageType);
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package com.njcn.user.api.fallback;
|
||||||
|
|
||||||
|
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
|
||||||
|
import com.njcn.common.pojo.exception.BusinessException;
|
||||||
|
import com.njcn.common.pojo.response.HttpResult;
|
||||||
|
import com.njcn.user.api.SmsSendFeignClient;
|
||||||
|
import feign.hystrix.FallbackFactory;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author xy
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class SmsSendClientFallbackFactory implements FallbackFactory<SmsSendFeignClient> {
|
||||||
|
@Override
|
||||||
|
public SmsSendFeignClient create(Throwable cause) {
|
||||||
|
//判断抛出异常是否为解码器抛出的业务异常
|
||||||
|
Enum<?> exceptionEnum = CommonResponseEnum.SERVICE_FALLBACK;
|
||||||
|
if (cause.getCause() instanceof BusinessException) {
|
||||||
|
BusinessException businessException = (BusinessException) cause.getCause();
|
||||||
|
}
|
||||||
|
Enum<?> finalExceptionEnum = exceptionEnum;
|
||||||
|
return new SmsSendFeignClient() {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public HttpResult<String> sendSmsSimple(String receiver, String content, String messageType) {
|
||||||
|
log.error("{}异常,降级处理,异常为:{}","发送短信(简化参数)数据异常",cause.toString());
|
||||||
|
throw new BusinessException(finalExceptionEnum);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package com.njcn.user.pojo.dto;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author caozehui
|
||||||
|
* @data 2026-03-31
|
||||||
|
*/
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import javax.validation.constraints.NotEmpty;
|
||||||
|
import java.io.Serializable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 系统凭证请求 DTO
|
||||||
|
*
|
||||||
|
* @author msgpush
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class CredentialReqDTO implements Serializable {
|
||||||
|
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 上游系统名称
|
||||||
|
*/
|
||||||
|
@NotEmpty(message = "上游系统名称不能为空")
|
||||||
|
private String systemName;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 密钥(用于生成凭证)
|
||||||
|
*/
|
||||||
|
@NotEmpty(message = "密钥不能为空")
|
||||||
|
private String secretKey;
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package com.njcn.user.pojo.dto;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author xy
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class SendResult implements Serializable {
|
||||||
|
|
||||||
|
private final boolean success;
|
||||||
|
private final String messageId;
|
||||||
|
private final String failReason;
|
||||||
|
private final boolean isTimeOut;
|
||||||
|
private final boolean unauthorized;
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package com.njcn.user.pojo.po.app;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.*;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author xy
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@TableName("sms_send_record")
|
||||||
|
public class SmsSendRecord implements Serializable {
|
||||||
|
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
@TableId(type = IdType.ASSIGN_ID)
|
||||||
|
private String id;
|
||||||
|
|
||||||
|
private String receiver;
|
||||||
|
|
||||||
|
private String content;
|
||||||
|
|
||||||
|
private String messageType;
|
||||||
|
|
||||||
|
private String credentialToken;
|
||||||
|
|
||||||
|
private Integer sendStatus;
|
||||||
|
|
||||||
|
@TableField(updateStrategy = FieldStrategy.IGNORED)
|
||||||
|
private String failReason;
|
||||||
|
|
||||||
|
private Integer retryCount;
|
||||||
|
|
||||||
|
private Integer maxRetry;
|
||||||
|
|
||||||
|
private Long responseTime;
|
||||||
|
|
||||||
|
private LocalDateTime sendTime;
|
||||||
|
|
||||||
|
private LocalDateTime createTime;
|
||||||
|
|
||||||
|
private LocalDateTime updateTime;
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package com.njcn.user.pojo.vo.app;
|
||||||
|
|
||||||
|
import cn.hutool.core.lang.RegexPool;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import javax.validation.constraints.NotBlank;
|
||||||
|
import javax.validation.constraints.Pattern;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Schema(description = "管理后台 - 消息记录发送 Request VO")
|
||||||
|
public class MessageRecordReqVO {
|
||||||
|
|
||||||
|
private String channel;
|
||||||
|
|
||||||
|
@Schema(description = "消息类型", example = "verify_code/order_notify/marketing/system_notify")
|
||||||
|
@NotBlank(message = "消息类型不能为空")
|
||||||
|
private String messageType;
|
||||||
|
|
||||||
|
@Schema(description = "接收者")
|
||||||
|
@NotBlank(message = "接收者不能为空")
|
||||||
|
@Pattern(regexp = RegexPool.EMAIL + "|" + RegexPool.MOBILE, message = "必须是有效的邮箱或手机号格式")
|
||||||
|
private String receiver;
|
||||||
|
|
||||||
|
@Schema(description = "标题")
|
||||||
|
private String title;
|
||||||
|
|
||||||
|
@Schema(description = "消息内容")
|
||||||
|
private String content;
|
||||||
|
|
||||||
|
@Schema(description = "模板编码")
|
||||||
|
private String templateCode;
|
||||||
|
|
||||||
|
@Schema(description = "模板参数")
|
||||||
|
private String templateParams;
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package com.njcn.user.controller.message;
|
||||||
|
|
||||||
|
import com.njcn.common.pojo.annotation.OperateInfo;
|
||||||
|
import com.njcn.common.pojo.enums.common.LogEnum;
|
||||||
|
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
|
||||||
|
import com.njcn.common.pojo.response.HttpResult;
|
||||||
|
import com.njcn.common.utils.HttpResultUtil;
|
||||||
|
import com.njcn.user.pojo.vo.app.MessageRecordReqVO;
|
||||||
|
import com.njcn.user.service.ISmsSendService;
|
||||||
|
import com.njcn.web.controller.BaseController;
|
||||||
|
import io.swagger.annotations.Api;
|
||||||
|
import io.swagger.annotations.ApiOperation;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author xy
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/sms")
|
||||||
|
@Api(tags = "短信发送管理")
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class SmsSendController extends BaseController {
|
||||||
|
|
||||||
|
private final ISmsSendService smsSendService;
|
||||||
|
|
||||||
|
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
|
||||||
|
@PostMapping("/send")
|
||||||
|
@ApiOperation("发送短信(同步,包含重试)")
|
||||||
|
public HttpResult<String> sendSms(@RequestBody MessageRecordReqVO vo) {
|
||||||
|
String methodDescribe = getMethodDescribe("sendSms");
|
||||||
|
|
||||||
|
try {
|
||||||
|
smsSendService.sendSmsWithRetry(vo);
|
||||||
|
return HttpResultUtil.assembleCommonResponseResult(
|
||||||
|
CommonResponseEnum.SUCCESS,
|
||||||
|
"短信发送成功",
|
||||||
|
methodDescribe
|
||||||
|
);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("短信发送失败", e);
|
||||||
|
return HttpResultUtil.assembleCommonResponseResult(
|
||||||
|
CommonResponseEnum.FAIL,
|
||||||
|
e.getMessage(),
|
||||||
|
methodDescribe
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@OperateInfo(info = LogEnum.BUSINESS_COMMON)
|
||||||
|
@PostMapping("/send/simple")
|
||||||
|
@ApiOperation("发送短信(简化参数)")
|
||||||
|
public HttpResult<String> sendSmsSimple(
|
||||||
|
@RequestParam String receiver,
|
||||||
|
@RequestParam String content,
|
||||||
|
@RequestParam(defaultValue = "verify_code") String messageType) {
|
||||||
|
String methodDescribe = getMethodDescribe("sendSmsSimple");
|
||||||
|
|
||||||
|
try {
|
||||||
|
smsSendService.sendSmsWithRetry(receiver, content, messageType);
|
||||||
|
return HttpResultUtil.assembleCommonResponseResult(
|
||||||
|
CommonResponseEnum.SUCCESS,
|
||||||
|
"短信发送成功",
|
||||||
|
methodDescribe
|
||||||
|
);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("短信发送失败", e);
|
||||||
|
return HttpResultUtil.assembleCommonResponseResult(
|
||||||
|
CommonResponseEnum.FAIL,
|
||||||
|
e.getMessage(),
|
||||||
|
methodDescribe
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package com.njcn.user.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.njcn.user.pojo.po.app.SmsSendRecord;
|
||||||
|
|
||||||
|
public interface CsSmsSendRecordMapper extends BaseMapper<SmsSendRecord> {
|
||||||
|
}
|
||||||
@@ -0,0 +1,416 @@
|
|||||||
|
package com.njcn.user.mapper;
|
||||||
|
|
||||||
|
import com.alibaba.nacos.shaded.com.google.gson.Gson;
|
||||||
|
import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
|
||||||
|
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||||
|
import com.njcn.common.pojo.exception.BusinessException;
|
||||||
|
import com.njcn.redis.utils.RedisUtil;
|
||||||
|
import com.njcn.user.pojo.dto.CredentialReqDTO;
|
||||||
|
import com.njcn.user.pojo.dto.SendResult;
|
||||||
|
import com.njcn.user.pojo.po.app.SmsSendRecord;
|
||||||
|
import com.njcn.user.pojo.vo.app.MessageRecordReqVO;
|
||||||
|
import com.njcn.user.service.ISmsSendService;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import javax.annotation.Resource;
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.net.ConnectException;
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
|
import java.net.SocketTimeoutException;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author xy
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
@AllArgsConstructor
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class SmsSendServiceImpl extends ServiceImpl<CsSmsSendRecordMapper, SmsSendRecord> implements ISmsSendService {
|
||||||
|
|
||||||
|
@Value("${msg.credential_url:http://192.168.2.126:48083/admin-api/push/credential/generate}")
|
||||||
|
private String CREDENTIAL_URL;
|
||||||
|
@Value("${msg.sms_send_url:http://192.168.2.126:48083/admin-api/push/message/send/sms}")
|
||||||
|
private String SMS_SEND_URL;
|
||||||
|
@Value("${msg.connect_timeout:5000}")
|
||||||
|
private Integer CONNECT_TIMEOUT;
|
||||||
|
@Value("${msg.read_timeout:30000}")
|
||||||
|
private Integer READ_TIMEOUT;
|
||||||
|
@Value("${msg.system_name:NPQS-9500}")
|
||||||
|
private String SYSTEM_NAME;
|
||||||
|
@Value("${msg.secret_key:123456}")
|
||||||
|
private String SECRET_KEY;
|
||||||
|
|
||||||
|
private static final int[] RETRY_DELAYS = {1, 2, 3};
|
||||||
|
private static final int MAX_RETRY = 3;
|
||||||
|
private static final String CREDENTIAL_CACHE_KEY = "SMS_CREDENTIAL_TOKEN";
|
||||||
|
private static final Gson GSON = new Gson();
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private RedisUtil redisUtil;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void sendSmsWithRetry(String receiver, String content, String messageType) {
|
||||||
|
MessageRecordReqVO vo = new MessageRecordReqVO();
|
||||||
|
vo.setReceiver(receiver);
|
||||||
|
vo.setContent(content);
|
||||||
|
vo.setMessageType(messageType);
|
||||||
|
sendSmsWithRetry(vo);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void sendSmsWithRetry(MessageRecordReqVO messageRecordReqVO) {
|
||||||
|
SmsSendRecord record = initRecord(messageRecordReqVO);
|
||||||
|
|
||||||
|
this.save(record);
|
||||||
|
|
||||||
|
try {
|
||||||
|
String credentialToken = getOrRefreshCredentialWithRetry(record);
|
||||||
|
|
||||||
|
if (credentialToken == null) {
|
||||||
|
record.setSendStatus(0);
|
||||||
|
record.setFailReason("获取凭证失败,已重试3次");
|
||||||
|
log.error("获取凭证失败,短信未发送,接收者: {}", messageRecordReqVO.getReceiver());
|
||||||
|
this.updateById(record);
|
||||||
|
throw new BusinessException("获取凭证失败,已重试3次");
|
||||||
|
}
|
||||||
|
|
||||||
|
record.setCredentialToken(credentialToken);
|
||||||
|
record.setSendTime(LocalDateTime.now());
|
||||||
|
this.updateById(record);
|
||||||
|
|
||||||
|
boolean success = attemptSendWithRetry(messageRecordReqVO, credentialToken, record);
|
||||||
|
|
||||||
|
if (success) {
|
||||||
|
record.setSendStatus(1);
|
||||||
|
record.setFailReason(null);
|
||||||
|
log.info("短信发送成功,接收者: {}", messageRecordReqVO.getReceiver());
|
||||||
|
} else {
|
||||||
|
record.setSendStatus(0);
|
||||||
|
if (record.getFailReason() == null) {
|
||||||
|
record.setFailReason("超过最大重试次数,发送失败");
|
||||||
|
}
|
||||||
|
log.error("短信发送失败,接收者: {},已重试{}次,原因: {}",
|
||||||
|
messageRecordReqVO.getReceiver(), record.getRetryCount(), record.getFailReason());
|
||||||
|
throw new BusinessException("短信发送失败: " + record.getFailReason());
|
||||||
|
}
|
||||||
|
} catch (BusinessException e) {
|
||||||
|
record.setSendStatus(0);
|
||||||
|
record.setFailReason(e.getMessage());
|
||||||
|
log.error("短信发送业务异常,接收者: {}", messageRecordReqVO.getReceiver(), e);
|
||||||
|
this.updateById(record);
|
||||||
|
throw e;
|
||||||
|
} catch (Exception e) {
|
||||||
|
record.setSendStatus(0);
|
||||||
|
record.setFailReason("发送异常: " + e.getMessage());
|
||||||
|
log.error("短信发送异常,接收者: {}", messageRecordReqVO.getReceiver(), e);
|
||||||
|
this.updateById(record);
|
||||||
|
throw new BusinessException("短信发送异常: " + e.getMessage());
|
||||||
|
} finally {
|
||||||
|
this.updateById(record);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private SmsSendRecord initRecord(MessageRecordReqVO vo) {
|
||||||
|
SmsSendRecord record = new SmsSendRecord();
|
||||||
|
record.setReceiver(vo.getReceiver());
|
||||||
|
record.setContent(vo.getContent());
|
||||||
|
record.setMessageType(vo.getMessageType());
|
||||||
|
record.setSendStatus(-1);
|
||||||
|
record.setRetryCount(0);
|
||||||
|
record.setMaxRetry(MAX_RETRY);
|
||||||
|
record.setCreateTime(LocalDateTime.now());
|
||||||
|
return record;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getOrRefreshCredentialWithRetry(SmsSendRecord record) {
|
||||||
|
Object cachedToken = redisUtil.getObjectByKey(CREDENTIAL_CACHE_KEY);
|
||||||
|
if (cachedToken != null) {
|
||||||
|
log.info("使用缓存的凭证令牌");
|
||||||
|
return cachedToken.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("缓存中无凭证,开始获取新凭证(最多重试3次)");
|
||||||
|
|
||||||
|
for (int i = 1; i <= 3; i++) {
|
||||||
|
try {
|
||||||
|
String token = fetchNewCredential();
|
||||||
|
log.info("第{}次尝试获取凭证成功", i);
|
||||||
|
return token;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("第{}次获取凭证失败: {}", i, e.getMessage());
|
||||||
|
|
||||||
|
record.setFailReason("获取凭证第" + i + "次失败: " + e.getMessage());
|
||||||
|
this.updateById(record);
|
||||||
|
|
||||||
|
try {
|
||||||
|
int waitSeconds = i * 10;
|
||||||
|
log.info("等待{}秒后重试...", waitSeconds);
|
||||||
|
TimeUnit.SECONDS.sleep(waitSeconds);
|
||||||
|
} catch (InterruptedException ie) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
log.error("凭证获取重试被中断");
|
||||||
|
record.setFailReason("获取凭证实例被中断");
|
||||||
|
this.updateById(record);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.error("获取凭证失败,已重试3次");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String fetchNewCredential() {
|
||||||
|
CredentialReqDTO reqDTO = new CredentialReqDTO();
|
||||||
|
reqDTO.setSystemName(SYSTEM_NAME);
|
||||||
|
reqDTO.setSecretKey(SECRET_KEY);
|
||||||
|
|
||||||
|
HttpURLConnection connection = null;
|
||||||
|
try {
|
||||||
|
URL url = new URL(CREDENTIAL_URL);
|
||||||
|
connection = (HttpURLConnection) url.openConnection();
|
||||||
|
connection.setRequestMethod("POST");
|
||||||
|
connection.setRequestProperty("Content-Type", "application/json");
|
||||||
|
connection.setConnectTimeout(CONNECT_TIMEOUT);
|
||||||
|
connection.setReadTimeout(READ_TIMEOUT);
|
||||||
|
connection.setDoOutput(true);
|
||||||
|
|
||||||
|
OutputStream outputStream = connection.getOutputStream();
|
||||||
|
outputStream.write(GSON.toJson(reqDTO).getBytes(StandardCharsets.UTF_8));
|
||||||
|
outputStream.flush();
|
||||||
|
outputStream.close();
|
||||||
|
|
||||||
|
int responseCode = connection.getResponseCode();
|
||||||
|
if (responseCode != 200) {
|
||||||
|
throw new BusinessException("获取凭证失败,HTTP响应码: " + responseCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
BufferedReader reader = new BufferedReader(
|
||||||
|
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
|
||||||
|
StringBuilder response = new StringBuilder();
|
||||||
|
String inputLine;
|
||||||
|
while ((inputLine = reader.readLine()) != null) {
|
||||||
|
response.append(inputLine);
|
||||||
|
}
|
||||||
|
reader.close();
|
||||||
|
|
||||||
|
JsonObject jsonResponse = GSON.fromJson(response.toString(), JsonObject.class);
|
||||||
|
int code = jsonResponse.get("code").getAsInt();
|
||||||
|
|
||||||
|
if (code != 0) {
|
||||||
|
String msg = jsonResponse.has("msg") ? jsonResponse.get("msg").getAsString() : "未知错误";
|
||||||
|
throw new BusinessException("获取凭证失败,错误码: " + code + ",错误信息: " + msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonObject data = jsonResponse.getAsJsonObject("data");
|
||||||
|
String token = data.get("credentialToken").getAsString();
|
||||||
|
long expiresTimestamp = data.get("expiresTime").getAsLong();
|
||||||
|
|
||||||
|
LocalDateTime expiresTime = LocalDateTime.ofInstant(
|
||||||
|
Instant.ofEpochMilli(expiresTimestamp),
|
||||||
|
ZoneId.systemDefault()
|
||||||
|
);
|
||||||
|
|
||||||
|
long expireSeconds = calculateExpireSeconds(expiresTime);
|
||||||
|
redisUtil.saveByKeyWithExpire(CREDENTIAL_CACHE_KEY, token, expireSeconds);
|
||||||
|
|
||||||
|
log.info("获取新凭证成功,过期时间: {},缓存有效期: {}秒", expiresTime, expireSeconds);
|
||||||
|
return token;
|
||||||
|
|
||||||
|
} catch (SocketTimeoutException e) {
|
||||||
|
throw new BusinessException("获取凭证超时(30秒),请检查网络连接");
|
||||||
|
} catch (ConnectException e) {
|
||||||
|
throw new BusinessException("无法连接到凭证服务,请检查服务是否启动和网络是否正常");
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new BusinessException("获取凭证IO异常: " + e.getMessage());
|
||||||
|
} finally {
|
||||||
|
if (connection != null) {
|
||||||
|
connection.disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private long calculateExpireSeconds(LocalDateTime expiresTime) {
|
||||||
|
long expireSeconds = java.time.Duration.between(
|
||||||
|
LocalDateTime.now(),
|
||||||
|
expiresTime
|
||||||
|
).getSeconds();
|
||||||
|
|
||||||
|
expireSeconds = expireSeconds - 60;
|
||||||
|
|
||||||
|
return Math.max(expireSeconds, 60);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean attemptSendWithRetry(MessageRecordReqVO vo, String token, SmsSendRecord record) {
|
||||||
|
for (int attempt = 0; attempt <= MAX_RETRY; attempt++) {
|
||||||
|
if (attempt > 0) {
|
||||||
|
int delayMinutes = RETRY_DELAYS[attempt - 1];
|
||||||
|
log.info("第{}次重试,等待{}分钟后发送...", attempt, delayMinutes);
|
||||||
|
|
||||||
|
try {
|
||||||
|
TimeUnit.MINUTES.sleep(delayMinutes);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
log.error("重试等待被中断", e);
|
||||||
|
record.setFailReason("重试等待被中断");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
record.setRetryCount(attempt);
|
||||||
|
}
|
||||||
|
|
||||||
|
SendResult result = executeSendSms(vo, token, record);
|
||||||
|
|
||||||
|
if (result.isSuccess()) {
|
||||||
|
record.setFailReason(null);
|
||||||
|
log.info("第{}次尝试发送成功,消息ID: {}", attempt, result.getMessageId());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
record.setFailReason(result.getFailReason());
|
||||||
|
|
||||||
|
if (result.isUnauthorized()) {
|
||||||
|
log.warn("凭证失效(401),重新获取凭证后重试...");
|
||||||
|
String newToken = getOrRefreshCredentialWithRetry(record);
|
||||||
|
if (newToken == null) {
|
||||||
|
record.setFailReason("凭证刷新失败,无法重新获取凭证");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
token = newToken;
|
||||||
|
record.setCredentialToken(newToken);
|
||||||
|
this.updateById(record);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!result.isTimeOut()) {
|
||||||
|
log.warn("发送失败且非超时,不再重试,原因: {},响应时间: {}ms",
|
||||||
|
result.getFailReason(), record.getResponseTime());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
log.warn("第{}次发送超时,将重试,响应时间: {}ms",
|
||||||
|
attempt, record.getResponseTime());
|
||||||
|
}
|
||||||
|
|
||||||
|
record.setFailReason("超过最大重试次数,发送超时");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private SendResult executeSendSms(MessageRecordReqVO vo, String token, SmsSendRecord record) {
|
||||||
|
HttpURLConnection connection = null;
|
||||||
|
long startTime = System.currentTimeMillis();
|
||||||
|
|
||||||
|
try {
|
||||||
|
URL url = new URL(SMS_SEND_URL);
|
||||||
|
connection = (HttpURLConnection) url.openConnection();
|
||||||
|
connection.setRequestMethod("POST");
|
||||||
|
connection.setRequestProperty("Content-Type", "application/json");
|
||||||
|
connection.setRequestProperty("X-Credential-Token", token);
|
||||||
|
connection.setConnectTimeout(CONNECT_TIMEOUT);
|
||||||
|
connection.setReadTimeout(READ_TIMEOUT);
|
||||||
|
connection.setDoOutput(true);
|
||||||
|
|
||||||
|
OutputStream outputStream = connection.getOutputStream();
|
||||||
|
outputStream.write(GSON.toJson(Collections.singletonList(vo)).getBytes(StandardCharsets.UTF_8));
|
||||||
|
outputStream.flush();
|
||||||
|
outputStream.close();
|
||||||
|
|
||||||
|
int responseCode = connection.getResponseCode();
|
||||||
|
long responseTime = System.currentTimeMillis() - startTime;
|
||||||
|
record.setResponseTime(responseTime);
|
||||||
|
|
||||||
|
BufferedReader reader = new BufferedReader(
|
||||||
|
new InputStreamReader(
|
||||||
|
responseCode == 200 ? connection.getInputStream() : connection.getErrorStream(),
|
||||||
|
StandardCharsets.UTF_8
|
||||||
|
)
|
||||||
|
);
|
||||||
|
StringBuilder response = new StringBuilder();
|
||||||
|
String inputLine;
|
||||||
|
while ((inputLine = reader.readLine()) != null) {
|
||||||
|
response.append(inputLine);
|
||||||
|
}
|
||||||
|
reader.close();
|
||||||
|
|
||||||
|
if (responseCode != 200) {
|
||||||
|
String failReason = "HTTP响应码异常: " + responseCode;
|
||||||
|
if (response.length() > 0) {
|
||||||
|
failReason += ",响应: " + response.toString();
|
||||||
|
}
|
||||||
|
record.setFailReason(failReason);
|
||||||
|
return new SendResult(false, null, failReason, false, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonObject jsonResponse = GSON.fromJson(response.toString(), JsonObject.class);
|
||||||
|
int code = jsonResponse.get("code").getAsInt();
|
||||||
|
|
||||||
|
if (code == 401) {
|
||||||
|
String failReason = "凭证失效(HTTP 401)";
|
||||||
|
record.setFailReason(failReason);
|
||||||
|
redisUtil.delete(CREDENTIAL_CACHE_KEY);
|
||||||
|
return new SendResult(false, null, failReason, false, true);
|
||||||
|
} else {
|
||||||
|
if (code != 0) {
|
||||||
|
String msg = jsonResponse.has("msg") ? jsonResponse.get("msg").getAsString() : "未知错误";
|
||||||
|
String failReason = "业务错误码: " + code + ",错误信息: " + msg;
|
||||||
|
record.setFailReason(failReason);
|
||||||
|
return new SendResult(false, null, failReason, false, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonObject firstResult = jsonResponse.getAsJsonArray("data").get(0).getAsJsonObject();
|
||||||
|
boolean result = firstResult.get("result").getAsBoolean();
|
||||||
|
String messageId = firstResult.has("messageId") ? firstResult.get("messageId").getAsString() : null;
|
||||||
|
String detail = firstResult.has("detail") ? firstResult.get("detail").getAsString() : null;
|
||||||
|
|
||||||
|
if (result) {
|
||||||
|
log.info("短信发送成功,接收者: {},消息ID: {},详情: {},耗时: {}ms",
|
||||||
|
vo.getReceiver(), messageId, detail, responseTime);
|
||||||
|
return new SendResult(true, messageId, null, false, false);
|
||||||
|
} else {
|
||||||
|
String failReason = "发送失败: " + detail;
|
||||||
|
record.setFailReason(failReason);
|
||||||
|
return new SendResult(false, messageId, failReason, false, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (SocketTimeoutException e) {
|
||||||
|
long responseTime = System.currentTimeMillis() - startTime;
|
||||||
|
record.setResponseTime(responseTime);
|
||||||
|
String failReason = "请求超时(30秒)";
|
||||||
|
record.setFailReason(failReason);
|
||||||
|
log.warn("短信发送超时,接收者: {},耗时: {}ms", vo.getReceiver(), responseTime);
|
||||||
|
return new SendResult(false, null, failReason, true, false);
|
||||||
|
} catch (ConnectException e) {
|
||||||
|
long responseTime = System.currentTimeMillis() - startTime;
|
||||||
|
record.setResponseTime(responseTime);
|
||||||
|
String failReason = "无法连接到短信服务";
|
||||||
|
record.setFailReason(failReason);
|
||||||
|
log.error("短信服务连接失败,接收者: {}", vo.getReceiver(), e);
|
||||||
|
return new SendResult(false, null, failReason, false, false);
|
||||||
|
} catch (IOException e) {
|
||||||
|
long responseTime = System.currentTimeMillis() - startTime;
|
||||||
|
record.setResponseTime(responseTime);
|
||||||
|
String failReason = "IO异常: " + e.getMessage();
|
||||||
|
record.setFailReason(failReason);
|
||||||
|
log.error("短信发送IO异常,接收者: {},耗时: {}ms", vo.getReceiver(), responseTime, e);
|
||||||
|
return new SendResult(false, null, failReason, false, false);
|
||||||
|
} finally {
|
||||||
|
if (connection != null) {
|
||||||
|
connection.disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.njcn.user.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.extension.service.IService;
|
||||||
|
import com.njcn.user.pojo.po.app.SmsSendRecord;
|
||||||
|
import com.njcn.user.pojo.vo.app.MessageRecordReqVO;
|
||||||
|
|
||||||
|
public interface ISmsSendService extends IService<SmsSendRecord> {
|
||||||
|
|
||||||
|
void sendSmsWithRetry(String receiver, String content, String messageType);
|
||||||
|
|
||||||
|
void sendSmsWithRetry(MessageRecordReqVO messageRecordReqVO);
|
||||||
|
}
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
package com.njcn.user.service.impl;
|
package com.njcn.user.service.impl;
|
||||||
|
|
||||||
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
|
|
||||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||||
import com.njcn.common.pojo.constant.PatternRegex;
|
import com.njcn.common.pojo.constant.PatternRegex;
|
||||||
@@ -19,7 +18,6 @@ import com.njcn.user.pojo.po.Role;
|
|||||||
import com.njcn.user.pojo.po.User;
|
import com.njcn.user.pojo.po.User;
|
||||||
import com.njcn.user.pojo.po.UserSet;
|
import com.njcn.user.pojo.po.UserSet;
|
||||||
import com.njcn.user.pojo.po.app.AppInfoSet;
|
import com.njcn.user.pojo.po.app.AppInfoSet;
|
||||||
import com.njcn.user.pojo.po.app.AppSendMsg;
|
|
||||||
import com.njcn.user.service.*;
|
import com.njcn.user.service.*;
|
||||||
import com.njcn.user.util.SmsApiUtil;
|
import com.njcn.user.util.SmsApiUtil;
|
||||||
import com.njcn.user.util.SmsUtil;
|
import com.njcn.user.util.SmsUtil;
|
||||||
@@ -46,22 +44,14 @@ import java.util.*;
|
|||||||
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, User> implements IAppUserService {
|
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, User> implements IAppUserService {
|
||||||
|
|
||||||
private static final Logger logger = LoggerFactory.getLogger(AppUserServiceImpl.class);
|
private static final Logger logger = LoggerFactory.getLogger(AppUserServiceImpl.class);
|
||||||
|
|
||||||
private final RedisUtil redisUtil;
|
private final RedisUtil redisUtil;
|
||||||
|
|
||||||
private final IAppSendMsgService appSendMsgService;
|
private final IAppSendMsgService appSendMsgService;
|
||||||
|
|
||||||
private final IUserSetService userSetService;
|
private final IUserSetService userSetService;
|
||||||
|
|
||||||
private final IRoleService roleService;
|
private final IRoleService roleService;
|
||||||
|
|
||||||
private final IUserRoleService userRoleService;
|
private final IUserRoleService userRoleService;
|
||||||
|
|
||||||
private final IAppInfoSetService appInfoSetService;
|
private final IAppInfoSetService appInfoSetService;
|
||||||
|
|
||||||
private final SmsUtil smsUtil;
|
|
||||||
|
|
||||||
private final SmsApiUtil smsApiUtil;
|
private final SmsApiUtil smsApiUtil;
|
||||||
|
private final ISmsSendService smsSendService;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@Transactional(rollbackFor = Exception.class)
|
@Transactional(rollbackFor = Exception.class)
|
||||||
@@ -69,8 +59,6 @@ public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, User> impleme
|
|||||||
if (!PubUtils.match(PatternRegex.PHONE_REGEX, phone)){
|
if (!PubUtils.match(PatternRegex.PHONE_REGEX, phone)){
|
||||||
throw new BusinessException(UserResponseEnum.REGISTER_PHONE_WRONG);
|
throw new BusinessException(UserResponseEnum.REGISTER_PHONE_WRONG);
|
||||||
}
|
}
|
||||||
SendSmsResponse sendSmsResponse = null;
|
|
||||||
ResponseEntity<String> response = null;
|
|
||||||
String msgTemplate = SmsUtil.getMessageTemplate(type);
|
String msgTemplate = SmsUtil.getMessageTemplate(type);
|
||||||
String vcode = null;
|
String vcode = null;
|
||||||
try {
|
try {
|
||||||
@@ -97,70 +85,17 @@ public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, User> impleme
|
|||||||
//开始执行短信发送
|
//开始执行短信发送
|
||||||
String mobiles = phone;
|
String mobiles = phone;
|
||||||
String content = SmsUtil.getLianTongMessageTemplate(type, vcode);
|
String content = SmsUtil.getLianTongMessageTemplate(type, vcode);
|
||||||
response = smsApiUtil.sendBatchSms(mobiles, content);
|
smsSendService.sendSmsWithRetry(mobiles,content,"verify_code");
|
||||||
String key = RedisKeyEnum.SMS_LOGIN_KEY.getKey() + phone;
|
String key = RedisKeyEnum.SMS_LOGIN_KEY.getKey() + phone;
|
||||||
//成功发送短信验证码后,保存进redis
|
//成功发送短信验证码后,保存进redis
|
||||||
redisUtil.saveByKeyWithExpire(key, vcode, 300L);
|
redisUtil.saveByKeyWithExpire(key, vcode, 300L);
|
||||||
//短信入库
|
|
||||||
addZdSendMessage(phone,vcode,msgTemplate,response);
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
logger.error("发送短信异常,异常为:"+e.getMessage());
|
logger.error("发送短信异常,异常为:"+e.getMessage());
|
||||||
//短信入库
|
|
||||||
addZdSendMessage(phone,vcode,msgTemplate,response);
|
|
||||||
throw new BusinessException(e.getMessage());
|
throw new BusinessException(e.getMessage());
|
||||||
}
|
}
|
||||||
return "OK";
|
return "OK";
|
||||||
}
|
}
|
||||||
|
|
||||||
// @Override
|
|
||||||
// @Transactional(rollbackFor = Exception.class)
|
|
||||||
// public String setMessage(String phone, String devCode, String type) {
|
|
||||||
// if (!PubUtils.match(PatternRegex.PHONE_REGEX, phone)){
|
|
||||||
// throw new BusinessException(UserResponseEnum.REGISTER_PHONE_WRONG);
|
|
||||||
// }
|
|
||||||
// SendSmsResponse sendSmsResponse = null;
|
|
||||||
// String msgTemplate = SmsUtil.getMessageTemplate(type);
|
|
||||||
// String vcode = null;
|
|
||||||
// try {
|
|
||||||
// //type为4,账号替换为新手机号
|
|
||||||
// if (!msgTemplate.equalsIgnoreCase(MessageEnum.REGISTER.getTemplateCode())) {
|
|
||||||
// User user = this.lambdaQuery().eq(User::getPhone,phone).one();
|
|
||||||
// if ("4".equalsIgnoreCase(type)) {
|
|
||||||
// //注册,无需判断手机号与设备的匹配
|
|
||||||
// if (user != null) {
|
|
||||||
// throw new BusinessException(UserResponseEnum.REGISTER_PHONE_FAIL);
|
|
||||||
// }
|
|
||||||
// } else {
|
|
||||||
// if (null == user) {
|
|
||||||
// throw new BusinessException(UserResponseEnum.LOGIN_PHONE_NOT_REGISTER);
|
|
||||||
// } else {
|
|
||||||
// user.setDevCode(devCode);
|
|
||||||
// logger.info("更新手机id:" + devCode);
|
|
||||||
// this.updateById(user);
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// vcode = getMessageCode();
|
|
||||||
// //获取短信发送结果
|
|
||||||
// sendSmsResponse = smsUtil.sendSms(phone,msgTemplate,"code",vcode);
|
|
||||||
// String key = RedisKeyEnum.SMS_LOGIN_KEY.getKey() + phone;
|
|
||||||
// if (sendSmsResponse.getCode() != null && "OK".equals(sendSmsResponse.getCode())) {
|
|
||||||
// //成功发送短信验证码后,保存进redis,验证码失效为5分钟
|
|
||||||
// redisUtil.saveByKeyWithExpire(key, vcode,300L);
|
|
||||||
// } else {
|
|
||||||
// throw new BusinessException(UserResponseEnum.SEND_CODE_FAIL);
|
|
||||||
// }
|
|
||||||
// //短信入库
|
|
||||||
// addSendMessage(phone,vcode,msgTemplate,sendSmsResponse);
|
|
||||||
// } catch (Exception e) {
|
|
||||||
// logger.error("发送短信异常,异常为:"+e.getMessage());
|
|
||||||
// //短信入库
|
|
||||||
// addSendMessage(phone,vcode,msgTemplate,sendSmsResponse);
|
|
||||||
// throw new BusinessException(e.getMessage());
|
|
||||||
// }
|
|
||||||
// return sendSmsResponse.getCode();
|
|
||||||
// }
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@Transactional(rollbackFor = {Exception.class})
|
@Transactional(rollbackFor = {Exception.class})
|
||||||
public void register(String phone, String code, String devCode) {
|
public void register(String phone, String code, String devCode) {
|
||||||
@@ -172,7 +107,6 @@ public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, User> impleme
|
|||||||
}
|
}
|
||||||
judgeCode(phone, code);
|
judgeCode(phone, code);
|
||||||
String password = null;
|
String password = null;
|
||||||
ResponseEntity<String> response = null;
|
|
||||||
//先根据手机号查询是否已被注册
|
//先根据手机号查询是否已被注册
|
||||||
User user = this.lambdaQuery().eq(User::getPhone,phone).ne(User::getState,0).one();
|
User user = this.lambdaQuery().eq(User::getPhone,phone).ne(User::getState,0).one();
|
||||||
if (!Objects.isNull(user)){
|
if (!Objects.isNull(user)){
|
||||||
@@ -198,73 +132,13 @@ public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, User> impleme
|
|||||||
//发送用户初始密码
|
//发送用户初始密码
|
||||||
password = redisUtil.getStringByKey(newUser.getId());
|
password = redisUtil.getStringByKey(newUser.getId());
|
||||||
String content = SmsUtil.getLianTongMessageTemplate("3", password);
|
String content = SmsUtil.getLianTongMessageTemplate("3", password);
|
||||||
response = smsApiUtil.sendBatchSms(phone, content);
|
smsSendService.sendSmsWithRetry(phone,content,"verify_code");
|
||||||
if (response != null && response.getStatusCodeValue() == 200) {
|
redisUtil.delete(newUser.getId());
|
||||||
//成功发送短信验证码后,删除用户密码信息
|
|
||||||
redisUtil.delete(newUser.getId());
|
|
||||||
} else {
|
|
||||||
throw new BusinessException(UserResponseEnum.SEND_CODE_FAIL);
|
|
||||||
}
|
|
||||||
addZdSendMessage(phone,password,MessageEnum.getTemplateByCode(3),response);
|
|
||||||
//删除验证码
|
//删除验证码
|
||||||
deleteCode(phone);
|
deleteCode(phone);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// @Override
|
|
||||||
// @Transactional(rollbackFor = {Exception.class})
|
|
||||||
// public void register(String phone, String code, String devCode) {
|
|
||||||
// if (!PubUtils.match(PatternRegex.PHONE_REGEX, phone)){
|
|
||||||
// throw new BusinessException(UserResponseEnum.REGISTER_PHONE_WRONG);
|
|
||||||
// }
|
|
||||||
// if (StringUtils.isBlank(devCode)) {
|
|
||||||
// throw new BusinessException(UserResponseEnum.DEV_CODE_WRONG);
|
|
||||||
// }
|
|
||||||
// judgeCode(phone, code);
|
|
||||||
// String password = null;
|
|
||||||
// SendSmsResponse sendSmsResponse = null;
|
|
||||||
// //先根据手机号查询是否已被注册
|
|
||||||
// User user = this.lambdaQuery().eq(User::getPhone,phone).ne(User::getState,0).one();
|
|
||||||
// if (!Objects.isNull(user)){
|
|
||||||
// throw new BusinessException(UserResponseEnum.REGISTER_PHONE_REPEAT);
|
|
||||||
// } else {
|
|
||||||
// //新增用户配置表
|
|
||||||
// UserSet userSet = userSetService.addAppUserSet();
|
|
||||||
// //新增用户表
|
|
||||||
// User newUser = cloneUserBoToUser(phone,devCode,userSet);
|
|
||||||
// //新增用户角色关系表
|
|
||||||
// Role role = roleService.getRoleByCode(AppRoleEnum.TOURIST.getCode());
|
|
||||||
// userRoleService.addUserRole(newUser.getId(), Collections.singletonList(role.getId()));
|
|
||||||
// //消息默认配置
|
|
||||||
// AppInfoSet appInfoSet = new AppInfoSet();
|
|
||||||
// appInfoSet.setUserId(newUser.getId());
|
|
||||||
// appInfoSet.setHarmonicInfo(1);
|
|
||||||
// appInfoSet.setEventInfo(1);
|
|
||||||
// appInfoSet.setRunInfo(1);
|
|
||||||
// appInfoSet.setAlarmInfo(1);
|
|
||||||
// appInfoSet.setFunctionBug(0);
|
|
||||||
// appInfoSet.setExFactoryBug(0);
|
|
||||||
// appInfoSetService.save(appInfoSet);
|
|
||||||
// //发送用户初始密码
|
|
||||||
// try {
|
|
||||||
// password = redisUtil.getStringByKey(newUser.getId());
|
|
||||||
// sendSmsResponse = smsUtil.sendSms(phone,MessageEnum.getTemplateByCode(3),"pwd",password);
|
|
||||||
// if (sendSmsResponse.getCode() != null && "OK".equals(sendSmsResponse.getCode())) {
|
|
||||||
// //成功发送短信验证码后,删除用户密码信息
|
|
||||||
// redisUtil.delete(newUser.getId());
|
|
||||||
// } else {
|
|
||||||
// throw new BusinessException(UserResponseEnum.SEND_CODE_FAIL);
|
|
||||||
// }
|
|
||||||
// addSendMessage(phone,password,MessageEnum.getTemplateByCode(3),sendSmsResponse);
|
|
||||||
// } catch (ClientException e) {
|
|
||||||
// logger.error("发送短信异常,异常为:"+e.getMessage());
|
|
||||||
// addSendMessage(phone,password,MessageEnum.getTemplateByCode(3),sendSmsResponse);
|
|
||||||
// }
|
|
||||||
// //删除验证码
|
|
||||||
// deleteCode(phone);
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void modifyPsd(String userId, String phone, String code, String password, String devCode) {
|
public void modifyPsd(String userId, String phone, String code, String password, String devCode) {
|
||||||
if (!PubUtils.match(PatternRegex.PHONE_REGEX, phone)){
|
if (!PubUtils.match(PatternRegex.PHONE_REGEX, phone)){
|
||||||
@@ -426,41 +300,4 @@ public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, User> impleme
|
|||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 验证码入库
|
|
||||||
*/
|
|
||||||
public void addSendMessage(String phone, String vcode, String template, SendSmsResponse sendSmsResponse) {
|
|
||||||
AppSendMsg appSendMsg = new AppSendMsg();
|
|
||||||
appSendMsg.setPhone(phone);
|
|
||||||
appSendMsg.setMessage(vcode);
|
|
||||||
appSendMsg.setSendTime(LocalDateTime.now());
|
|
||||||
if (Objects.isNull(sendSmsResponse)){
|
|
||||||
appSendMsg.setSendStatus("无状态");
|
|
||||||
appSendMsg.setRemark(null);
|
|
||||||
} else {
|
|
||||||
appSendMsg.setSendStatus(sendSmsResponse.getCode() == null ? "无状态" : sendSmsResponse.getCode());
|
|
||||||
appSendMsg.setRemark(sendSmsResponse.getMessage());
|
|
||||||
}
|
|
||||||
appSendMsg.setTemplate(template);
|
|
||||||
appSendMsgService.save(appSendMsg);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 中国电信验证码入库
|
|
||||||
*/
|
|
||||||
public void addZdSendMessage(String phone, String vcode, String template, ResponseEntity<String> response) {
|
|
||||||
AppSendMsg appSendMsg = new AppSendMsg();
|
|
||||||
appSendMsg.setPhone(phone);
|
|
||||||
appSendMsg.setMessage(vcode);
|
|
||||||
appSendMsg.setSendTime(LocalDateTime.now());
|
|
||||||
if (Objects.isNull(response)){
|
|
||||||
appSendMsg.setSendStatus("无状态");
|
|
||||||
appSendMsg.setRemark(null);
|
|
||||||
} else {
|
|
||||||
appSendMsg.setSendStatus(String.valueOf(response.getStatusCodeValue()));
|
|
||||||
}
|
|
||||||
appSendMsg.setTemplate(template);
|
|
||||||
appSendMsgService.save(appSendMsg);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -480,11 +480,21 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IU
|
|||||||
@Override
|
@Override
|
||||||
public List<User> getMarketList() {
|
public List<User> getMarketList() {
|
||||||
Role roleByCode = roleService.getRoleByCode(AppRoleEnum.MARKET_USER.getCode());
|
Role roleByCode = roleService.getRoleByCode(AppRoleEnum.MARKET_USER.getCode());
|
||||||
List<UserRole> userRoles = userRoleMapper.selectUserRole(Stream.of(roleByCode.getId()).collect(Collectors.toList()));
|
List<UserRole> userRoles = userRoleMapper.selectUserRole(
|
||||||
List<String> collect = userRoles.stream().map(UserRole::getUserId).collect(Collectors.toList());
|
Collections.singletonList(roleByCode.getId())
|
||||||
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
|
);
|
||||||
queryWrapper.ne(User::getState, UserState.DELETE).in(User::getId, collect);
|
List<String> userIds = userRoles.stream()
|
||||||
return this.list(queryWrapper);
|
.map(UserRole::getUserId)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
if (userIds.isEmpty()) {
|
||||||
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.lambdaQuery()
|
||||||
|
.ne(User::getState, UserState.DELETE)
|
||||||
|
.in(User::getId, userIds)
|
||||||
|
.list();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
Reference in New Issue
Block a user