1. 程式人生 > 資料庫 >基於Redis實現每日登入失敗次數限制

基於Redis實現每日登入失敗次數限制

1. 思路

下面是我以前寫的程式碼,沒考慮高併發場景。如果是高併發場景下,要考慮到redis的set方法覆蓋值問題,可以使用incr來替代get,set保證資料安全

通過redis記錄登入失敗的次數,以使用者的username為key

每次收到登入的請求時,都去redis查詢登入次數是否已經大於等於我們設定的限制次數,是的話直接返回

2. 程式碼

前臺登入和後臺查詢資料庫的程式碼省略

2.1 controller

我這裡使用的Jboot,獲取redisTemplate的方式是Jboot.me().getRedis(),spring的話用jedisTemplate就行.

// 如果使用者輸入賬號密碼有效登入超過限制次數,24小時禁止登入
 // 設定一天限制失敗次數,預設為10次
 final int limit = 3;
 JbootRedis jr = Jboot.me().getRedis();
 //Constants.LOGIN_COUNT = "LOGIN_COUNT"
 //account是頁面傳過來的username
 String key = Constants.LOGIN_COUNT + "_" + account;
 Integer count = jr.get(key);
 if(count == null){
   count = 0;
 }else {
   if (count >= limit) {
     //直接返回
     ajaxJson.setMsg("您今天登入失敗的次數已經超過限制,請明天再試。");
     ajaxJson.setSuccess(false);
     logger.error("賬號為【"+account+"】的使用者單日登入次數超過上限");
     render(callback,gson.toJson(ajaxJson));
     return;
   }
 }
//... 去資料庫根據username查詢user物件
 if (user != null) {
   // 往redis中增加登入失敗的次數
   Integer newCount = IncrFailLoginCount(key,count);
   logger.error("賬號為【"+account+"】的使用者登入失敗,"+ajaxJson.getMsg());
   ajaxJson.setMsg(ajaxJson.getMsg() + ",剩下登入次數為:"+(limit-newCount));
   render(callback,gson.toJson(ajaxJson));
   return;
 }else{
   // 登入成功,清除redis失敗記錄
   jr.del(key);
 }

2.2 IncrFailLoginCount方法

/**
 * 一天中登入失敗的次數統計
 * @param key redis中儲存的鍵
 * @param count 已經登入失敗的次數
 * @return count 登入失敗次數
 */
private Integer IncrFailLoginCount(String key,Integer count) {
  JbootRedis jr = Jboot.me().getRedis();
  count++;
  //設定過期時間為今晚23點59分59秒
  long timeInMillis = DateUtils.getMillsecBeforeMoment(23,59,999);
  if (timeInMillis < 100){
    // 避免在最後一秒的時候登入導致過期時間過小甚至為負數
    timeInMillis = 1000*60;
  }
  // 設定過期時間
  jr.set(key,count);
  //這裡注意順序,先set再pexpire
  jr.pexpire(key,timeInMillis);
  return count;
}

這裡用到了時間的一個工具類,具體程式碼如下:

/**
* 獲取當前時間到指定時刻前的毫秒數
* @param hour 指定時刻的小時
* @param min 指定時刻的分鐘
* @param sec 指定時刻的秒
* @param mill 指定時刻的毫秒
* @return
*/
public static long getMillsecBeforeMoment(int hour,int min,int sec,int mill){
  return getMillisecBetweenDate(new Date(),getMoment(hour,min,sec,mill));
}
/**
* 獲取兩個日期之間的毫秒數
 * @param before
 * @param after
 * @return
 */
public static long getMillisecBetweenDate(Date before,Date after){
 long beforeTime = before.getTime();
 long afterTime = after.getTime();
 return afterTime - beforeTime;
}
/**
* 獲取當天的某一時刻Date
 * @param hour 24小時
 * @param min 分鐘
 * @param sec 秒
 * @param mill 毫秒
 * @return
 */
public static Date getMoment(int hour,int mill){
 Calendar calendar = Calendar.getInstance();
 calendar.setTime(new Date());
 calendar.set(Calendar.HOUR_OF_DAY,hour);
 calendar.set(Calendar.MINUTE,min);
 calendar.set(Calendar.SECOND,sec);
 calendar.set(Calendar.MILLISECOND,mill);
 return calendar.getTime();
}

3. 總結

這裡有個地方要注意,就是redis 設定過期時間後,重新set會清除過期效果,重新變成永久狀態,所以需要每次都pexpire()
redis中還有一個方法:incr(),每次呼叫這個方法,都會讓一個鍵的值+1,如果沒有這個鍵,會初始為0再+1. 適合做計數器,也能再這個案例中使用,但是我這裡只是希望登入失敗的時候才計數+1,登入之前直接判斷count,所以使用了傳統的get(),set(). 有興趣的同學可以去詳細瞭解.