1、問題回顧
按照ip2region項目的官方集成到springboot項目后,運行測試一切都ok,沒有任何問題。但是當項目打成可執行的jar包后再運行,卻顯示找不到ip2region.db,無法找到資源文件的錯誤。異常代碼如下:
java.io.FileNotFoundException: class path resource [ip2region/ip2region.db] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/app.jar!/BOOT-INF/classes!/ip2region/ip2region.db
2、解決辦法
將ip2region.db文件放到本地目錄,然后直接讀取本地文件進行ip解析,代碼如下:
public static String getCityInfo(String ip) {
DbSearcher searcher = null;
try {
String dbPath = GlobalConfig.getProfile() + "ip2region/ip2region.db";
//String dbPath = "f:/profile/ip2region/ip2region.db"; //本地測試使用地址
File file = new File(dbPath);
if (file.exists()) {
DbConfig config = new DbConfig();
searcher = new DbSearcher(config, file.getPath());
Method method = searcher.getClass().getMethod("btreeSearch", String.class);
if (!Util.isIpAddress(ip)) {
log.error("Error: Invalid ip address");
}
DataBlock dataBlock = (DataBlock) method.invoke(searcher, ip);
return dataBlock.getRegion();
}
} catch (Exception e) {
log.error("獲取地址信息異常:{}", e.getLocalizedMessage());
}
return "XX XX";
}