启动redis
redis-server /opt/redis-5.0.4/redis.conf
redis-cli
发送验证码案例
1.用random生成一个6位数的随机验证码
//生成验证码 public static String getCode(){ Random random = new Random(); String code=""; for (int i = 0; i < 6; i++) { int i1 = random.nextInt(10); code += i1; } return code; }
2.向redis中存储验证码,并限制发送的次数
//发送验证码 public static void verifyCode(String phone){ Jedis jedis = JedisPoolUtil.getJedis(); //验证码的key String codeKey = "verifyCode"+phone+"code"; //记录验证码的次数 key String countKey ="verifyCode"+phone+"count"; String count = jedis.get(countKey); if(count==null){ jedis.setex(countKey,60L,"1"); }else if(Integer.parseInt(count)<=2){ jedis.incr(countKey); }else{ System.out.println("超过发送的次数"); jedis.close(); return; } String code = getCode(); System.out.println("验证码:"+code); jedis.setex(codeKey,60L,code); jedis.close(); }
3.验证用户发送的验证码是否匹配
public static void getRedisCode(String phone,String code){ Jedis jedis = JedisPoolUtil.getJedis(); String codeKey = "verifyCode"+phone+"code"; String vcode =jedis.get(codeKey); if(vcode==null){ System.out.println("验证码过期了"); }else if(vcode.equalsIgnoreCase(code)){ System.out.println("验证成功"); }else { System.out.println("验证失败"); } jedis.close(); }
4.编写main方法进行测试
public static void main(String[] args) { //模拟验证码的发送:phone verifyCode("18635183513"); //验证用户输入的验证码和redis的验证码做比较 getRedisCode("18635183513","722225"); }
要先发送验证码到redis数据库
然后再进行测试
因为我们设置了1分钟的过期时间,等1分钟后就会看到验证码失效
如果验证码没有失效但验证码错误会提示验证不通过