本文共 3195 字,大约阅读时间需要 10 分钟。
阿里云提供一套短信发送的服务可通过 Java 进行对接
com.aliyun aliyun-java-sdk-core 3.2.2 com.aliyun aliyun-java-sdk-dysmsapi 1.0.0
@Servicepublic class MessageServiceImpl extends AbstractBaseService { ...}
Constants.ALI_ACCESS_KEY_ID
和 Constants.ALI_ACCESS_SECRET
是密钥,成对生成和使用// 用于从阿里云获取数据的权限客户端private static IAcsClient iAcsClient;static { // 超时时间 System.setProperty("sun.net.client.defaultConnectTimeout", "10000"); System.setProperty("sun.net.client.defaultReadTimeout", "10000"); // 初始化配置 String regionId = "cn-hangzhou"; DefaultProfile profile = DefaultProfile.getProfile(regionId, Constants.ALI_ACCESS_KEY_ID, Constants.ALI_ACCESS_SECRET); try { String productId = "Dysmsapi"; String domain = "dysmsapi.aliyuncs.com"; DefaultProfile.addEndpoint(regionId, regionId, productId, domain); } catch (ClientException e) { throw new TSharkException("初始化短信接口配置失败!", e); } // 初始化权限客户端 iAcsClient = new DefaultAcsClient(profile);}
Constants.ALI_MESSAGE_SIGN_NAME
是从阿里云获取的短信签名@Autowiredprivate RedisHelper redisHelper;public Boolean sendMessage(String mobile, String template) { // 有效性验证 if (checkMobile(mobile)) { throw new TSharkException("验证码已发送,请稍后再试!"); } SendSmsRequest request = new SendSmsRequest(); SendSmsResponse response = null; // 生成随机数 String random = String.valueOf(new Random().nextInt(999999)); request.setMethod(MethodType.POST); request.setPhoneNumbers(mobile); request.setSignName(Constants.ALI_MESSAGE_SIGN_NAME); request.setTemplateCode(template); request.setTemplateParam("{\"name\":\"" + mobile + "\", \"code\":\"" + random + "\"}"); try { response = iAcsClient.getAcsResponse(request); } catch (ClientException e) { throw new TSharkException("接收短信回执失败!", e); } boolean result = response.getCode() != null && response.getCode().equals("OK"); if (result) { // 保存随机数 saveRandom(mobile, random); } return result;}
private Boolean checkMobile(String mobile) { String randomKey = "random:" + mobile; return redisHelper.get(randomKey) != null;}
private void saveRandom(String mobile, String random) { String randomKey = "random:" + mobile; if (checkMobile(mobile)) { return; } redisHelper.set(randomKey, random); // 5分钟失效 redisHelper.expire(randomKey, 5, TimeUnit.MINUTES);}