负载均衡时获取用户真实IP_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 负载均衡时获取用户真实IP

负载均衡时获取用户真实IP

 2017/8/4 21:31:19  永无止境2313  程序员俱乐部  我要评论(0)
  • 摘要:正常情况下,request请求获取用户IP的api为request.getRemoteAddr()可是某些情况下,这不是正确答案负载均衡时,获取的就是反向代理服务器的地址要获取真实用户ip,需做如下配置修改在前端nginx上需要做如下配置:location/proxy_set_hearderhost$host;proxy_set_headerX-forwarded-for$proxy_add_x_forwarded_for;proxy_set_headerX-real
  • 标签:用户
正常情况下,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.cnblogs.com/lhj588/p/4344354.html
上一篇: iOS 键盘上方增加工具栏 下一篇: 没有下一篇了!
发表评论
用户名: 匿名