这里可以创建常量类读取配置文件的阿里云密钥等信息(可参考博主的“对象存储”)package com.xsha.msmservice.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xsha.msmservice.service.MsmService;
import com.xsha.msmservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Service
public class MsmServiceImpl implements MsmService {
// 注入redis缓存对象
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Override
public boolean sendMessage(String phone) {
if(StringUtils.isEmpty(phone)) return false;
// 先获取手机号对应的验证码(该验证码没过期)
String code = redisTemplate.opsForValue().get(phone);
if(!StringUtils.isEmpty(code)) {
return true;
}
// 过期则生成随机验证码,并在发送之后向redis中存入手机号对应的验证码
code = RandomUtil.getFourBitRandom();
Map<String, Object> map = new HashMap<>();
map.put("code", code);
// 设置短信配置
DefaultProfile profile = DefaultProfile.getProfile("your region", "your accessId", "your accessSecret");
IAcsClient client = new DefaultAcsClient(profile);
SendSmsRequest request = new SendSmsRequest();
request.setPhoneNumbers(phone);//接收短信的手机号码
request.setSignName("your signature name");//短信签名名称
request.setTemplateCode("your template");//短信模板CODE
request.setTemplateParam(JSONObject.toJSONString(map));//短信模板变量对应的实际值
try {
SendSmsResponse response = client.getAcsResponse(request);
// 发送短信,尽量打印出来是否发送成功
new Gson().toJson(response);
// 将验证码放置在redis缓存中,并设置5分钟有效时间,最后一个参数是单位
redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
} catch (ServerException e) {
e.printStackTrace();
return false;
} catch (ClientException e) {
e.printStackTrace();
return false;
}
return true;
}
}