溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Redis如何模仿手機驗證碼發送

發布時間:2021-11-01 17:45:28 來源:億速云 閱讀:199 作者:小新 欄目:開發技術

這篇文章將為大家詳細講解有關Redis如何模仿手機驗證碼發送,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

具體如下:

流程圖

Redis如何模仿手機驗證碼發送

一:添加jedis依賴包

Redis如何模仿手機驗證碼發送

二:測試連接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();

三:編寫生成驗證碼方法

/**
     * 生成驗證碼的方法
     * @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;
    }

四:編寫發送驗證碼方法

/**
     * 用戶點擊生成驗證碼并將其添加到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();
    }

五:編寫校驗驗證碼方法

/**
     * 用戶輸入手機號以及驗證碼進行校驗
     * @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如何模仿手機驗證碼發送”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女