欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

redis 實現(xiàn)登陸次數(shù)限制的思路詳解

 更新時間:2019年08月06日 08:43:33   作者:xiaoyureed  
這篇文章主要介紹了redis 實現(xiàn)登陸次數(shù)限制的思路詳解,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下

title: redis-login-limitation 

利用 redis 實現(xiàn)登陸次數(shù)限制, 注解 + aop, 核心代碼很簡單.

基本思路

比如希望達到的要求是這樣: 在 1min 內(nèi)登陸異常次數(shù)達到5次, 鎖定該用戶 1h

那么登陸請求的參數(shù)中, 會有一個參數(shù)唯一標識一個 user, 比如 郵箱/手機號/userName

用這個參數(shù)作為key存入redis, 對應的value為登陸錯誤的次數(shù), string 類型, 并設(shè)置過期時間為 1min. 當獲取到的 value == "4" , 說明當前請求為第 5 次登陸異常, 鎖定.

所謂的鎖定, 就是將對應的value設(shè)置為某個標識符, 比如"lock", 并設(shè)置過期時間為 1h

核心代碼

定義一個注解, 用來標識需要登陸次數(shù)校驗的方法

package io.github.xiaoyureed.redispractice.anno;
import java.lang.annotation.*;
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RedisLimit {
  /**
   * 標識參數(shù)名, 必須是請求參數(shù)中的一個
   */
  String identifier();
  /**
   * 在多長時間內(nèi)監(jiān)控, 如希望在 60s 內(nèi)嘗試
   * 次數(shù)限制為5次, 那么 watch=60; unit: s
   */
  long watch();
  /**
   * 鎖定時長, unit: s
   */
  long lock();
  /**
   * 錯誤的嘗試次數(shù)
   */
  int times();
}

編寫切面, 在目標方法前后進行校驗, 處理...

package io.github.xiaoyureed.redispractice.aop;
@Component
@Aspect
// Ensure that current advice is outer compared with ControllerAOP
// so we can handling login limitation Exception in this aop advice.
//@Order(9)
@Slf4j
public class RedisLimitAOP {
  @Autowired
  private StringRedisTemplate stringRedisTemplate;
  @Around("@annotation(io.github.xiaoyureed.redispractice.anno.RedisLimit)")
  public Object handleLimit(ProceedingJoinPoint joinPoint) {
    MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    final Method   method     = methodSignature.getMethod();
    final RedisLimit redisLimitAnno = method.getAnnotation(RedisLimit.class);// 貌似可以直接在方法參數(shù)中注入 todo
    final String identifier = redisLimitAnno.identifier();
    final long  watch   = redisLimitAnno.watch();
    final int  times   = redisLimitAnno.times();
    final long  lock    = redisLimitAnno.lock();
    // final ServletRequestAttributes att       = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    // final HttpServletRequest    request     = att.getRequest();
    // final String          identifierValue = request.getParameter(identifier);
    String identifierValue = null;
    try {
      final Object arg      = joinPoint.getArgs()[0];
      final Field declaredField = arg.getClass().getDeclaredField(identifier);
      declaredField.setAccessible(true);
      identifierValue = (String) declaredField.get(arg);
    } catch (NoSuchFieldException e) {
      log.error(">>> invalid identifier [{}], cannot find this field in request params", identifier);
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    }
    if (StringUtils.isBlank(identifierValue)) {
      log.error(">>> the value of RedisLimit.identifier cannot be blank, invalid identifier: {}", identifier);
    }
    // check User locked
    final ValueOperations<String, String> ssOps = stringRedisTemplate.opsForValue();
    final String             flag = ssOps.get(identifierValue);
    if (flag != null && "lock".contentEquals(flag)) {
      final BaseResp result = new BaseResp();
      result.setErrMsg("user locked");
      result.setCode("1");
      return new ResponseEntity<>(result, HttpStatus.OK);
    }
    ResponseEntity result;
    try {
      result = (ResponseEntity) joinPoint.proceed();
    } catch (Throwable e) {
      result = handleLoginException(e, identifierValue, watch, times, lock);
    }
    return result;
  }
  private ResponseEntity handleLoginException(Throwable e, String identifierValue, long watch, int times, long lock) {
    final BaseResp result = new BaseResp();
    result.setCode("1");
    if (e instanceof LoginException) {
      log.info(">>> handle login exception...");
      final ValueOperations<String, String> ssOps = stringRedisTemplate.opsForValue();
      Boolean                exist = stringRedisTemplate.hasKey(identifierValue);
      // key doesn't exist, so it is the first login failure
      if (exist == null || !exist) {
        ssOps.set(identifierValue, "1", watch, TimeUnit.SECONDS);
        result.setErrMsg(e.getMessage());
        return new ResponseEntity<>(result, HttpStatus.OK);
      }
      String count = ssOps.get(identifierValue);
      // has been reached the limitation
      if (Integer.parseInt(count) + 1 == times) {
        log.info(">>> [{}] has been reached the limitation and will be locked for {}s", identifierValue, lock);
        ssOps.set(identifierValue, "lock", lock, TimeUnit.SECONDS);
        result.setErrMsg("user locked");
        return new ResponseEntity<>(result, HttpStatus.OK);
      }
      ssOps.increment(identifierValue);
      result.setErrMsg(e.getMessage() + "; you have try " + ssOps.get(identifierValue) + "times.");
    }
    log.error(">>> RedisLimitAOP cannot handle {}", e.getClass().getName());
    return new ResponseEntity<>(result, HttpStatus.OK);
  }
}

這樣使用:

package io.github.xiaoyureed.redispractice.web;
@RestController
public class SessionResources {
  @Autowired
  private SessionService sessionService;
  /**
   * 1 min 之內(nèi)嘗試超過5次, 鎖定 user 1h
   */
  @RedisLimit(identifier = "name", watch = 30, times = 5, lock = 10)
  @RequestMapping(value = "/session", method = RequestMethod.POST)
  public ResponseEntity<LoginResp> login(@Validated @RequestBody LoginReq req) {
    return new ResponseEntity<>(sessionService.login(req), HttpStatus.OK);
  }
}

references

https://github.com/xiaoyureed/redis-login-limitation

總結(jié)

以上所述是小編給大家介紹的redis 實現(xiàn)登陸次數(shù)限制的思路詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!

相關(guān)文章

  • redis的string類型及bitmap介紹

    redis的string類型及bitmap介紹

    這篇文章主要介紹了redis的string類型及bitmap介紹,redis有很多的客戶端連接進來,站在redis所在機器的角度來說,就是有很多socket的連接
    2022-07-07
  • RedisDesktopManager無法遠程連接Redis的完美解決方法

    RedisDesktopManager無法遠程連接Redis的完美解決方法

    下載RedisDesktopManager客戶端,輸入服務器IP地址,端口(缺省值:6379);點擊Test Connection按鈕測試連接,連接失敗,怎么回事呢?下面小編給大家?guī)砹薘edisDesktopManager無法遠程連接Redis的完美解決方法,一起看看吧
    2018-03-03
  • Redis主從實現(xiàn)讀寫分離

    Redis主從實現(xiàn)讀寫分離

    這篇文章主要為大家詳細介紹了Redis主從實現(xiàn)讀寫分離的相關(guān)資料 ,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-10-10
  • Redis分布式限流組件設(shè)計與使用實例

    Redis分布式限流組件設(shè)計與使用實例

    本文主要講解基于 自定義注解+Aop+反射+Redis+Lua表達式 實現(xiàn)的限流設(shè)計方案。實現(xiàn)的限流設(shè)計與實際使用。具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-08-08
  • SpringBoot整合Redis入門之緩存數(shù)據(jù)的方法

    SpringBoot整合Redis入門之緩存數(shù)據(jù)的方法

    Redis是一個開源的使用ANSI C語言編寫、支持網(wǎng)絡(luò)、可基于內(nèi)存亦可持久化的日志型、Key-Value數(shù)據(jù)庫,并提供多種語言的API,下面通過本文給大家介紹下SpringBoot整合Redis入門之緩存數(shù)據(jù)的相關(guān)知識,感興趣的朋友一起看看吧
    2021-11-11
  • redis刪除key下所有value步驟詳解

    redis刪除key下所有value步驟詳解

    在使用Redis時,經(jīng)常需要刪除某個key下的所有value,本文就來詳細的介紹一下redis刪除key下所有value步驟,具有一定的參考價值,感興趣的可以了解一下
    2024-01-01
  • Linux中設(shè)置Redis開機啟動的方法

    Linux中設(shè)置Redis開機啟動的方法

    這篇文章主要給大家介紹了關(guān)于Linux中設(shè)置Redis開機啟動的方法,主要包括在CentOS7.0系統(tǒng)和Debian 8.0系統(tǒng)下實現(xiàn)方法,文中介紹的非常詳細,需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-04-04
  • 如何基于Session實現(xiàn)短信登錄功能

    如何基于Session實現(xiàn)短信登錄功能

    對比起Cookie,Session是存儲在服務器端的會話,相對安全,并且不像Cookie那樣有存儲長度限制,下面這篇文章主要給大家介紹了關(guān)于如何基于Session實現(xiàn)短信登錄功能的相關(guān)資料,需要的朋友可以參考下
    2022-10-10
  • 詳解redis是如何實現(xiàn)隊列消息的ack

    詳解redis是如何實現(xiàn)隊列消息的ack

    這篇文章主要介紹了關(guān)于redis是如何實現(xiàn)隊列消息的ack的相關(guān)資料,文中介紹的非常詳細,需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-04-04
  • Redis Cluster集群數(shù)據(jù)分片機制原理

    Redis Cluster集群數(shù)據(jù)分片機制原理

    這篇文章主要介紹了Redis Cluster集群數(shù)據(jù)分片機制原理,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-04-04

最新評論