Springboot 프로젝트에서 ip2region이 겪는 문제와 궁극적인 해결 방법을 통합합니다

6927 단어 기술 공유

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()은 구성된 로컬 파일 저장 경로입니다.


코드 주소: [코드 다운로드]

좋은 웹페이지 즐겨찾기