Redis登录次数限制

概述

有这样一个需求:登录应当校验它的用户名和密码,密码输入错误不能过多,超过5次就应当限制它的登录,给它一个不能登录的提示,用redis来做

思路是
使用redis记录访问登录次数的值,先设定好初始值,每次访问自增,达到某限定值后,进行阻止

方案

@Autowired
    private  RedisTemplate redisTemplate;

    @Autowired
    private IWeiboUserInfoService weiboUserInfoService;

    @PostMapping("login")
    public Result login(@RequestBody WeiboUserInfo userInfo){

        if (StringUtils.isBlank(userInfo.getUserLoginName())||StringUtils.isBlank(userInfo.getUserLoginPasspwd())){
            return new Result("401","用户名密码不能为空");
        }

        //先去查数据库,用户名和密码是否匹配,不匹配则记录登录次数
        QueryWrapper<WeiboUserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(WeiboUserInfo::getUserLoginName,userInfo.getUserLoginName());

        //用户名不能重复
        WeiboUserInfo user = weiboUserInfoService.getOne(queryWrapper);

        if (user==null){

            return checkUserLoginTimes();

        }else {

            if (user.getUserLoginPasspwd().equals(userInfo.getUserLoginPasspwd())){
                //跳转到相应页面,前端跳转
                return new Result("401","登录成功");
            }else {

                return checkUserLoginTimes();
            }

        }

    }

    private Result checkUserLoginTimes(){

        //先取
        String loginTimesStr = (String) redisTemplate.opsForValue().get("loginTimes");
        Integer loginTimes = Integer.parseInt(loginTimesStr);
        if (loginTimes==null){

            loginTimes=0;
            redisTemplate.opsForValue().set("loginTimes","0");

        }

        if (loginTimes>=5){
            redisTemplate.expire("loginTimes",5, TimeUnit.SECONDS);
            return  new Result("401","账户被锁定,请20分钟后登录");
        }

        redisTemplate.opsForValue().increment("loginTimes",(long)1);
        return new Result("401","用户名或密码不正确");

    }

你可能感兴趣的:(redis)