Redis模仿發(fā)送手機驗證碼功能
更新時間:2021年09月27日 15:34:07 作者:Lw中
這篇文章主要介紹了Redis模仿手機驗證碼發(fā)送功能,通過示例代碼給大家講解通過用戶輸入手機號以及驗證碼進行校驗,代碼簡單易懂,需要的朋友可以參考下
流程圖
一:添加jedis依賴包
二:測試連接Redis服務是否成功
// 創(chuàng)建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; }
四:編寫發(fā)送驗證碼方法
/** * 用戶點擊生成驗證碼并將其添加到redis中 * @param phone */ public static void sendVerifyCode(String phone) { Jedis jedis = new Jedis("192.168.119.128", 6379); // 手機號碼的key,獲取手機號碼發(fā)送驗證碼次數(shù) String countKey = "VerifyCode" + phone + ":count"; // 驗證碼的key,獲取手機號碼的驗證碼 String codeKey = "VerifyCode" + phone + ":code"; // 獲取countKey判斷當前手機號碼是否可以發(fā)送驗證碼 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("當前手機號發(fā)送驗證碼次數(shù)超過上限,請明天再發(fā)送驗證碼"); 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模仿手機驗證碼發(fā)送的文章就介紹到這了,更多相關Redis發(fā)送手機驗證碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
redis持久化AOF和RDB的區(qū)別及解決各個場景問題示例
這篇文章主要為大家介紹了redis持久化AOF和RDB的區(qū)別及解決各個場景問題示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08