Redis模仿發(fā)送手機驗證碼功能
更新時間:2021年09月27日 15:34:07 作者:Lw中
這篇文章主要介紹了Redis模仿手機驗證碼發(fā)送功能,通過示例代碼給大家講解通過用戶輸入手機號以及驗證碼進行校驗,代碼簡單易懂,需要的朋友可以參考下
流程圖

一:添加jedis依賴包

二:測試連接Redis服務(wù)是否成功
// 創(chuàng)建Jedis對象用于連接Redis服務(wù)(在服務(wù)器上通過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();
}
到此這篇關(guān)于Redis模仿手機驗證碼發(fā)送的文章就介紹到這了,更多相關(guān)Redis發(fā)送手機驗證碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Redis數(shù)據(jù)類型之散列類型hash命令學習
這篇文章主要為大家介紹了Redis數(shù)據(jù)類型之散列類型hash命令學習,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-07-07
redis執(zhí)行l(wèi)ua腳本的實現(xiàn)方法
redis在2.6推出了腳本功能,允許開發(fā)者使用Lua語言編寫腳本傳到redis中執(zhí)行。本文就介紹了redis執(zhí)行l(wèi)ua腳本的實現(xiàn)方法,感興趣的可以了解一下2021-11-11
redis-cli登錄遠程redis服務(wù)并批量導入數(shù)據(jù)
本文主要介紹了redis-cli登錄遠程redis服務(wù)并批量導入數(shù)據(jù),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-10-10
Springboot整合Redis與數(shù)據(jù)持久化
這篇文章主要介紹了Springboot整合Redis與Redis數(shù)據(jù)持久化的操作,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-07-07
Redis全文搜索教程之創(chuàng)建索引并關(guān)聯(lián)源數(shù)據(jù)的教程
RediSearch提供了一種簡單快速的方法對 hash 或者 json 類型數(shù)據(jù)的任何字段建立二級索引,然后就可以對被索引的 hash 或者 json 類型數(shù)據(jù)字段進行搜索和聚合操作,這篇文章主要介紹了Redis全文搜索教程之創(chuàng)建索引并關(guān)聯(lián)源數(shù)據(jù),需要的朋友可以參考下2023-12-12

