SmsService.java
3.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package cn.com.glsx.notify.modules.service;
import cn.com.glsx.notify.modules.entity.MessageLog;
import cn.com.glsx.notify.modules.entity.MessageTemplate;
import cn.com.glsx.notify.modules.mapper.MessageLogMapper;
import cn.com.glsx.notify.modules.mapper.MessageTemplateMapper;
import cn.com.glsx.notify.modules.utils.RopHttpUtil;
import com.glsx.plat.common.utils.StringUtils;
import com.glsx.plat.sms.properties.SMSProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.Date;
/**
* 短信发送服务
*
* @author payu
*/
@Slf4j
@Service
@RefreshScope
public class SmsService {
@Resource
private SMSProperties properties;
@Autowired
private MessageLogMapper messageLogMapper;
@Autowired
private MessageTemplateMapper messageTemplateMapper;
@Async
public void sendSms(String phone, String template, Object... arg) {
MessageTemplate mt = messageTemplateMapper.findByTemplate(template);
if (mt == null) {
log.warn("短信模板{}不存在", template);
return;
}
if (StringUtils.isNullOrEmpty(mt.getSource())) {
log.warn("短信模板{}发送通道为空", template);
return;
}
String content = MessageFormat.format(mt.getContent(), arg);
//把非英文逗号分隔符替换为英文逗号分隔符,todo 待优化,用正则统一替换非英文逗号分隔符
phone = phone.replaceAll(",", ",").replaceAll(";", ",").replaceAll(";", ",");
sendMessage(phone, mt.getSource(), String.valueOf(mt.getType()), content);
MessageLog log = new MessageLog();
log.setToUser(phone);
log.setContent(content);
log.setTemplate(template);
log.setSendType(mt.getSendType());
log.setCreatedDate(new Date());
messageLogMapper.insert(log);
}
/**
* 发送短信
*
* @param phone 电话号码,批量用逗号隔开
* @param source 发送通道
* @param type 类型
* @param context 发送内容
*/
public void sendMessage(String phone, String source, String type, String context) {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>(5);
try {
params.add("phone", phone);
params.add("source", source);
params.add("messageSource", source);
params.add("type", type);
params.add("context", context);
String sendMessageMethod = "glsx.accounts.send.message";
String post = RopHttpUtil.postE(params, String.class, properties.getUrl() + "?method=" + sendMessageMethod, sendMessageMethod);
log.info("发送短信结果{}", post);
} catch (Exception e) {
log.error("发送短信到{}异常,{}", phone, e.getMessage());
}
}
}