要求:
1、输入手机号,点击发送后随机生成6位数字码,2分钟有效
2、输入验证码,点击验证,返回成功或失败
3、每个手机号每天只能输入3次
代码如下
import redis.clients.jedis.jedis; import java.util.random; public class validationtest { public static void main(string[] args) { //getvalidation("15005076571"); //checkvalidation("769897","15005076571"); } static void getvalidation(string tel) { //、端口 jedis jedis = new jedis("myhost", 6379); //密码 jedis.auth("mypassword"); try { //获取电话号码 string phoneno = tel; //本人用1库进行测试 jedis.select(1); string countkey = phoneno ":count"; string codekey = phoneno ":code"; //获取指定的电话号码发送的验证码次数 string cnt = jedis.get(countkey); //对次数进行判断 if (cnt == null) { //没有发送过验证码 jedis.setex(countkey, 60 * 60 * 24, "1"); //发送验证码,假设生成的验证码 stringbuffer code = new stringbuffer(); for (int i = 0; i < 6; i ) { code.append(new random().nextint(10)); } system.out.println("code:" code); //缓存中添加验证码 jedis.setex(codekey, 60 * 2, code.tostring()); } else { if (integer.parseint(cnt) < 3) { //发送验证码,假设生成的验证码 stringbuffer code = new stringbuffer(); for (int i = 0; i < 6; i ) { code.append(new random().nextint(10)); } system.out.println("code:" code); //缓存中添加验证码 jedis.setex(codekey, 60 * 2, code.tostring()); //递增手机发送数量 jedis.incr(countkey); } else { //返回超出3次,禁止发送 system.out.println("超出3次,禁止发送"); } } } catch (exception e) { //这边其实是需要回滚下redis e.printstacktrace(); } finally { //关闭redis if (jedis != null) { jedis.close(); } } } static void checkvalidation(string code, string tel) { jedis jedis = null; try { jedis = new jedis("myhost", 6379); //密码 jedis.auth("mypassword"); jedis.select(1); string codekey = tel ":code"; string validation = jedis.get(codekey); if (validation == null) { system.out.println("验证码未发送或者失效"); } else { if (validation.equals(code)) { system.out.println("验证成功"); } else { system.out.println("验证失败"); } } } catch (exception e) { e.printstacktrace(); } finally { if (jedis != null) { jedis.close(); } } } }