深浅模式
完成手机验证码功能
业务场景
用户在手机端点击获取短信验证码,且用户一个手机号每天只能发三次短信,手机端接收到6位验证码,进行比较。
实现思路
- 6位随机数工具类
- 2个key 一个用来设置 1天时间,校验该手机号发送几次,一个key存验证码
代码
java
package com.mangoubiubiu;
import com.mangoubiubiu.utils.RandomUtils;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import java.util.Set;
public class JedisTest {
public static void main(String[] args) {
//verifyCode("123123123123");
checkCode("757178","13807369783");
}
//做验证码校验
public static void checkCode(String code,String phone){
Jedis jedis=new Jedis("192.168.117.134",6379);
//验证码key
String codeKey="verifyCode"+phone+":code";
String s = jedis.get(codeKey);
if(code.equals(s)){
System.out.println("验证成功");
}else {
System.out.println("验证失败");
}
}
public static void verifyCode(String phone){
//创建Jedis对象
Jedis jedis=new Jedis("192.168.117.134",6379);
//拼接key
//手机验证码key拼接
String countKey="verifyCode"+phone+":count";
//验证码key
String codeKey="verifyCode"+phone+":code";
//每个手机每天只能发生三次
String count = jedis.get(countKey);
if(count == null){
//没有发送次数,第一次发送
//设置发送次数是1
jedis.setex(countKey,24*60*60,"1");
}else if(Integer.parseInt(count)<=2){
//发送次数+1
jedis.incr(codeKey);
}else if(Integer.parseInt(count)>2){
//发送三次,不能再次进行发送
System.out.println("不能发送,今天的发送次数已经超过三次。");
jedis.close();
}
//发短信到redis里面
String vcode= RandomUtils.getSixCode();
System.out.println(vcode);
jedis.setex(codeKey,120,vcode);
jedis.close();
}
}java
package com.mangoubiubiu.utils;
import java.util.Random;
public class RandomUtils {
/**
* 禁用构造函数
*/
private RandomUtils(){
}
/**
* 生成6位数的随机验证码
* @return
*/
public static String getSixCode(){
Random random=new Random();
StringBuilder stringBuilder=new StringBuilder();
for (int i=0;i<6;i++){
//生成10以内的随机数
int nums = random.nextInt(10);
stringBuilder.append(nums);
}
return stringBuilder.toString();
}
}