当服务部署在服务器上时,一般都是通过nginx做代理转发,但是在common中的aop日志打印时, ip获取到的就变成本地的了,可以通过修改nginx的代理配置, 以及后端的工具类解析, 打印真实ip.
nginx配置
只需配置在监听的对应端口下就可以全部生效
server {
listen 8080;
server_name localhost;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
location /api {
proxy_pass http://localhost:8008/api;
}
}
配置后重启
这样nginx就会携带者ip打到应用在,在应用中通过IPUtil解析获取真实IP
/**
* 获取真实ip
* @param request
* @return
*/
public static String getIpFromRequest(HttpServletRequest request) {
String ip;
if (StringUtils.isNotBlank(ip=request.getHeader(“x-real-ip”))){
return ip;
}
boolean found = false;
if (StringUtils.isNotBlank((ip = request.getHeader(“x-forwarded-for”)))) {
StringTokenizer tokenizer = new StringTokenizer(ip, “,”);
while (tokenizer.hasMoreTokens()) {
ip = tokenizer.nextToken().trim();
if (isIPv4Valid(ip) && !isIPv4Private(ip)) {
found = true;
break;
}
}
}
if (!found) {
ip = request.getRemoteAddr();
}
if (StringUtils.equals(ip,”0:0:0:0:0:0:0:1″)){
log.error(“未能解析IP, 可能原因[nginx未配置,传递真实IP]”);
}
return ip;
}