最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

title: redis-login-limitation 

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

基本思路

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

那么登陸請(qǐng)求的參數(shù)中, 會(huì)有一個(gè)參數(shù)唯一標(biāo)識(shí)一個(gè) user, 比如 郵箱/手機(jī)號(hào)/userName

用這個(gè)參數(shù)作為key存入redis, 對(duì)應(yīng)的value為登陸錯(cuò)誤的次數(shù), string 類型, 并設(shè)置過(guò)期時(shí)間為 1min. 當(dāng)獲取到的 value == "4" , 說(shuō)明當(dāng)前請(qǐng)求為第 5 次登陸異常, 鎖定.

所謂的鎖定, 就是將對(duì)應(yīng)的value設(shè)置為某個(gè)標(biāo)識(shí)符, 比如"lock", 并設(shè)置過(guò)期時(shí)間為 1h

核心代碼

定義一個(gè)注解, 用來(lái)標(biāo)識(shí)需要登陸次數(shù)校驗(yàn)的方法

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

編寫(xiě)切面, 在目標(biāo)方法前后進(jìn)行校驗(yàn), 處理...

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)嘗試超過(guò)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 實(shí)現(xiàn)登陸次數(shù)限制的思路詳解,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!

相關(guān)文章

  • 一文搞懂阿里云服務(wù)器部署Redis并整合Spring?Boot

    一文搞懂阿里云服務(wù)器部署Redis并整合Spring?Boot

    這篇文章主要介紹了一文搞懂阿里云服務(wù)器部署Redis并整合Spring?Boot,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-09-09
  • Redis和Nginx實(shí)現(xiàn)限制接口請(qǐng)求頻率的示例

    Redis和Nginx實(shí)現(xiàn)限制接口請(qǐng)求頻率的示例

    限流就是限制API訪問(wèn)頻率,當(dāng)訪問(wèn)頻率超過(guò)某個(gè)閾值時(shí)進(jìn)行拒絕訪問(wèn)等操作,本文主要介紹了Redis和Nginx實(shí)現(xiàn)限制接口請(qǐng)求頻率的示例,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-02-02
  • redis 過(guò)期策略及內(nèi)存回收機(jī)制解析

    redis 過(guò)期策略及內(nèi)存回收機(jī)制解析

    這篇文章主要介紹了redis 過(guò)期策略及內(nèi)存回收機(jī)制,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • Redis高并發(fā)超賣(mài)問(wèn)題解決方案圖文詳解

    Redis高并發(fā)超賣(mài)問(wèn)題解決方案圖文詳解

    Redis是一種基于內(nèi)存的數(shù)據(jù)存儲(chǔ)系統(tǒng),被廣泛用于解決高并發(fā)問(wèn)題,下面這篇文章主要給大家介紹了關(guān)于Redis高并發(fā)超賣(mài)問(wèn)題解決方案的相關(guān)資料,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-02-02
  • Redis分布式鎖的超時(shí)問(wèn)題及解決

    Redis分布式鎖的超時(shí)問(wèn)題及解決

    這篇文章主要介紹了Redis分布式鎖的超時(shí)問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-05-05
  • 基于Redis無(wú)序集合如何實(shí)現(xiàn)禁止多端登錄功能

    基于Redis無(wú)序集合如何實(shí)現(xiàn)禁止多端登錄功能

    這篇文章主要給你大家介紹了關(guān)于基于Redis無(wú)序集合如何實(shí)現(xiàn)禁止多端登錄功能的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2018-12-12
  • Redis應(yīng)用之簽到的使用

    Redis應(yīng)用之簽到的使用

    在很多時(shí)候,我們遇到用戶簽到的場(chǎng)景,本文主要介紹了Redis應(yīng)用之簽到的使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2024-05-05
  • 一篇文章帶你徹底搞懂Redis?事務(wù)

    一篇文章帶你徹底搞懂Redis?事務(wù)

    這篇文章主要介紹了一篇文章帶你徹底搞懂Redis?事務(wù)的相關(guān)資料,需要的朋友可以參考下
    2022-10-10
  • 高并發(fā)下Redis如何保持?jǐn)?shù)據(jù)一致性(避免讀后寫(xiě))

    高并發(fā)下Redis如何保持?jǐn)?shù)據(jù)一致性(避免讀后寫(xiě))

    本文主要介紹了高并發(fā)下Redis如何保持?jǐn)?shù)據(jù)一致性(避免讀后寫(xiě)),文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • redis加鎖的幾種方式匯總

    redis加鎖的幾種方式匯總

    這篇文章主要介紹了redis加鎖的幾種方式匯總,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-03-03

最新評(píng)論

出国| 名山县| 普安县| 阳城县| 抚顺县| 普安县| 全椒县| 徐州市| 河源市| 富裕县| 竹溪县| 荔波县| 辽阳县| 绩溪县| 龙南县| 达孜县| 神木县| 南岸区| 阿坝县| 井研县| 会同县| 桂阳县| 平利县| 蒙山县| 高阳县| 永平县| 綦江县| 民权县| 鄱阳县| 富顺县| 寿阳县| 绥德县| 上高县| 张家口市| 句容市| 山东省| 永兴县| 丰镇市| 三台县| 岑巩县| 盘锦市|