AddressUtil地址工具类
本文主要需要在网上下载ip2region.db离线IP地址定位库,下载文件放到项目资源目录下即可,如有改动,也可自行调整获取地址定位资源路径。
需要在pom文件中引入ip2region
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>1.7.2</version>
</dependency>
public class AddressUtil {
private static Logger log = LoggerFactory.getLogger(AddressUtil.class);
public static String getCityInfo(String ip) {
DbSearcher searcher = null;
try {
//ip2region.db是离线地址定位库,可以自行在网上下载
//本文中将**ip2region.db**可放到resources/ip2region 目录下
String dbPath = AddressUtil.class.getResource("/ip2region/ip2region.db").getPath();
File file = new File(dbPath);
if (!file.exists()) {
String tmpDir = System.getProperties().getProperty("java.io.tmpdir");
dbPath = tmpDir + File.separator + "ip.db";
file = new File(dbPath);
InputStream resourceAsStream = AddressUtil.class.getClassLoader().getResourceAsStream("classpath:ip2region/ip2region.db");
if (resourceAsStream != null) {
FileUtils.copyInputStreamToFile(resourceAsStream, file);
}
}
DbConfig config = new DbConfig();
searcher = new DbSearcher(config, file.getPath());
Method method = searcher.getClass().getMethod("btreeSearch", String.class);
if (!Util.isIpAddress(ip)) {
log.error("Error: Invalid ip address");
}
DataBlock dataBlock = (DataBlock) method.invoke(searcher, ip);
return dataBlock.getRegion();
} catch (Exception e) {
log.error("获取地址信息异常,{}", e.getMessage());
return StringUtils.EMPTY;
} finally {
if (searcher != null) {
try {
searcher.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}