GeoLite2实现ip地址转化为城市地址-java
1、GeoLite2下载
下载地址:https://www.maxmind.com/en/accounts/363203/geoip/downloads。下载GeoLite2 City即可。
2、导入依赖
<!-- https://mvnrepository.com/artifact/com.maxmind.geoip2/geoip2 -->
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>2.14.0</version>
</dependency>
3、写测试类
package com.soso.influx.demo;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.InetAddress;
/**
* author:seven lin
* date:2020/7/21 14:39
* description:
**/
public class IP2Adrress {
public static void main(String[] args) throws IOException, GeoIp2Exception {
//GeoIP2-City 数据库文件
// File database = new File("GeoLite2-City.mmdb");
//将GeoLite2-City.mmdb放在resources中,然后使用下面的方式进行读取数据
InputStream database = IP2Adrress.class.getClassLoader().getResourceAsStream("GeoLite2-City.mmdb");
// 创建 DatabaseReader对象
DatabaseReader reader = new DatabaseReader.Builder(database).build();
InetAddress ipAddress = InetAddress.getByName("128.101.101.101");
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
}
}
该类再继承udf类,再把参数转化一下,就可以用在hive上的清洗了。