前几步全部看我上文章
https://blog.csdn.net/weixin_50235904/article/details/122240255?spm=1001.2014.3001.5501
编写一个Controller
关于手机验证码
/**
* @Date 2021/12/31
* @Author Acer
*/
@RestController
@RequestMapping("/phonecode")
public class PhoneController {
@Autowired
RedisTemplate redisTemplate;
/**
* 生成一个验证码
* 根据一个手机号或得一个六位数的随机数
* 存入redis缓存,20秒
*/
@RequestMapping("/haveCode")
public Object haveCode(String phone) {
if(redisTemplate.opsForValue().get(phone)!=null){
return "已经发送验证码,20秒之后再试!!";
}
int[] number = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
StringBuilder stringBuilder = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 6; i++) {
int is = random.nextInt(10);//10秒换一个数
stringBuilder.append(number[is]);//存到stringBuilder中
}
redisTemplate.opsForValue().set(phone, stringBuilder, 20, TimeUnit.SECONDS);//存入redis中20秒
return "验证码为:" + stringBuilder;
}
/**
* 验证验证码
* 传入手机号和验证码
*/
@RequestMapping("yz")
public Object yz(String phone, String code) {
if (redisTemplate.hasKey(phone) == false) {
return "手机号没有验证码验证码过期";
}
if (code.equals(redisTemplate.opsForValue().get(phone))) {
return "验证码正确";
}
return "验证码错误";
}
}
通过访问接口
http://localhost:8081/phonecode/haveCode?phone=“设置手机号”
在20秒之内访问接口
http://localhost:8081/phonecode/yz?phone=“设置手机号”&code=“获取的验证码”