手机验证码(Jedis的使用)
package JedisDemo; import redis.clients.jedis.Jedis; import java.util.Random; // 手机验证码 public class phoneCodeVerify { public static void main(String[] args) { // 模拟验证码的发送 String phoneNumber = "13603915587"; transmitCode(phoneNumber); // 校验 //verifyCode(phoneNumber, "23892"); } // 生成6位手机验证码 public static String getCode() { StringBuilder str = new StringBuilder(); Random random = new Random(); // 以当前系统时间的毫秒数为随机化种子 for (int i = 1; i < 6; i++) { int num = random.nextInt(10); //生成0~9的随机数 str.append(num); } return str.toString(); } // 每个手机每天只能发送三次验证码,验证码放到redis中,并设置过期时间 public static void transmitCode(String phoneNumber) { Jedis jedis = new Jedis("10.115.103.111", 6379); // 验证码和发送次数分别用两个key-value存储 String countKey = "VerifyCode: " + phoneNumber + " :count"; String codeKey = "VerifyCode: " + phoneNumber + " :code"; // 每个手机每天只能发送三次 String count = jedis.get(countKey); if (count == null) { //第一次发送 jedis.setex(countKey, 24 * 60 * 60, "1"); // 为指定的key设置值及其过期时间 } else if (Integer.parseInt(count) <= 2) { // 还没有到三次 jedis.incr(countKey); } else if (Integer.parseInt(count) > 2){ //已经发送三次 System.out.println("发送失败:验证码今天已经发送三次"); jedis.close(); return ; } // 发送的验证码要放到redis中去 String sendCode = getCode(); jedis.setex(codeKey, 120, sendCode); System.out.println("验证法已发送!"); jedis.close(); } // 验证码校验手否正确 public static void verifyCode(String phoneNumber, String code) { // 从Redis中获取验证码 Jedis jedis = new Jedis("10.115.103.111", 6379); String codeKey = "VerifyCode: " + phoneNumber + " :code"; String redisCode = jedis.get(codeKey); //判断 if (redisCode == null) { System.out.println("手机号输入错误"); } else { if (redisCode.equals(code)) { System.out.println("验证成功!"); } else { System.out.println("验证失败!"); } } jedis.close(); } }
作者:Ryanjie
出处:http://www.cnblogs.com/ryanjan/
本文版权归作者和博客园所有,欢迎转载。转载请在留言板处留言给我,且在文章标明原文链接,谢谢!
如果您觉得本篇博文对您有所收获,觉得我还算用心,请点击右下角的 [推荐],谢谢!