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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值