最近突然用到 ip获取城市省份信息这些,不想使用api,长话短说,以下是实现方法
首先在maven中引入如下包。
java
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>2.7.0</version>
</dependency>
我这边使用工具类进行的去进行,让需要用到的地方进行直接使用,在代码中的xdb文件是ip地理位置信息的数据库文件,目前放在本地的
java
@Slf4j
public class Ip2RegionUtil {
public static String findByIp(String ip) {
InputStream inputStream = null;
try {
inputStream = new ClassPathResource("/ipdb/ip2region.xdb").getInputStream();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
byte[] dbBinStr = null;
try {
dbBinStr = FileCopyUtils.copyToByteArray(inputStream);
Searcher searcher = Searcher.newWithBuffer(dbBinStr);
return searcher.search(ip);
} catch (Exception e) {
log.error("ip转换异常【{}】,【{}】",ip,e);
return "未知ip";
}finally {
try {
inputStream.close();
} catch (IOException e) {
log.error("关闭ip2.xdb流异常【{}】",e.getMessage());
}
}
}
以上即可实现ip获取城市的省份信息了。 切记如果是maven项目 pom 文件中记得将xdb文件放开不要一起打包
xdb 文件路径 ip2region/binding at master · lionsoul2014/ip2region · GitHub
或在联系我,我这儿也可以给