温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用Java redis实现发送手机验证码功能的方法

发布时间:2020-07-27 15:56:26 来源:亿速云 阅读:590 作者:小猪 栏目:编程语言

这篇文章主要讲解了使用Java redis实现发送手机验证码功能的方法,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

要求:

1、输入手机号,点击发送后随机生成6位数字码,2分钟有效

2、输入验证码,点击验证,返回成功或失败

3、每个手机号每天只能输入3次

代码如下

import redis.clients.jedis.Jedis;

import java.util.Random;

public class ValidationTest {
  public static void main(String[] args) {
    //getValidation("15005076571");
    //checkValidation("769897","15005076571");
  }

  static void getValidation(String tel) {
    //主机、端口
    Jedis jedis = new Jedis("myhost", 6379);
    //密码
    jedis.auth("mypassword");
    try {
      //获取电话号码
      String phoneNo = tel;
      //本人用1库进行测试
      jedis.select(1);
      String countKey = phoneNo + ":count";
      String codeKey = phoneNo + ":code";
      //获取指定的电话号码发送的验证码次数
      String cnt = jedis.get(countKey);
      //对次数进行判断
      if (cnt == null) {
        //没有发送过验证码
        jedis.setex(countKey, 60 * 60 * 24, "1");
        //发送验证码,假设生成的验证码
        StringBuffer code = new StringBuffer();
        for (int i = 0; i < 6; i++) {
          code.append(new Random().nextInt(10));
        }
        System.out.println("code:" + code);
        //缓存中添加验证码
        jedis.setex(codeKey, 60 * 2, code.toString());
      } else {
        if (Integer.parseInt(cnt) < 3) {
          //发送验证码,假设生成的验证码
          StringBuffer code = new StringBuffer();
          for (int i = 0; i < 6; i++) {
            code.append(new Random().nextInt(10));
          }
          System.out.println("code:" + code);
          //缓存中添加验证码
          jedis.setex(codeKey, 60 * 2, code.toString());
          //递增手机发送数量
          jedis.incr(countKey);
        } else {
          //返回超出3次,禁止发送
          System.out.println("超出3次,禁止发送");
        }
      }
    } catch (Exception e) {
      //这边其实是需要回滚下redis
      e.printStackTrace();
    } finally {
      //关闭redis
      if (jedis != null) {
        jedis.close();
      }
    }
  }

  static void checkValidation(String code, String tel) {
    Jedis jedis = null;
    try {
      jedis = new Jedis("myhost", 6379);
      //密码
      jedis.auth("mypassword");
      jedis.select(1);
      String codeKey = tel + ":code";
      String validation = jedis.get(codeKey);
      if (validation == null) {
        System.out.println("验证码未发送或者失效");
      } else {
        if (validation.equals(code)) {
          System.out.println("验证成功");
        } else {
          System.out.println("验证失败");
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (jedis != null) {
        jedis.close();
      }
    }
  }
}

看完上述内容,是不是对使用Java redis实现发送手机验证码功能的方法有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI