1.使用阿里云的短信api,将其进行组件抽取
(1)创建一个spring.factories文件(META-INF/spring.factories)
#声明我要自动装配一个smsTemplate org.springframework.boot.autoconfigure.EnableAutoConfiguration= \com.itcast.tanhua.autoconfig.TanHuaAutoConfiguration
(2)定义配置对象,引入配置
<1>添加配置application.yml文件
sms: signName: 验证码短信 templateCode: SMS_280126445 accessKey: secret:
<2>引用配置文件参数
(注意参数名要相同)
@Data @ConfigurationProperties(prefix = "tanhua.sms") public class SmsProperties { //这些属性名称需要与app-server中的属性名称一致 private String signName; private String templateCode; private String accessKey; private String secret; }
<3>开启注解自动识别配置对象
@EnableConfigurationProperties({SmsProperties.class})
(3)添加模板类对象
public class SmsTemplate { @Autowired private SmsProperties properties; public SmsTemplate(SmsProperties properties) { this.properties = properties; } public void sendSms(String mobile, String code) { try { // 配置阿里云 Config config = new Config(). setAccessKeyId(properties.getAccessKey()). setAccessKeySecret(properties.getSecret()); // 设置访问域名 config.endpoint = "dysmsapi.aliyuncs.com"; Client client = new Client(config); SendSmsRequest request = new SendSmsRequest(). setPhoneNumbers(mobile). setSignName(properties.getSignName()). setTemplateCode(properties.getTemplateCode()). setTemplateParam("{\"code\":\"" + code + "\"}"); SendSmsResponse response = client.sendSms(request); SendSmsResponseBody body = response.getBody(); System.out.println(body.getMessage()); } catch (Exception e) { e.printStackTrace(); } } }
(4)定义一个自动装配类
//开启注解使能够自动识别道smsproperties,在其中可以添加多个 @EnableConfigurationProperties({ SmsProperties.class }) public class TanHuaAutoConfiguration { @Bean public SmsTemplate smsTemplate(SmsProperties properties) { return new SmsTemplate(properties); } }
2.获取短信验证码业务流程以及实现
(1)短信验证码接口
(2)流程分析
(3)获取登录验证码流程
1、搭建SpringBoot运行环境(引导类,配置文件)
2、编写Controller接受请求参数
3、定义业务层方法,根据手机号码发送短信
4、数据响应
<1>编写Controller
@PostMapping("/login") public ResponseEntity String(@RequestBody Map map) { String phone = (String) map.get("phone"); userService.sendMsg(phone); // 正常返回状态码200 return ResponseEntity.ok(null); }
<2>业务层
public void sendMsg(String phone) { // 1.随机生成六位数字 String code = RandomStringUtils.randomNumeric(6); // 2.调用ssmtemplate,发送手机验证码 smsTemplate.sendSms(phone, code); // 3.将验证码存到redis中 存活时间设置为5分钟 redisTemplate.opsForValue().set("CHECK_CODE_" + phone, code, Duration.ofMinutes(5)); }
<3>响应
使用responseEntity来实现
// 正常返回状态码200 return ResponseEntity.ok(null);