参考github:https://github.com/lionsoul2014/ip2region/blob/master/data/ip2region.xdb
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>2.7.0</version>
</dependency>
package com.sun.springboot.controller.test;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
/**
* @author Mr.sunql
* @description
* @date Created in17:34 2024/4/7
*/
@Component
public class SearcherTest {
@Autowired
private ResourceLoader resourceLoader;
public static void main(String[] args) {
// 1、创建 searcher 对象
Searcher searcher = null;
try {
// URL url = ResourceUtils.getURL("classpath:ip2region.xdb");
// System.out.println(url);
ClassPathResource classPathResource=new ClassPathResource("ip2region.xdb");
String dbFile = classPathResource.getFile().getPath();
System.out.println(dbFile);
searcher = Searcher.newWithFileOnly(dbFile);
} catch (IOException e) {
System.out.printf("failed to create searcher with `%s`: %s\n", e);
return;
}
// 2、查询
try {
String ip = "112.200.214.160";
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);
// 3、关闭资源
searcher.close();
} catch (Exception e) {
System.out.printf("failed to search(%s): %s\n", e);
}
// 备注:并发使用,每个线程需要创建一个独立的 searcher 对象单独使用。
}
}