基于Redis实现每日登录失败次数限制
1.思路
下面是我以前写的代码,没考虑高并发场景。如果是高并发场景下,要考虑到redis的set方法覆盖值问题,可以使用incr来替代get,set保证数据安全
通过redis记录登录失败的次数,以用户的username为key
每次收到登录的请求时,都去redis查询登录次数是否已经大于等于我们设置的限制次数,是的话直接返回
2.代码
前台登录和后台查询数据库的代码省略
2.1controller
我这里使用的Jboot,获取redisTemplate的方式是Jboot.me().getRedis(),spring的话用jedisTemplate就行.
//如果用户输入账号密码有效登录超过限制次数,24小时禁止登录
//设置一天限制失败次数,默认为10次
finalintlimit=3;
JbootRedisjr=Jboot.me().getRedis();
//Constants.LOGIN_COUNT="LOGIN_COUNT"
//account是页面传过来的username
Stringkey=Constants.LOGIN_COUNT+"_"+account;
Integercount=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中增加登录失败的次数
IntegernewCount=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.2IncrFailLoginCount方法
/**
*一天中登录失败的次数统计
*@paramkeyredis中存储的键
*@paramcount已经登录失败的次数
*@returncount登录失败次数
*/
privateIntegerIncrFailLoginCount(Stringkey,Integercount){
JbootRedisjr=Jboot.me().getRedis();
count++;
//设置过期时间为今晚23点59分59秒
longtimeInMillis=DateUtils.getMillsecBeforeMoment(23,59,59,999);
if(timeInMillis<100){
//避免在最后一秒的时候登录导致过期时间过小甚至为负数
timeInMillis=1000*60;
}
//设置过期时间
jr.set(key,count);
//这里注意顺序,先set再pexpire
jr.pexpire(key,timeInMillis);
returncount;
}
这里用到了时间的一个工具类,具体代码如下:
/**
*获取当前时间到指定时刻前的毫秒数
*@paramhour指定时刻的小时
*@parammin指定时刻的分钟
*@paramsec指定时刻的秒
*@parammill指定时刻的毫秒
*@return
*/
publicstaticlonggetMillsecBeforeMoment(inthour,intmin,intsec,intmill){
returngetMillisecBetweenDate(newDate(),getMoment(hour,min,sec,mill));
}
/**
*获取两个日期之间的毫秒数
*@parambefore
*@paramafter
*@return
*/
publicstaticlonggetMillisecBetweenDate(Datebefore,Dateafter){
longbeforeTime=before.getTime();
longafterTime=after.getTime();
returnafterTime-beforeTime;
}
/**
*获取当天的某一时刻Date
*@paramhour24小时
*@parammin分钟
*@paramsec秒
*@parammill毫秒
*@return
*/
publicstaticDategetMoment(inthour,intmin,intsec,intmill){
Calendarcalendar=Calendar.getInstance();
calendar.setTime(newDate());
calendar.set(Calendar.HOUR_OF_DAY,hour);
calendar.set(Calendar.MINUTE,min);
calendar.set(Calendar.SECOND,sec);
calendar.set(Calendar.MILLISECOND,mill);
returncalendar.getTime();
}
3.总结
这里有个地方要注意,就是redis设置过期时间后,重新set会清除过期效果,重新变成永久状态,所以需要每次都pexpire()
redis中还有一个方法:incr(),每次调用这个方法,都会让一个键的值+1,如果没有这个键,会初始为0再+1.适合做计数器,也能再这个案例中使用,但是我这里只是希望登录失败的时候才计数+1,登录之前直接判断count,所以使用了传统的get(),set().有兴趣的同学可以去详细了解.