提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
目录
前言
业务中需要对业务请求来源进行分析,记录用户所在地区,所以使用了IP2Location来实现对IP地址的解析,得到用户的国家和地区
一、IP2Location是什么?
IP2Location是一个强大的IP地址解析工具,可以将IP地址转换为可读性更高的格式,直观地表示IP地址所属的地理位置、ISP和其它属性信息。
二、使用步骤
1.下载IP2Location 离线包
IP2Location™ LITE IP-COUNTRY-REGION-CITY-LATITUDE-LONGITUDE-ZIPCODE Database 下载后将得到一个ZIP文件,将ZIP文件解压后,使用mmdb结尾的文件例如GeoLite2-City.mmdb文件作为数据源解析
2. 引入IP解析jar包
<!-- https://mvnrepository.com/artifact/com.maxmind.geoip2/geoip2 -->
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>2.15.0</version>
</dependency>
3. 读入GeoLite2-City.mmdb数据
为了保障IP库的时效性,故需定期更新下载IP库文件,重新读取,进行IP解析。
原先使用@Configuration声明DatabaseReader对象,尝试定期修改被Spring管理的DataBaseReader对象失败,故在此使用了单例模式,增加了定时机制,当IP2Location官方更新IP库后,重新下载最新IP库文件,通过setNull2DatabaseReader 将DataBaseReader对象置为NULL,重新实例化
@Slf4j
public class IpDatabaseReader {
private volatile static DatabaseReader databaseReader = null;
public static final String LOCAL_TEST_IP_DATABASE = "dockerfile/geoLite2/GeoLite2-City.mmdb";
private IpDatabaseReader() {
}
public static void setNull2DatabaseReader() {
IpDatabaseReader.databaseReader = null;
}
public static DatabaseReader getInstance() {
try {
if (null == databaseReader) {
synchronized (DatabaseReader.class) {
if (null == databaseReader) {
log.info("实例化IpDatabaseReader");
databaseReader = new DatabaseReader.Builder(new File(LOCAL_TEST_IP_DATABASE)).build();
}
}
}
} catch (Exception e){
e.printStackTrace();
}
return databaseReader;
}
}
4.使用示例
/**
*
* @description: 获得国家
* @param reader
* @param ip
* @return
* @throws Exception
*/
public static String getCountry(DatabaseReader reader, String ip) throws Exception {
return reader.country(InetAddress.getByName(ip)).getCountry().getNames().get("zh-CN");
}
/**
*
* @description: 获得省份
* @param reader
* @param ip
* @return
* @throws Exception
*/
public static String getProvince(DatabaseReader reader, String ip) throws Exception {
return reader.city(InetAddress.getByName(ip)).getMostSpecificSubdivision().getNames().get("zh-CN");
}
/**
*
* @description: 获得城市
* @param reader
* @param ip
* @return
* @throws Exception
*/
public static String getCity(DatabaseReader reader, String ip) throws Exception {
return reader.city(InetAddress.getByName(ip)).getCity().getNames().get("zh-CN");
}