Prechádzať zdrojové kódy

feat(sms): 实现腾讯云短信客户端初始化和复用- 添加 @PostConstruct 注解,在应用启动时初始化 SmsClient- 创建全局 smsClient 实例,避免每次发送短信时重复创建
- 增加初始化失败的日志记录和异常抛出机制
- 修复手机号格式验证逻辑中的错误处理
- 移除重复的客户端创建代码,提升性能和可维护性

hxd 5 dní pred
rodič
commit
9ed9da1856

+ 14 - 3
portal-service-domain/src/main/java/com/hfln/portal/domain/customer/util/MsgClient.java

@@ -13,6 +13,7 @@ import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Component;
 import org.springframework.web.client.RestTemplate;
 
+import javax.annotation.PostConstruct;
 import javax.validation.constraints.NotBlank;
 import java.io.UnsupportedEncodingException;
 import java.net.URLEncoder;
@@ -26,6 +27,8 @@ public class MsgClient {
     @Autowired
     private RestTemplate restTemplate;
 
+    private SmsClient smsClient;
+
     @NotBlank
     @Value("${lnxx.sms.tencent.secretId}")
     private String secretId;
@@ -58,6 +61,16 @@ public class MsgClient {
     @Value("${lnxx.sms.tencent.signName}")
     private String signName;
 
+    @PostConstruct
+    private void init() {
+        try {
+            this.smsClient = new SmsClient(new Credential(secretId, secretKey), region, new ClientProfile());
+        } catch (Exception e) {
+            log.error("初始化腾讯云短信客户端失败", e);
+            throw new BizException("初始化腾讯云短信客户端失败: " + e.getMessage());
+        }
+    }
+
     public String sendMsg(String mobile, String content, String signName) {
         if (isValidMobile(mobile)) {
             return "手机号格式不正确";
@@ -101,15 +114,13 @@ public class MsgClient {
             throw new BizException("手机号码格式有误");
         }
         try {
-            SmsClient client = new SmsClient(new Credential(secretId, secretKey), region, new ClientProfile());
             SendSmsRequest req = new SendSmsRequest();
             req.setPhoneNumberSet(new String[]{mobile});
-//			req.setSignName("雷能守护小程序");
             req.setSignName(signName);
             req.setTemplateId(templateId);
             req.setTemplateParamSet(templateParams);
             req.setSmsSdkAppId(sdkAppId);
-            SendSmsResponse resp = client.SendSms(req);
+            SendSmsResponse resp = smsClient.SendSms(req);
             return AbstractModel.toJsonString(resp);
         } catch (Exception e) {
             log.error("发送腾讯云短信失败", e);