要求:
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(); } } } }