這篇文章將為大家詳細講解有關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如何模仿手機驗證碼發送”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。