调用阿里大于接口发送短信,并且放入redis中设置过期时间
程序员文章站
2022-05-29 09:40:32
...
以下代码在写之前,要先去阿里购买发送短信的次数
阿里短信接口API:https://help.aliyun.com/document_detail/101414.html?spm=a2c4g.11186623.6.624.320e1a81IIQgdd
//API参数
final String product = "Dysmsapi";
final String domain = "dysmsapi.aliyuncs.com";
//账号AK(相当于账号密码)
final String accessKeyId = "accessKeyId ";
final String accessKeySecret = "accessKeySecret ";
//初始化ascClient
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("xxxx");
// 签名,签名要保持跟你申请短信模板的保持一致,否则会返回签名无效
request.setSignName("签名");
// 短信模板标识(在阿里界面申请创建模板成功后,看到对应的短信模板标识)
request.setTemplateCode("标识");//类似于这种:SMS_XXXXXXXX
// 随机生成验证码
int mobileCode = (int) ((Math.random() * 9 + 1) * 100000);
final Jedis jedisTemplate = new Jedis();
// 下面这种方法是第二种存储缓存的,可以忽略,这里主要是使用redis
//MemCachedClient memCachedClient = new MemCachedClient();
// 将随机码保存到redis,五分钟有效时间
jedisTemplate.setex( "mobileCode", 5 * 60, String.valueOf( mobileCode ) );
request.setTemplateParam("{'code':" + mobileCode + "}");
//请求失败这里会抛ClientException异常
SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
//请求成功
System.out.println("发送成功");
}