Redis从入门到精通-手机验证码
一、业务场景,需求
用户在手机端点击获取短信验证码,且用户一个手机号每天只能发三次短信,手机端接收到6位验证码,进行比较。
二、实现
1、6位随机数工具类
2、2个key 一个用来设置 1天时间,校验该手机号发送几次,一个key存验证码
三、代码
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","138079783"); } //做验证码校验 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(); } }
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(); } }
本文作者:KwFruit
本文链接:https://www.cnblogs.com/mangoubiubiu/p/15760819.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
分类:
Redis
, Redis从入门到精通
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
2021-01-03 Jenkins搭建
2021-01-03 Spring Cloud Config ------Nacos