Redis 验证码是逻辑实现
package com.cph.redis;
import redis.clients.jedis.Jedis;
import java.util.Random;
public class PhoneCode {
//生成6位数字验证码
public static String getCode(){
Random random = new Random();
String code = "";
for(int i = 0; i < 6; i++){
code += random.nextInt(10);
}
return code;
}
//每个手机每天只能发送3次,验证码放到redis中,设置过期时间
public static void verifyCode(String phone){
Jedis jedis = new Jedis("121.196.223.94",6379);
//拼接key
//手机发送次数
String countKey = "VerifyCode" + phone + ":count";
//验证码key
String codeKey = "VerifyCode" + phone + ":code";
String count = jedis.get(countKey);
if(count == null){
//没有发送过,第一次发送,设置发送次数是1
jedis.setex(countKey, 24*60*60,"1");
}else if(Integer.parseInt(count) <= 2){
jedis.incr(countKey);
}else{
//发送三次,不能再发送了
System.out.println("发送三次,不能再发送了");
jedis.close();
}
//将code存入redis
String code1 = getCode();
jedis.setex(codeKey, 120, code1);
jedis.close();
}
public static void getRedisCode(String phone,String code){
Jedis jedis = new Jedis("121.196.223.94",6379);
String codeKey = "VerifyCode" + phone + ":code";
String redisCode = jedis.get(codeKey);
if(redisCode.equals(code)){
System.out.println("成功");
}else{
System.out.println("失败");
}
}
public static void main(String[] args) {
verifyCode("13084577878");
}
}