redis 手机验证码实现示例

Nancy ·
更新时间:2024-09-20
· 241 次阅读

本文主要介绍了redis 手机验证码实现示例,分享给大家,具体如下:

/** * @author gh Email:@2495140780qq.com * @Description * @date 2021-11-10-21:12 */ public class PhoneCode { public static void main(String[] args) { //模拟验证码发送 // verifyCode("13796734562"); //效验 getRedisCode("13796734562", "740032"); } //3.验证码的校验 public static void getRedisCode(String phone,String code) { //从redis中获取验证码 Jedis jedis = new Jedis("127.0.0.1",6379); //验证码key String codeKey = "VerifyCode"+phone+":code"; String redisCode = jedis.get(codeKey); //判断 if(redisCode.equals(code)) { System.out.println("成功"); }else { System.out.println("失败"); } jedis.close(); } //2.每个手机每天只能发送三次,验证码放到redis中,设置过期时间60 public static void verifyCode(String phone) {//手机号 //链接redis Jedis jedis = new Jedis("127.0.0.1",6379); //拼接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(countKey); }else if (Integer.parseInt(count) >2) { //发送三次,不能大发送 System.out.println("今天发送次数已经超过三次"); jedis.close(); return; } //发送的验证放到redis中去 String vcode = getCode(); jedis.setex(codeKey,120,vcode); jedis.close(); } //1.生成6位的验证码 public static String getCode() { Random random = new Random(); String code = ""; for (int i = 0; i < 6; i++) { int rand = random.nextInt(10); //10 以内的值 code += rand; } return code; } }

发送验证码 

127.0.0.1:6379> flushdb OK 127.0.0.1:6379> keys * 1) "VerifyCode13796734562:count" 2) "VerifyCode13796734562:code" 127.0.0.1:6379> get VerifyCode13796734562:count # 第一次获取验证码 "1" 127.0.0.1:6379> get VerifyCode13796734562:code # 获取的验证码为 "478121" 127.0.0.1:6379> get VerifyCode13796734562:count "2" 127.0.0.1:6379> get VerifyCode13796734562:code "250610" 校验

到此这篇关于redis 手机验证码实现示例的文章就介绍到这了,更多相关redis 手机验证码内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!



示例 验证码 手机 Redis

需要 登录 后方可回复, 如果你还没有账号请 注册新账号