1)新建几个文件夹

2)编写接口 SendSmsService
public interface SendSmsService {
/**
* 用于发送短信
* @param phoneNumber :手机号
* @param templateCode :模板编号
* @param code :验证码
* @return 是否发送成功
*/
public boolean send(String phoneNumber, String templateCode, Map<String, Object> code);
}
3)编写实现类 SendSmsServiceImpl
public class SendSmsServiceImpl implements SendSmsService {
@Override
public boolean send(String phoneNumber, String templateCode, Map<String, Object> code) {
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "<accessKeyId>", "<accessSecret>");
IAcsClient client = new DefaultAcsClient(profile);
// 构建请求
CommonRequest request = new CommonRequest();
request.setSysMethod(MethodType.POST);
request.setSysDomain("dysmsapi.aliyuncs.com");
request.setSysVersion("2017-05-25");
request.setSysAction("SendSms");
// 上面不需要改
// 自定义参数 :
// 手机号,这里 Value 就填用户的手机号,实际应用须要从表单获取
request.putQueryParameter("PhoneNumbers", phoneNumber);
// 签名,这里的 Value 就是在阿里云上申请的 签名
request.putQueryParameter("SignName", "XXXX");
// 模板,这里的 Value 就是在阿里云上申请的模板的 模版CODE 值
request.putQueryParameter("TemplateCode", templateCode);
// 验证码,真实应用需要自动构建验证码
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(code));
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
// 自带的判断是否成功的方法
return response.getHttpResponse().isSuccess();
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
return false;
}
}
4)编写配置文件,连接 Redis :application.yml
server:
port: 8088
# 配置 Redis
spring:
redis:
host: 192.168.142.120
port: 6379
password: 123456
5)编写调用接口
@RestController
@CrossOrigin // 跨域的支持
public class SmsApiController {
@Autowired
private SendSmsService sendSmsService;
@Autowired
private RedisTemplate redisTemplate;
@GetMapping("send/{phone}")
public String sendSms(@PathVariable("phone") String phoneNumber){
// 调用发送发放(模拟真实业务,整合 Redis)
// 判断当前手机号是否存储在 Redis 中
// 如果没有则发送短信
// 如果有表示上一个验证码还未过期,不用发送
String code = (String) redisTemplate.opsForValue().get(phoneNumber);
if (!StringUtils.isEmpty(code)){
return "[手机号: "+phoneNumber + "],[验证码: " + code +"],还未过期";
}
// 生成验证码
code = UUID.randomUUID().toString().substring(0,6);
HashMap<String, Object> map = new HashMap<>();
map.put("code",code);
sendSmsService.send(phoneNumber,"XXXX",map);
// 如果发送成功,就放入 Redis
if (isSend){
redisTemplate.opsForValue().set(phoneNumber,code,5, TimeUnit.MINUTES);
return "[手机号: "+phoneNumber + "],[验证码: " + code +"],发送成功";
}else {
return "[手机号: "+phoneNumber + "],[验证码: " + code +"],发送失败";
}
}
}
6)使用浏览器访问测试!!