栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

Redis模仿手机验证码发送

Java 更新时间:发布时间: 百科书网 趣学号
流程图

一:添加jedis依赖包

二:测试连接Redis服务是否成功
// 创建Jedis对象用于连接Redis服务(在服务器上通过redis-server需要指定配置文件:redis-server /etc/redis.conf)
Jedis jedis = new Jedis("192.168.119.128", 6379);
String value = jedis.ping();
System.out.println(value);
jedis.close();
三:编写生成验证码方法
    public static String getCode() {
        Random random = new Random();
        String code = "";
        for (int i = 0; i < 6; i++) {
            int num = random.nextInt(10);
            code += num;
        }
        System.out.println(code);
        return code;
    }
四:编写发送验证码方法
    public static void sendVerifyCode(String phone) {
        Jedis jedis = new Jedis("192.168.119.128", 6379);

        // 手机号码的key,获取手机号码发送验证码次数
        String countKey = "VerifyCode" + phone + ":count";
        // 验证码的key,获取手机号码的验证码
        String codeKey = "VerifyCode" + phone + ":code";

        // 获取countKey判断当前手机号码是否可以发送验证码
        String count = jedis.get(countKey);
        if (count == null) {
            jedis.setex(countKey, 24 * 60 * 60, "1");
        } else if (Integer.parseInt(count) <= 2) {
            jedis.incr(countKey);
        } else if (Integer.parseInt(count) > 2) {
            System.out.println("当前手机号发送验证码次数超过上限,请明天再发送验证码");
            jedis.close();
        }

        String code = getCode();
        jedis.setex(codeKey, 120, code);

        jedis.close();
    }
五:编写校验验证码方法
    public static void CustomerVerifyCode(String phone, String code) {
        Jedis jedis = new Jedis("192.168.119.128", 6379);

        String codeKey = "VerifyCode" + phone + ":code";
        String phoneVerifyCode = jedis.get(codeKey);

        if (phoneVerifyCode.equals(code)) {
            System.out.println("校验成功!");
        } else {
            System.out.println("校验失败!");
        }

        jedis.close();
    }

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/270390.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号