服务器之家

服务器之家 > 正文

Redis模仿发送手机验证码功能

时间:2021-11-18 16:57     来源/作者:Lw中

流程图

Redis模仿发送手机验证码功能

一:添加jedis依赖包

Redis模仿发送手机验证码功能

二:测试连接redis服务是否成功

?
1
2
3
4
5
// 创建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();

三:编写生成验证码方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
     * 生成验证码的方法
     * @return code
     */
    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;
    }

四:编写发送验证码方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
     * 用户点击生成验证码并将其添加到redis中
     * @param phone
     */
    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();
    }

五:编写校验验证码方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
     * 用户输入手机号以及验证码进行校验
     * @param phone
     * @param code
     */
    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();
    }

到此这篇关于redis模仿手机验证码发送的文章就介绍到这了,更多相关redis发送手机验证码内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/weixin_43894879/article/details/120485050

标签:

相关文章

热门资讯

yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
2021年耽改剧名单 2021要播出的59部耽改剧列表
2021年耽改剧名单 2021要播出的59部耽改剧列表 2021-03-05
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部