依赖
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>2.7.0</version>
</dependency>
//maven拦截resource目录文件
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>xdb</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
代码
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.lionsoul.ip2region.xdb.Searcher;
import java.io.File;
import java.io.InputStream;
/**
* 根据ip查询地址
*/
@Slf4j
public final class AddressUtil {
private static Searcher searcher = null;
static {
try {
String dbPath = AddressUtil.class.getResource("/ip2region/ip2region.xdb").getPath();
File file = new File(dbPath);
if (!file.exists()) {
String tmpDir = System.getProperties().getProperty("java.io.tmpdir");
dbPath = (tmpDir.endsWith(File.separator) ? tmpDir : tmpDir + File.separator) + "ip2region.xdb";
file = new File(dbPath);
String classPath = "classpath:ip2region/ip2region.xdb";
InputStream resourceAsStream = ResourceUtil.getStreamSafe(classPath);
if (resourceAsStream != null) {
FileUtils.copyInputStreamToFile(resourceAsStream, file);
}
}
// 1、从 dbPath 加载整个 xdb 到内存。
byte[] cBuff = null;
try {
cBuff = Searcher.loadContentFromFile(dbPath);
} catch (Exception e) {
log.error("failed to load content from `%s`: %s\n", dbPath, e);
}
// 2、使用上述的 cBuff 创建一个完全基于内存的查询对象。
try {
searcher = Searcher.newWithBuffer(cBuff);
} catch (Exception e) {
log.error("failed to create content cached searcher: %s\n", e);
}
log.info("bean [{}]", searcher);
} catch (Exception e) {
log.error("init ip region error", e);
}
}
private AddressUtil() {
}
/**
* 解析IP
*
* @param ip ip
* @return 地区
*/
public static String getRegion(String ip) {
try {
//db
if (searcher == null || StrUtil.isEmpty(ip)) {
log.error("Searcher is null");
return StrUtil.EMPTY;
}
long startTime = System.currentTimeMillis();
String result = searcher.search(ip);
long endTime = System.currentTimeMillis();
log.debug("region use time[{}] result[{}]", endTime - startTime, result);
return result;
} catch (Exception e) {
log.error("根据ip查询地区失败:", e);
}
return StrUtil.EMPTY;
}
}