Jedis——手机验证码操作
要求
1、输入手机号,点击发送后随机生成6为数字码,2分钟有效
Random、验证码存进Redis并设置过期时间120秒
2、输入验证码,点击验证,返回成功或失败
从Redis中获取验证码比对输入验证码
3、每个手机号每天只能输入3次
incr每次发送加1,大于2之后,提醒不能发送
package com.atguigu.jedis; import redis.clients.jedis.Jedis; import java.util.Random; public class PhoneCode { //生成6位数验证码 public static String getCode(){ String res = ""; Random random = new Random(); for(int i=0; i<6; i++){ int rand = random.nextInt(10); res += rand; } return res; } //2、每个手机每天只能发送三次,验证码放到Redis中,设置过期时间 public static void verifyCode(String phone){ //连接redis Jedis jedis = new Jedis("192.168.189.128", 6379); //手机发送次数key String countKey = "Verifycode" + phone + "count"; //验证码key 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){ //发送次数加1 jedis.incr(countKey); }else{ //发送三次,不能发送 System.out.println("今天发送次数已经超过三次"); jedis.close(); return; } //发送验证码放到redis String code = getCode(); jedis.setex(codeKey, 120, code); jedis.close(); } public static void getRedisCode(String phone, String code){ Jedis jedis = new Jedis("192.168.189.128", 6379); //验证码key String codeKey = "Verifycode" + phone + "code"; //从jedis获取验证码 String redisCode = jedis.get(codeKey); if(redisCode.equals(code)){ System.out.println("success"); }else{ System.out.println("fail"); } jedis.close(); } public static void main(String[] args) { //模拟验证码发送 verifyCode("134567"); getRedisCode("134567", "658404"); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?