zoukankan      html  css  js  c++  java
  • 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()是配置的本地文件存储路径

    代码地址:[代码下载]

  • 相关阅读:
    编译安装LAMP之安装Apache+php与管理(十五)
    编译安装Mysql与管理(十四)
    linux服务器的性能分析与优化(十三)
    awk和sed (十二)
    Bash Shell (十一)
    linux 计划任务(十)
    Linux文本编辑器(九)
    linux rsync介绍(八)
    yum安装LAMP环境与管理(七)
    mysql date数据类型异常原因0000-00
  • 原文地址:https://www.cnblogs.com/entfrm/p/12554943.html
Copyright © 2011-2022 走看看