导入上面jar包
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.5.3</version>
</dependency>
service类:
package com.bing.jedis_test1;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import java.util.Map;
public class SmsBing {
public boolean sendSms(String phoneName, Map<String,Object> code){
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4FzoxT6Zxxxxx", "WyGf440RLZl9jW0Nrexxxxx");
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setSysMethod(MethodType.POST);
request.setSysDomain("dysmsapi.aliyuncs.xxx");
request.setSysVersion("2017-05-25");
request.setSysAction("SendSms");
//模板编号和签名可以做成变量 ------SignName-------TemplateCode
request.putQueryParameter("PhoneNumbers", phoneName);
request.putQueryParameter("SignName", "短信注册功能"); // 去阿里云短信验证
request.putQueryParameter("TemplateCode", "SMS_205xxxxx");
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(code));
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
return true;
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
return false;
}
}
controller层调用:
package com.bing.jedis_test1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
public class SmsAction {
@Autowired
SmsBing smsBing;
@Autowired
RedisTemplate redisTemplate;
@RequestMapping("/sms")
public String Sms(@RequestParam(required = true) String phone){
String code = (String) redisTemplate.opsForValue().get("phone");
if(!StringUtils.isEmpty(code)){
return phone+"此号码存在,验证码为"+code;
}
String substring = UUID.randomUUID().toString().substring(0, 4);
Map<String,Object> map = new HashMap<>();
map.put(code,substring);
boolean isSend = smsBing.sendSms(phone, map);
if(isSend){
redisTemplate.opsForValue().set(phone, code, 30, TimeUnit.SECONDS);
return "号码发送成功,请注意查收,号码在30秒后过期";
}else{
return "发送失败";
}
}
}
调用action执行方法测试。