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()是配置的本地文件存储路径

代码地址:[代码下载]