我有一个登录功能,如果用户调用它超过5次,我希望我的功能在10秒钟内不起作用,那我该怎么办?如果有人回答我的问题,我会很高兴。
You need to record failed login attempts for a user (eg in database
) and once it reaches the threshold, you need to return error response from login
method for configurable amount of time from the last failed login attempt, eg:
x
minutes from that timestamp function not work for example 10 seconds
You need to be specific on what exactly you mean by function not to work . But if you simply wanted to block the method call for x
seconds, follow the below approach:
You need to create a counter
to count the number of attempts and then if(counter>5)
then use Thread.sleep(10000) to make the request to hold (sleep) for 10 seconds. Ideally, the counter
value should be persisted to a database (or any other storage) and read it again to validate the number of attempts.
But, I strongly suggest you follow @Darshan's answer which makes more sense.
First you need to identify the user .
This can be done on the basis of IP .
Have a ConcurrentHashMap
ConcurrentHashMap<String,Long>IpAddressValidationMap // String is the Ip address and Long is the timeInMilleseconds
You make a filter and put a check
public void prefilterFunction(RequestObject object)
{
String ip=object.getIP(); // just an example not the standard call for getting Ip addr
Long time=IpAddressValidationMap.get(ip);
if(time!=null)
{
if(time<THRESHOLD_TIME)
{
return ;
}
else
{
// We allow the user to proceed
}
}
}
public void validateLogin(RequestObject object)
{
// if the login fails
IpAddressValidationMap.put(ipAddr,System.currentTimeinMIllis());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.