Springboot项目中集成ip2region遇到的问题及终极解决办法

Springboot整合ip2region的异常解决与实践
本文介绍了在Springboot项目中集成ip2region时遇到的问题,即项目打包后运行找不到ip2region.db资源文件。为解决此问题,文章提出将db文件置于本地目录,直接读取文件进行IP解析的方法,并提供了相关代码示例。

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()是配置的本地文件存储路径
代码地址:[代码下载]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值