1.背景
現在的社交平臺一般都需要展示用戶的歸屬地,這個功能有下面二個主要功能點,接下來我們來介紹下具體實現。
-
IP 獲取
-
IP 轉歸屬地
2.ip獲取
2.1 Http請求
對于controller的請求,我們只需要寫個攔截器,將用戶的ip設置進上下文即可,非常方便。
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {RequestInfo info = new RequestInfo(); info.setUid(Optional.ofNullable(request.getAttribute(TokenInterceptor.ATTRIBUTE_UID)).map(Object::toString).map(Long::parseLong).orElse(null));info.setIp(ServletUtil.getClientIP(request));RequestHolder.set(info);return true;
}
ip在請求頭中都會攜帶。直接用hutool的工具類獲取ip
public static String getClientIP(HttpServletRequest request, String... otherHeaderNames) {String[] headers = {"X-Forwarded-For", "X-Real-IP", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR"};if (ArrayUtil.isNotEmpty(otherHeaderNames)) {headers = ArrayUtil.addAll(headers, otherHeaderNames);}return getClientIPByHeader(request, headers);
}
需要注意的是,如果我們開啟了nginx來帶來請求,需要在nginx里面保存用戶真實ip到X-Real-IP,否則你拿到的就是nginx的ip地址了。
location /{proxy_pass http://127.0.0.1:8088;# 在 Nginx 的配置文件中使用 $remote_addr 可以獲取到客戶端的 IP 地址,# 這是因為 Nginx 會在接收到客戶端請求時自動將客戶端的真實 IP 地址存儲在 $remote_addr 變量中。Malichyet proxy_set_header X-Real-IP $remote_elidnchatproxy_set_header Host $host;
}
2.2 websocket請求
對于websocket請求獲取ip就會麻煩一些。