最新要用到地理位置做区域划分,需要知道哪个ip属于哪个区,五大洲的区域划分,有两千个IP需要知道,并且查询频率比较高,每十分钟去查询一次,
最开始是用的第三方API去调用,比如淘宝,百度等,但是就怕请求太频繁了,哪天给我黑名单了, 那我线上程序就挂了,还有一个,在国内用的话,是比较方便的,IP纯真数据库,但是我的IP大部分都是国外,定位在国内是没有什么问题,国外就不太准确了,巴西的IP取出来是美国的地址,这个数据库比较小,用起来简单,由于对国外的IP不准确,就放弃了,
然后才开始选择GeoLite2 IP库作为查询目的,不过这个库要手动去更新,不更新其实也能满足现在的需要 用起来也比较简单,文件可能有些大了,63M 大小,
下面开始 试用
1 下载mmdb文件数据库和添加依赖
maven 依赖 下面的配置
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>2.12.0</version>
</dependency>
代码部分 IP库GeoLite2-City.mmdb 我是放在项目的根目录下,
public static void getLiteIPinit() throws IOException, GeoIp2Exception {
//GeoIP2-City 数据库文件
File database = new File(Thread.currentThread().getContextClassLoader().getResource("GeoLite2-City.mmdb").getPath());
// this.getClass().getClassLoader().getResource("").getPath(); 得到的是 ClassPath的绝对URI路径。
// 创建 DatabaseReader对象
DatabaseReader reader = new DatabaseReader.Builder(database).build();
InetAddress ipAddress = InetAddress.getByName("180.168.61.200");
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
}
2 IP纯真数据库 简单使用也说下, 国内还是很不错
maven 依赖
<dependency>
<groupId>com.github.jarod</groupId>
<artifactId>qqwry-java</artifactId>
<version>0.7.0</version>
</dependency>
Java 代码实现
public static void main(String[] args) throws IOException {
//这里因为是去读取本地的纯真库,所以有一个IO异常抛出
QQWry wry = new QQWry();
IPZone zone = wry.findIP("123.123.123.123");
System.out.println(zone.getMainInfo());
System.out.println(zone.getSubInfo());
}
输出:
北京市
联通