亚洲中字慕日产2020,大陆极品少妇内射AAAAAA,无码av大香线蕉伊人久久,久久精品国产亚洲av麻豆网站

資訊專欄INFORMATION COLUMN

redis 實現(xiàn)登陸次數(shù)限制

loonggg / 2940人閱讀

摘要:利用實現(xiàn)登陸次數(shù)限制注解核心代碼很簡單基本思路比如希望達到的要求是這樣在內(nèi)登陸異常次數(shù)達到次鎖定該用戶那么登陸請求的參數(shù)中會有一個參數(shù)唯一標識一個比如郵箱手機號用這個參數(shù)作為存入對應的為登陸錯誤的次數(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 類型, 并設置過期時間為 1min. 當獲取到的 value == "4" , 說明當前請求為第 5 次登陸異常, 鎖定.

所謂的鎖定, 就是將對應的value設置為某個標識符, 比如"lock", 并設置過期時間為 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 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 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 login(@Validated @RequestBody LoginReq req) {
        return new ResponseEntity<>(sessionService.login(req), HttpStatus.OK);
    }
}
references

https://github.com/xiaoyureed...

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://www.ezyhdfw.cn/yun/75864.html

相關文章

  • 大話后端開發(fā)的奇淫技巧大集合

    摘要:,大家好,很榮幸有這個機會可以通過寫博文的方式,把這些年在后端開發(fā)過程中總結(jié)沉淀下來的經(jīng)驗和設計思路分享出來模塊化設計根據(jù)業(yè)務場景,將業(yè)務抽離成獨立模塊,對外通過接口提供服務,減少系統(tǒng)復雜度和耦合度,實現(xiàn)可復用,易維護,易拓展項目中實踐例子 Hi,大家好,很榮幸有這個機會可以通過寫博文的方式,把這些年在后端開發(fā)過程中總結(jié)沉淀下來的經(jīng)驗和設計思路分享出來 模塊化設計 根據(jù)業(yè)務場景,將業(yè)務...

    CloudwiseAPM 評論0 收藏0
  • Redis實戰(zhàn)之限制操作頻率

    摘要:場景場景留言功能限制,秒內(nèi)只能評論次,超出次數(shù)不讓能再評論,并提示過于頻繁場景點贊功能限制,秒內(nèi)只能點贊次,超出次數(shù)后不能再點贊,并禁止操作個小時,提示過于頻繁,被禁止操作小時場景上傳記錄功能,限制一天只能上傳次,超出次數(shù)不讓能再上傳,并提 場景 場景1 留言功能限制,30秒 內(nèi)只能評論 10次,超出次數(shù)不讓能再評論,并提示:過于頻繁 場景2 點贊功能限制,10秒 內(nèi)只能點贊 10次,...

    張率功 評論0 收藏0
  • shiro項目介紹

    摘要:項目介紹在之前的整合項目之后,更加完善功能,之前的代碼不予展示與介紹,想了解的請參考整合項目項目代碼獲取功能新增用戶注冊登錄錯誤次數(shù)限制使用作緩存注解配置引入數(shù)據(jù)校驗使用統(tǒng)一異常處理配置項目結(jié)構(gòu)代碼控制層,以下展示注冊和登錄功能會跳到我們自 shiro項目介紹 在之前的shiro整合項目之后,更加完善shiro功能,之前的代碼不予展示與介紹,想了解的請參考shiro整合項目項目代碼獲取...

    ruicbAndroid 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<