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解析,代码如下:
1public static String getCityInfo(String ip) { 2 DbSearcher searcher = null; 3 try { 4 String dbPath = GlobalConfig.getProfile() + "ip2region/ip2region.db"; 5 //String dbPath = "f:/profile/ip2region/ip2region.db"; //本地测试使用地址 6 File file = new File(dbPath); 7 if (file.exists()) { 8 DbConfig config = new DbConfig(); 9 searcher = new DbSearcher(config, file.getPath()); 10 Method method = searcher.getClass().getMethod("btreeSearch", String.class); 11 if (!Util.isIpAddress(ip)) { 12 log.error("Error: Invalid ip address"); 13 } 14 DataBlock dataBlock = (DataBlock) method.invoke(searcher, ip); 15 return dataBlock.getRegion(); 16 } 17 } catch (Exception e) { 18 log.error("获取地址信息异常:{}", e.getLocalizedMessage()); 19 } 20 return "XX XX"; 21}