springboot項目中集成ip2region遇到的問題及終極解決辦法


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";
}

注:GlobalConfig.getProfile()是配置的本地文件存儲路徑

代碼地址:[代碼下載]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM