获取真实IP
public class IPUtils {
public static String getRealIP(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
if( ip.indexOf(",")!=-1 ){
ip = ip.split(",")[0];
}
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
System.out.println("Proxy-Client-IP ip: " + ip);
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
System.out.println("WL-Proxy-Client-IP ip: " + ip);
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
System.out.println("HTTP_CLIENT_IP ip: " + ip);
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
System.out.println("HTTP_X_FORWARDED_FOR ip: " + ip);
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
System.out.println("X-Real-IP ip: " + ip);
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
System.out.println("getRemoteAddr ip: " + ip);
}
return ip;
}
}
根据IP锁定限制时间
@Component
public class LoginStintUtil {
@Autowired
private StringRedisTemplate stringRedisTemplate;
public boolean loginStint(String realIp) {
ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
String loginCount = opsForValue.get(Const.SHIRO_LOGIN_IP + realIp);
if (Const.LOCK.equals(loginCount)) {
return Const.LOCK.equals(opsForValue.get(Const.SHIRO_LOGIN_IP + realIp));
}
opsForValue.increment(Const.SHIRO_LOGIN_IP + realIp, 1);
if (StringUtils.isNotEmpty(loginCount)) {
if (Integer.parseInt(loginCount) >= Const.LOGIN_COUNT) {
opsForValue.set(Const.SHIRO_LOGIN_IP + realIp, Const.LOCK);
stringRedisTemplate.expire(Const.SHIRO_LOGIN_IP + realIp, 1, TimeUnit.HOURS);
}
}
return Const.LOCK.equals(opsForValue.get(Const.SHIRO_LOGIN_IP + realIp));
}
public void removeRedisLoginCount(String realIp) {
ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
opsForValue.set(Const.SHIRO_LOGIN_IP + realIp, "0");
}
}
调用方法检测是否锁定,
String realIp = IPUtils.getRealIP(request);
if (StringUtils.isNotBlank(realIp)){
boolean isLock = loginStintUtil.loginStint(realIp);
if (isLock) {
response.setMessage("您已登录失败5次,请一小时后再登录");
return response;
}else {
loginStintUtil.removeRedisLoginCount(realIp);
}
}