生活随笔
收集整理的這篇文章主要介紹了
Redis实现手机验证码功能
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
完成一個手機驗證碼功能
要求:
1、輸入手機號,點擊發(fā)送后隨機生成6位數(shù)字碼,2分鐘有效
2、輸入驗證碼,點擊驗證,返回成功或失敗
3、每個手機號每天只能輸入3次
public class PhoneCode {public static void main(String[] args
) {verifyCode("12345678910");}public static String getCode() {Random random
= new Random();String code
= "";for (int i
= 0; i
< 6; i
++) {int rand
= random
.nextInt(10);code
+= rand
;}return code
;}public static void verifyCode(String phone
) {Jedis jedis
= new Jedis("47.107.53.146", 6379);String countKey
= "VerifyCode" + phone
+ ":count";String codeKey
= "VerifyCode" + phone
+ ":code";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ù)已經(jīng)超過三次");jedis
.close();return;}String vscode
= getCode();jedis
.setex(codeKey
, 120, vscode
);jedis
.close();}public static void getRedisCode(String phone
,String code
) {Jedis jedis
= new Jedis("47.107.53.146",6379);String codeKey
= "VerifyCode"+phone
+":code";String redisCode
= jedis
.get(codeKey
);if(redisCode
.equals(code
)) {System.out
.println("成功");}else {System.out
.println("失敗");}jedis
.close();}
}
-
運行后:
-
查看服務器上的 key
-
驗證碼校驗
輸出:成功
-
第二次發(fā)送驗證碼后:
-
第三次后:
-
第四次后就會出現(xiàn)
總結(jié)
以上是生活随笔為你收集整理的Redis实现手机验证码功能的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。