|
@@ -38,21 +38,50 @@ public class IPLocationUtil {
|
|
* 初始化IP地址索引
|
|
* 初始化IP地址索引
|
|
*/
|
|
*/
|
|
private static void initIpSearcher() {
|
|
private static void initIpSearcher() {
|
|
- try (InputStream is = IPLocationUtil.class.getClassLoader().getResourceAsStream("ip/ip2region.xdb")) {
|
|
|
|
- if (is == null) {
|
|
|
|
- log.error("IPLocationUtil ip2region资源不存在: ip/ip2region.xdb");
|
|
|
|
- searcher = null;
|
|
|
|
|
|
+ try {
|
|
|
|
+ // 1) 外部路径优先:系统属性 ip2region.db 或 环境变量 IP2REGION_DB_PATH
|
|
|
|
+ String externalPath = System.getProperty("ip2region.db");
|
|
|
|
+ if (externalPath == null || externalPath.trim().isEmpty()) {
|
|
|
|
+ externalPath = System.getenv("IP2REGION_DB_PATH");
|
|
|
|
+ }
|
|
|
|
+ if (externalPath != null && !externalPath.trim().isEmpty()) {
|
|
|
|
+ searcher = Searcher.newWithFileOnly(externalPath.trim());
|
|
|
|
+ log.info("IPLocationUtil ip2region初始化成功 (external path: {})", externalPath);
|
|
return;
|
|
return;
|
|
}
|
|
}
|
|
- byte[] cBuff = is.readAllBytes();
|
|
|
|
- searcher = Searcher.newWithBuffer(cBuff);
|
|
|
|
- log.info("IPLocationUtil ip2region初始化成功 (classpath)");
|
|
|
|
|
|
+
|
|
|
|
+ // 2) 从classpath读取写入临时文件,再基于文件初始化
|
|
|
|
+ try (InputStream is = IPLocationUtil.class.getClassLoader().getResourceAsStream("ip/ip2region.xdb")) {
|
|
|
|
+ if (is == null) {
|
|
|
|
+ log.error("IPLocationUtil ip2region资源不存在: ip/ip2region.xdb");
|
|
|
|
+ searcher = null;
|
|
|
|
+ return;
|
|
|
|
+ }
|
|
|
|
+ byte[] cBuff = is.readAllBytes();
|
|
|
|
+ java.nio.file.Path tmp = java.nio.file.Files.createTempFile("ip2region", ".xdb");
|
|
|
|
+ java.nio.file.Files.write(tmp, cBuff);
|
|
|
|
+ subtleSetDeleteOnExit(tmp);
|
|
|
|
+ searcher = Searcher.newWithFileOnly(tmp.toString());
|
|
|
|
+ log.info("IPLocationUtil ip2region初始化成功 (temp file: {})", tmp);
|
|
|
|
+ }
|
|
} catch (Exception e) {
|
|
} catch (Exception e) {
|
|
log.error("IPLocationUtil ip2region初始化失败", e);
|
|
log.error("IPLocationUtil ip2region初始化失败", e);
|
|
searcher = null;
|
|
searcher = null;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
|
|
+ /**
|
|
|
|
+ * 尝试标记临时文件在JVM退出时删除
|
|
|
|
+ */
|
|
|
|
+ private static void subtleSetDeleteOnExit(java.nio.file.Path tmp) {
|
|
|
|
+ try {
|
|
|
|
+ java.io.File f = tmp.toFile();
|
|
|
|
+ f.deleteOnExit();
|
|
|
|
+ } catch (Exception ignore) {
|
|
|
|
+ // no-op
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+
|
|
/**
|
|
/**
|
|
* 根据IP地址获取三级地址信息
|
|
* 根据IP地址获取三级地址信息
|
|
*
|
|
*
|