导入依赖
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>2.6.5</version>
</dependency>
ip2region.xdb 文件放到resources文件夹下
链接地址:https://gitee.com/lionsoul/ip2region/tree/master/binding/java
测试代码
import org.lionsoul.ip2region.xdb.Searcher;
import java.io.*;
import java.util.concurrent.TimeUnit;
public class SearcherTest {
public static void main(String[] args) {
String dbPath = "ip2region.xdb file path";
// 1、从 dbPath 中预先加载 VectorIndex 缓存,并且把这个得到的数据作为全局变量,后续反复使用。
byte[] vIndex;
try {
vIndex = Searcher.loadVectorIndexFromFile(dbPath);
} catch (Exception e) {
System.out.printf("failed to load vector index from `%s`: %s\n", dbPath, e);
return;
}
// 2、使用全局的 vIndex 创建带 VectorIndex 缓存的查询对象。
Searcher searcher;
try {
searcher = Searcher.newWithVectorIndex(dbPath, vIndex);
} catch (Exception e) {
System.out.printf("failed to create vectorIndex cached searcher with `%s`: %s\n", dbPath, e);
return;
}
// 3、查询
try {
String ip = "1.2.3.4";
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);
}
// 4、关闭资源
searcher.close();
// 备注:每个线程需要单独创建一个独立的 Searcher 对象,但是都共享全局的制度 vIndex 缓存。
}
}
以上代码本地环境貌似没有问题,但是打成jar包后会报找不到文件异常,因为读取jar报文件要以二进制流形式才能读取到,因此线上环境要换一种写法
@Configuration
@Slf4j
public class IpSearchConfig {
@Bean
public Searcher getSearch() {
//部署时使用的代码
try{
//读取jar包内的配置文件信息
ClassPathResource resource = new ClassPathResource("ip2region.xdb");
InputStream inputStream = resource.getInputStream();
byte[] dbBinStr = IoUtil.readBytes(inputStream);
Searcher searcher = Searcher.newWithBuffer(dbBinStr);
return searcher;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String getRegion(String ip){
// 3、查询
try {
log.error("ip:"+ip);
Searcher searcher=getSearch();
log.error("searcher:"+searcher);
String region = searcher.search(ip);
return region;
} catch (Exception e) {
log.error("根据ip获取地址出错:{}",e);
}
return "";
}
}