Springboot在使用ip2region的时候一直在报
java.io.FileNotFoundException: ip2region.xdb file path (系统找不到指定的文件。)
找了半天找到了这个(spring boot 整合 ip2region(ip地址库))
直接解决了
// 官网的例子
//searcher = Searcher.newWithFileOnly(dbPath);
// 解决方法
File file = ResourceUtils.getFile("classpath:" + "ip2region.xdb");
searcher = Searcher.newWithFileOnly(file.getAbsolutePath());
完整代码
public static void main(String[] args) {
// 1、创建 searcher 对象
String dbPath = "ip2region.xdb file path";
Searcher searcher = null;
try {
//searcher = Searcher.newWithFileOnly(dbPath);
File file = ResourceUtils.getFile("classpath:" + "ip2region.xdb");
searcher = Searcher.newWithFileOnly(file.getAbsolutePath());
} catch (Exception e) {
System.out.printf("failed to create searcher with `%s`: %s\n", dbPath, e);
return;
}
String ip = "127.0.0.1";
// 2、查询
try {
long sTime = System.nanoTime();
String region = searcher.search(ip);
long cost = TimeUnit.NANOSECONDS.toMicros((long) (System.nanoTime() - sTime));
System.out.printf("{region: %s, ioCount: %d, took: %d μs}\n", region, searcher.getIOCount(), cost);
} catch (Exception e) {
System.out.printf("failed to search(%s): %s\n", ip, e);
}
// 3、关闭资源
try {
searcher.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
// 备注:并发使用,每个线程需要创建一个独立的 searcher 对象单独使用。
}
xdb文件官网所在路径
xdb文件本地所在路径
maven
<!-- ip地址库 -->
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>2.6.4</version>
</dependency>
官网地址https://github.com/lionsoul2014/ip2region/tree/master/binding/java