前言
最近的一個項目中需要將不同省份的用戶,展示不同內容,所以需要通過Request請求獲取IP地址, 然后通過IP獲取IP對應省份。
這里的操作步驟一共有步:
1. 通過Request獲取IP
2. 通過IP獲取對應省份、城市
3. 通過設置的省份和IP對應省份進行比對,展示內容
通過Request獲取IP
可以參考我的另外一篇文章【Java 通過Request請求獲取IP地址】下面是代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
public class IpAdrressUtil { /** * 獲取Ip地址 * @param request * @return */ private static String getIpAdrress(HttpServletRequest request) { String Xip = request.getHeader( "X-Real-IP" ); String XFor = request.getHeader( "X-Forwarded-For" ); if (StringUtils.isNotEmpty(XFor) && ! "unKnown" .equalsIgnoreCase(XFor)){ //多次反向代理后會有多個ip值,第一個ip才是真實ip int index = XFor.indexOf( "," ); if (index != - 1 ){ return XFor.substring( 0 ,index); } else { return XFor; } } XFor = Xip; if (StringUtils.isNotEmpty(XFor) && ! "unKnown" .equalsIgnoreCase(XFor)){ return XFor; } if (StringUtils.isBlank(XFor) || "unknown" .equalsIgnoreCase(XFor)) { XFor = request.getHeader( "Proxy-Client-IP" ); } if (StringUtils.isBlank(XFor) || "unknown" .equalsIgnoreCase(XFor)) { XFor = request.getHeader( "WL-Proxy-Client-IP" ); } if (StringUtils.isBlank(XFor) || "unknown" .equalsIgnoreCase(XFor)) { XFor = request.getHeader( "HTTP_CLIENT_IP" ); } if (StringUtils.isBlank(XFor) || "unknown" .equalsIgnoreCase(XFor)) { XFor = request.getHeader( "HTTP_X_FORWARDED_FOR" ); } if (StringUtils.isBlank(XFor) || "unknown" .equalsIgnoreCase(XFor)) { XFor = request.getRemoteAddr(); } return XFor; } } |
通過IP獲取對應省份、城市
使用【GeoLite2 City】庫
目前開源的IP地址庫與城市對應關系用的比較多的是MaxMind公司的GeoLite數據庫,GeoLite數據庫有開源版本和收費版本,我們使用的是開源版本,GeoLite目前已經更新到2了,所以我們下載GeoLite2 City庫。
官方下載地址是【http://dev.maxmind.com/geoip/geoip2/geolite2/】
如果覺得慢就用迅雷下。下載完成后就是,下載完成就解壓。得到【GeoLite2-City.mmdb】文件,這個就是數據庫。
Java例子是這樣使用的:
首先在項目中加入maven支持
1
2
3
4
5
|
<dependency> <groupId>com.maxmind.geoip2</groupId> <artifactId>geoip2</artifactId> <version> 2.8 . 1 </version> </dependency> |
然后通過GeoLite2查詢得到省份、城市:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
public static void main(String[] args) throws Exception{ // 創建 GeoLite2 數據庫 File database = new File( "/Users/admin/GeoLite2-City.mmdb" ); // 讀取數據庫內容 DatabaseReader reader = new DatabaseReader.Builder(database).build(); InetAddress ipAddress = InetAddress.getByName( "171.108.233.157" ); // 獲取查詢結果 CityResponse response = reader.city(ipAddress); // 獲取國家信息 Country country = response.getCountry(); System.out.println(country.getIsoCode()); // 'CN' System.out.println(country.getName()); // 'China' System.out.println(country.getNames().get( "zh-CN" )); // '中國' // 獲取省份 Subdivision subdivision = response.getMostSpecificSubdivision(); System.out.println(subdivision.getName()); // 'Guangxi Zhuangzu Zizhiqu' System.out.println(subdivision.getIsoCode()); // '45' System.out.println(subdivision.getNames().get( "zh-CN" )); // '廣西壯族自治區' // 獲取城市 City city = response.getCity(); System.out.println(city.getName()); // 'Nanning' Postal postal = response.getPostal(); System.out.println(postal.getCode()); // 'null' System.out.println(city.getNames().get( "zh-CN" )); // '南寧' Location location = response.getLocation(); System.out.println(location.getLatitude()); // 22.8167 System.out.println(location.getLongitude()); // 108.3167 } |
如果是生產環境,可以直接創建一個Service,在Service初始化的時候創建reader對象,然后在公共方法中通過ip查詢地址,下面以省份為例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
import com.maxmind.geoip2.DatabaseReader; import com.maxmind.geoip2.model.CityResponse; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; import java.io.File; import java.net.InetAddress; /** * IP地址服務 */ @Service public class IpAddressService { private static Logger logger = LoggerFactory.getLogger(IpAddressService. class ); private static String dbPath = "/usr/local/GeoLite2-City.mmdb" ; private static DatabaseReader reader; @Autowired private Environment env; @PostConstruct public void init() { try { String path = env.getProperty( "geolite2.city.db.path" ); if (StringUtils.isNotBlank(path)) { dbPath = path; } File database = new File(dbPath); reader = new DatabaseReader.Builder(database).build(); } catch (Exception e) { logger.error( "IP地址服務初始化異常:" + e.getMessage(), e); } } public String getSubdivision(String ipAddress){ try { CityResponse response = reader.city(InetAddress.getByName(ipAddress)); return response.getMostSpecificSubdivision().getNames().get( "zh-CN" ); } catch (Exception e){ logger.error( "根據IP[{}]獲取省份失敗:{}" , ipAddress, e.getMessage()); return null ; } } } |
然后在需要的地方就行判斷:
1
2
3
4
5
6
|
String areaNames = { "北京" , "天津" , "上海" }; String subdivision = ipAddressService.getSubdivision(getIpAdrress(request)); // 匹配 if (containsArea(subdivision, areaNames)){ // 處理... } |
匹配方法:
1
2
3
4
5
6
7
8
9
10
11
|
private boolean containsArea(String name, String[] areaNames) { if (StringUtils.isBlank(name)){ return false ; } for (String areaName : areaNames){ if (name.contains(areaName)){ return true ; } } return false ; // 按地域返回數據 } |
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:http://blog.csdn.net/chwshuang/article/details/71951000