利用redis保存验证码并设置过期时间
生活随笔
收集整理的這篇文章主要介紹了
利用redis保存验证码并设置过期时间
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
package com.atguigu.jedis;import redis.clients.jedis.Jedis;import java.util.Random;public class PhoneCode {public static void main(String[] args) {//模擬驗證碼發(fā)送verifyCode("13678765435");//模擬驗證碼校驗//getRedisCode("13678765435","4444");}//3 驗證碼校驗public static void getRedisCode(String phone,String code) {//從redis獲取驗證碼Jedis jedis = new Jedis("39.103.193.185",6379);//驗證碼keyString codeKey = "VerifyCode"+phone+":code";String redisCode = jedis.get(codeKey);//判斷if(redisCode.equals(code)) {System.out.println("成功");}else {System.out.println("失敗");}jedis.close();}//2 每個手機每天只能發(fā)送三次,驗證碼放到redis中,設(shè)置過期時間120public static void verifyCode(String phone) {//連接redisJedis jedis = new Jedis("39.103.193.185",6379);//拼接key//手機發(fā)送次數(shù)keyString countKey = "VerifyCode"+phone+":count";//驗證碼keyString codeKey = "VerifyCode"+phone+":code";//每個手機每天只能發(fā)送三次String count = jedis.get(countKey);if(count == null) {//沒有發(fā)送次數(shù),第一次發(fā)送//設(shè)置發(fā)送次數(shù)是1jedis.setex(countKey,24*60*60,"1");} else if(Integer.parseInt(count)<=2) {//發(fā)送次數(shù)+1jedis.incr(countKey);} else if(Integer.parseInt(count)>2) {//發(fā)送三次,不能再發(fā)送System.out.println("今天發(fā)送次數(shù)已經(jīng)超過三次");jedis.close();}//發(fā)送驗證碼放到redis里面String vcode = getCode();jedis.setex(codeKey,120,vcode);jedis.close();}//1 生成6位數(shù)字驗證碼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;}
}
總結(jié)
以上是生活随笔為你收集整理的利用redis保存验证码并设置过期时间的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 查看防火墙状态并关闭防火墙
- 下一篇: 数组与集合相互转换