Spring boot集成ip2region,打成jar包后无法读取ip2region文件

问题回顾

项目工程结构重构成基于maven模块化管理,运行编译后的jar无法读取ip2region.db配置文件,抛出异常:FileNotFoundException.

问题处理

初始代码

      //db
        String dbPath = AddressUtils.class.getResource("/ip2region.db").getPath();
        File file = new File(dbPath);
        if (file.exists() == false) {
            Console.log("Error: Invalid ip2region.db file");
        }
            DbConfig config = new DbConfig();
            DbSearcher searcher = new DbSearcher(config, dbPath);

问题修复

//        读取jar包内的配置文件信息
        ClassPathResource resource = new ClassPathResource("/ip2region.db");
        InputStream inputStream = resource.getInputStream();
            byte[] dbBinStr = IoUtil.readBytes(inputStream);
            DbConfig config = new DbConfig();
            DbSearcher searcher = new DbSearcher(config, dbBinStr);
           // 查询算法memory,采用二进制方式初始化DBSearcher需要使用MEMORY_ALGORITYM,
           //否则会抛出null。
            Method method = searcher.getClass().getMethod("memorySearch", String.class);
           String ip = ((DataBlock) method.invoke(searcher, ip)).getRegion();

外链

参考链接:https://gitee.com/lionsoul/ip2region/issues/IILFL

mica开源的ip2region boot stater:https://segmentfault.com/a/1190000022622489

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。