7、模拟验证码

截图.png

public class PhoneCode {

public static void main(String[] args) {

//模拟验证码发送

verifyCode("12345678901");

//getRedisCode("12345678901","012170");

}

//3 校验

public static void getRedisCode(String phone,String code){

//从redis中获取验证码

Jedis jedis = new Jedis("175.178.27.250",6379);

String codeKey = "VeriCode"+phone+":code";

String redisCode = jedis.get(codeKey);

//判断

if (redisCode.equals(code)){

System.out.println("成功");

}else {

System.out.println("失败");

}

jedis.close();

}

//2 每个手机每天只能发送三次,验证码放到redis中,设置过期时间

public static void verifyCode(String phone){

//连接Jedis

Jedis jedis = new Jedis("175.178.27.250",6379);

//拼接key

//手机发送次数key

String countKey = "VeriCode"+phone+":count";

//验证码key

String codeKey = "VeriCode"+phone+":code";

//每个手机每天只能发送三次

String count = jedis.get(countKey);

String vcode = getCode();

if(count==null){

//第一次发送,设置发送次数为1

jedis.setex(countKey,24*60*60,"1");

//将发送的验证码放入redis

jedis.setex(codeKey,120,vcode);

}else if(Integer.parseInt(count) <= 2){

//发送次数+1

jedis.incr(countKey);

//将发送的验证码放入redis

jedis.setex(codeKey,120,vcode);

}else if(Integer.parseInt(count)>2){

//超过三次不能发送

System.out.println("您的操作过于频繁,请稍后再试");

jedis.close();

return;

}

}

//1 生成六位验证码

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;

}

}

posted @   枫叶红时  阅读(36)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
· 面试官:你是如何进行SQL调优的?

阅读目录(Content)

此页目录为空

点击右上角即可分享
微信分享提示