正常情况下,request请求获取用户IP的api为request.getRemoteAddr()
可是某些情况下,这不是正确答案
负载均衡时,获取的就是反向代理服务器的地址
要获取真实用户ip,需做如下配置修改
在前端nginx上需要做如下配置:
location /
proxy_set_hearder host $host;
proxy_set_
header X-forwarded-for $proxy_add_x_forwarded_for;
proxy_set_header X-real-ip $remote_addr;
};
class="java" name="code">import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
public class RequestUtils {
private static org.slf4j.Logger logger = LoggerFactory.getLogger(RequestUtils.class);
public static String getClientIp(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
logger.info("x-forwarded-for = {}", ip);
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
logger.info("Proxy-Client-IP = {}", ip);
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
logger.info("WL-Proxy-Client-IP = {}", ip);
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
logger.info("RemoteAddr-IP = {}", ip);
}
if(StringUtils.isNotBlank(ip)) {
ip = ip.split(",")[0];
}
return ip;
}
}
ps:日志格式化输出调用org.slf4j.Logger
参考:
nginx做反向负载均衡,后端服务器获取真实客户端ip
http://www.cnb
logs.com/lhj588/p/4344354.html