三人行必有我师

GeoIP解析IP地理位置

Logstash | 作者 ziyou | 发布于2019年12月20日 | | 阅读数:9017


我们在对IP进行解析的时候使用maxmind提供的提供的GeoLite2,这个是maxmind提供的GeoIP2的免费版本,其准确率稍低于付费版本,可以很好的对IP进行地域解析,可以满足我们的需求。
          GeoLite2有提供各种版本的API供开发者使用,我们就主要是用的是java版本的API。具体步骤如下:1、下载maxmind DB数据库

在maxmind官网下载需要的IP解析数据库,里面有两种数据库,一是国家数据库,一是城市数据库,我们使用的基本都是城市数据库,下载选择二进制格式。网页地址:GeoLite2 开源数据库

2、安装软件包,建议使用maven安装此软件包,将以下依赖添加到pom.xml中。
<dependency>
<groupId> com.maxmind.geoip2 </groupId >
<artifactId > geoip2 </artifactId >
<version >2.12.0</version >
</dependency >
3、使用
// A File object pointing to your GeoIP2 or GeoLite2 database
System.out.println(GeoIP2Test.class.getClassLoader().getResource("GeoLite2-City.mmdb").toString().replaceFirst("/",""));
File database = new File(GeoIP2Test.class.getClassLoader().getResource("GeoLite2-City.mmdb").toString().replaceFirst("file:/",""));

// This creates the DatabaseReader object. To improve performance, reuse
// the object across lookups. The object is thread-safe.
DatabaseReader reader = new DatabaseReader.Builder(database).build();


InetAddress ipAddress = InetAddress.getByName("128.101.101.101");

// Replace "city" with the appropriate method for your database, e.g.,
// "country".
CityResponse response = reader.city(ipAddress);
Country country = response.getCountry();
System.out.println(country.getIsoCode()); // 'US'
System.out.println(country.getName()); // 'United States'
System.out.println(country.getNames().get("zh-CN")); // '美国'


Subdivision subdivision = response.getMostSpecificSubdivision();
System.out.println(subdivision.getName()); // 'Minnesota'
System.out.println(subdivision.getIsoCode()); // 'MN'


City city = response.getCity();
System.out.println(city.getName()); // 'Minneapolis'


Postal postal = response.getPostal();
System.out.println(postal.getCode()); // '55455'


Location location = response.getLocation();
System.out.println(location.getLatitude()); // 44.9733
System.out.println(location.getLongitude()); // -93.2323

[尊重社区原创,转载请保留或注明出处]
本文地址:http://elasticsearch.cn/article/13594


0 个评论

要回复文章请先登录注册