短信平台根据客户的需求也不同,所以短信平台的扩展要做好。系统默认提供阿里云的短信支持。
1.首先提供短信接口
import java.util.Map;
import com.aliyuncs.exceptions.ClientException;
import net.sf.json.JSONObject;
public interface ISMSSupportGenerator {
public boolean sendSMS(Map<String, String> resourceInfo, JSONObject params, String phone) throws ClientException;
}
2.扩展短信平台,发送短信的类直接继承该类,然后在properties配置文件中配置类的路径即可。类的加载通过
private synchronized ISMSSupportGenerator getSmsSendInstance() {
if (smsSupportGenerator == null) {
try {
smsSupportGenerator = (ISMSSupportGenerator) Class.forName(SMS_CLASS).newInstance();
} catch (Exception e) {
LOG.error("Get smsSender instance error:{}", e);
}
}
return smsSupportGenerator;
}
方法实现。类名地址通过@Value注入到类中
3.短信平台初始化配置信息
平台初始化信息即接口中的resourceInfo信息,在项目启动时直接加载。这些信息可以通过数据库配置,也可以在配置文件中写。由于项目上的种种原因,直接写在了properties中,通过逗号和分号进行分离,初始化数据方法如下:
@PostConstruct
public void initialize() {
String[] params = resources.split(";");
for (String data : params) {
resourceInfo.put(data.split(":")[0], data.split(":")[1]);
}
String[] param = noticeResource.split(";");
for (String data : param) {
resourceMsg.put(data.split(":")[0], data.split(":")[1]);
}
LOG.info("Send message initialize finish.");
}
以一个map形式存储,因为需要用到两套模板,所以初始化了两个resourceInfo的map。
4.阿里短信集成
阿里短信集成可以去看阿里的api文档,如果使用验证码的话,要自己生成,作为参数传送到api中。
public class AliSMSSupportGeneratorImpl implements ISMSSupportGenerator {
@Override
public boolean sendSMS(Map<String, String> resourceInfo,JSONObject params,String phone) throws ClientException {
final String product = "Dysmsapi";
final String domain = "dysmsapi.aliyuncs.com";
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
final String accessKeyId = resourceInfo.get("aliAccessKeyId");
final String accessKeySecret = resourceInfo.get("aliAccessKeySecret");
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
IAcsClient acsClient = new DefaultAcsClient(profile);
// 组装请求对象
SendSmsRequest request = new SendSmsRequest();
// 使用post提交
request.setMethod(MethodType.POST);
request.setPhoneNumbers(phone);
request.setSignName(resourceInfo.get("aliSignName"));
request.setTemplateCode(resourceInfo.get("aliTemplateCode"));
request.setTemplateParam(params.toString());
SendSmsResponse sendSmsResponse = null;
sendSmsResponse = acsClient.getAcsResponse(request);
if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
return true;
}
return false;
}
}
这样就OK了。
简单的阿里短信实现