1、需要在阿里云中开通短信服务
①、创建签名
②、创建模板
2、引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
</dependency>
3、编写controller类
同时将数据存储到redis中进行保存
@Autowired
private MsmService msmService;
@Autowired
private RedisTemplate<String, String> redisTemplate;
@ApiOperation(value = "发送验证码")
@GetMapping("/send/{phone}")
public Result sendMsg(@PathVariable("phone") String phone) {
//1、先从redis获取验证码,如果获取到直接返回
String code = redisTemplate.opsForValue().get(phone);
if (StringUtils.isEmpty(code)) {
//2、获取不到,进行阿里云发送
//生成随机的值,传递给阿里云进行发送
code = RandomUtil.getFourBitRandom();
//传递给阿里云的短信服务
Map<String, Object> map = new HashMap<>();
map.put("code", code);
//调用service发送短信的方法
boolean result = msmService.send(map, phone);
if (result) {
//将验证码存储到redis,设置有效时间
redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
return new Result(true, ResultCode.OK, "发送成功!!");
} else {
return new Result(false, ResultCode.ERROR, "发送失败!!");
}
}
return new Result(true, ResultCode.OK, "发送成功!!");
}
4、编写service层
public boolean send(Map<String, Object> map, String phone) {
if (StringUtils.isEmpty(phone)) return false;
DefaultProfile profile = DefaultProfile.getProfile("default", "LTAI4GHn6zFJGAvporUTGVCX", "lca87Spiqz5JXM8LbnejbZ81e3LMe9");
IAcsClient client = new DefaultAcsClient(profile);
//设置相关固定的参数
CommonRequest request = new CommonRequest();
//request.setProtocol(ProtocolType.HTTPS);
request.setMethod(MethodType.POST);
request.setDomain("dysmsapi.aliyuncs.com");
request.setVersion("2017-05-25");
request.setAction("SendSms");
//设置发送相关的参数
request.putQueryParameter("PhoneNumbers", phone); //手机号
request.putQueryParameter("SignName", "ABC商城"); //申请阿里云 签名名称
request.putQueryParameter("TemplateCode", "SMS_198917059"); //申请阿里云 模板code
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map)); //验证码数据,转换json数据传递
try {
//最终发送
CommonResponse response = client.getCommonResponse(request);
boolean success = response.getHttpResponse().isSuccess();
return success;
}catch(Exception e) {
e.printStackTrace();
return false;
}
}
实现效果如下: