背景:
项目在海外运行,需要根据IP获取国家,城市,经纬度等信息,但是,百度地图、高德地图、淘宝等API的使用不了,而谷歌地图的又有频率限制,于是网上各种搜索,找到 GeoLiteCity.dat,GeoLiteCity.dat就好比一个本地的数据库文件,方法如下:
引入依赖:
<dependency>
<groupId>com.maxmind.geoip</groupId>
<artifactId>geoip-api</artifactId>
<version>1.3.1</version>
</dependency>
测试类如下:
public class IPTest {
public static void main(String[] args) {
try {
LookupService cl = new LookupService("C:\\GeoLiteCity.dat", LookupService.GEOIP_MEMORY_CACHE);
Location l2 = cl.getLocation("128.1.35.120");
System.out.println(
"countryCode: " + l2.countryCode +"\n"+
"countryName: " + l2.countryName +"\n"+
"region: " + l2.region +"\n"+
"city: " + l2.city +"\n"+
"latitude: " + l2.latitude +"\n"+
"longitude: " + l2.longitude);
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行结果如下:
countryCode: TH
countryName: Thailand
region: 40
city: Bangkok
latitude: 13.753998
longitude: 100.5014
项目中使用如下:
import com.maxmind.geoip.Location;
import com.maxmind.geoip.LookupService;
/**
* @author: xbq
* @Date: 2018/8/1 09:35
*/
@Service
public class LoadIp {
private LookupService cl;
@PostConstruct
public void init() {
try {
cl = new LookupService(systemConstants.getIpDb(), LookupService.GEOIP_MEMORY_CACHE);
} catch (IOException e) {
CusLogger.error("加载ip纯真库异常:" + e.getMessage(), e);
}
}
/**
* 使用
* @param ip
* @return
*/
public void fun(String ip) {
// 根据ip来判定国家地区
if(cl != null) {
Location l2 = null;
l2 = cl.getLocation(ip);
if(l2 != null) {
// 获取国家编码
String countryCode = l2.countryCode;
// 获取国家名称
String countryName = l2.countryName;
// 获取城市
String city = l2.city;
// 业务处理 ...
}
}
}
}