业务场景:
(1)向手机号发送6位数验证码,验证码有效期2min。
(2)每个手机号一天最多发送3次验证码。
(3)新的一天验证码次数重新计算。
简单实现思路:
redis中存入两个key,一个记录验证码为:verify_xxxxx_code(有效期2min),一个记录发送次数为:verify_XXXXX_count(有效期至次日0:00:00)。如果发送一次验证码,将verify_XXXXX_count的值自增1。
demo如下:
import org.apache.commons.lang.StringUtils;
import redis.clients.jedis.Jedis;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
public class TelephoneVerify {
public static void main(String[] args) {
//发送验证码并记录redis
sendCode("15811111111");
//根据用户电话号码和输入的验证码进行验证
//verifyCodeByTelAndCode("15811111111","XXXXXX");
}
//生成6位数的随机数
public static String generateRandom6Num() {
Random random = new Random();
String result = "";
for (int i = 0; i < 6; i++) {
result += random.nextInt(10);
}
return result;
}
//根据电话和code验证
public static void verifyCodeByTelAndCode(String telephone, String code) {
//TODO 正式使用时可以用连接池
Jedis jedis = new Jedis("192.168.1.1", 6379);
jedis.auth("XXXXX");
if (jedis.get("verify_" + telephone + "_code").equals(code)) {
System.out.println("验证通过");
} else {
System.out.println("验证失败");
}
jedis.close();
}
//核心方法
//随机码和发送次数存入redis(第二天0点过期),2min过期
public static void sendCode(String telephone) {
String codeTel = "verify_" + telephone + "_code";
String countTel = "verify_" + telephone + "_count";
//TODO 正式使用时可以用连接池
Jedis jedis = new Jedis("192.168.1.1", 6379);
jedis.auth("XXXXX");
//如果是第一次发送短信或者到了新的一天
if (StringUtils.isEmpty(jedis.get(countTel))) {
String code = generateRandom6Num();
jedis.setex(codeTel, 120, code);
System.out.println("当前验证码+" + code);
jedis.setex(countTel, getDayRemainingTime(), "1");//设置为第二天0点过期
//调用运营商,向对应手机号发送验证码,具体方法略
//TODO 根据自身需要补充
} else if (Integer.parseInt(jedis.get(countTel)) < 3) {
if (StringUtils.isEmpty(jedis.get(codeTel))) {//验证码失效
String code = generateRandom6Num();
jedis.setex(codeTel, 120, code);
//调用运营商,向对应手机号发送验证码,具体方法略
//TODO 根据自身需要补充
System.out.println("当前验证码+" + code);
jedis.incr(countTel);
} else {
System.out.println("验证码已发送至手机,有效期2min,请查看。");
jedis.close();
return;
}
} else {
System.out.println("一个手机号每天最多申请三次验证码。");
jedis.close();
return;
}
jedis.close();
}
/**
* 获取一天中剩余的时间(秒数)
*/
public static Integer getDayRemainingTime() {
Calendar curDate = Calendar.getInstance();
Calendar tommorowDate = new GregorianCalendar(curDate
.get(Calendar.YEAR), curDate.get(Calendar.MONTH), curDate
.get(Calendar.DATE) + 1, 0, 0, 0);
return (int) (tommorowDate.getTimeInMillis() - curDate.getTimeInMillis()) / 1000;
}
}