1. 程式人生 > 程式設計 >如何使用Java redis實現傳送手機驗證碼功能

如何使用Java redis實現傳送手機驗證碼功能

要求:

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,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();
      }
    }
  }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。