package com.wss.springboot;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
@SpringBootTest
public class PhoneCodeTest {
@Autowired
RedisTemplate redisTemplate;
@Test
void codeTest(){
System.out.println("输入手机号");
Scanner scan = new Scanner(System.in);
String phone = scan.next();
getPhoneAndSendCode(phone);
System.out.println("输验证码");
String code = scan.next();
verifyCode(code);
}
//判读验证码输入是否正确
public void verifyCode(String code){
ValueOperations opsForValue = redisTemplate.opsForValue();
String rsCode = opsForValue.get("codeKey");
if (rsCode == null){
System.out.println("验证码已失效");
}
if (code.equals(rsCode)){
System.out.println("验证通过");
}else {
System.out.println("验证码错误");
}
}
//判断手机发送次数,并生成验证码
public void getPhoneAndSendCode(String phone){
ValueOperations opsForValue = redisTemplate.opsForValue();
String countKey = "countKey:"+phone;
//获得手机发送次数 count
String count = opsForValue.get(countKey);
if (count == null){
//count == null ,手机第一次发送,设置key value 和过期时间
opsForValue.set(countKey, "1",24*60*60, TimeUnit.SECONDS);
}else if (Integer.parseInt(count) <= 2){
opsForValue.increment(countKey);
}else{
System.out.println("手机今天已发送三次验证码,无法再次发送");
return;
}
//生成验证码
String code = getCode();
System.out.println("生成的验证码:"+code);
//将验证码存储并设置过期时间
opsForValue.set("codeKey", code, 30, TimeUnit.SECONDS);
}
//获得验证码
public String getCode(){
String code = "";
Random random = new Random();
for (int i = 0; i < 6; i++) {
int ran = random.nextInt(10);
code += ran;
}
return code;
}
}