YunaiV/yudao-cloud · error · RuntimeException

IPUtils 初始化失败

Error message

IPUtils 初始化失败

What it means

IPUtils statically loads the ip2region.xdb binary from the classpath and wraps any failure (missing file, unreadable bytes, Searcher build error) in RuntimeException('IPUtils 初始化失败'). The class initializes on first use, so the error surfaces far from the configuration cause.

Source

Thrown at yudao-framework/yudao-spring-boot-starter-biz-ip/src/main/java/cn/iocoder/yudao/framework/ip/core/utils/IPUtils.java:40

     * IP 查询器,启动加载到内存中
     */
    private static Searcher SEARCHER;

    static {
        init();
    }

    /**
     * 初始化
     */
    private static void init() {
        try {
            long now = System.currentTimeMillis();
            byte[] bytes = ResourceUtil.readBytes("ip2region.xdb");
            SEARCHER = Searcher.newWithBuffer(bytes);
            log.info("启动加载 IPUtils 成功,耗时 ({}) 毫秒", System.currentTimeMillis() - now);
        } catch (Exception e) {
            throw new RuntimeException("IPUtils 初始化失败", e);
        }
    }

    /**
     * 查询 IP 对应的地区编号
     *
     * @param ip IP 地址,格式为 127.0.0.1
     * @return 地区id
     */
    @SneakyThrows
    public static Integer getAreaId(String ip) {
        return Integer.parseInt(SEARCHER.search(ip.trim()));
    }

    /**
     * 查询 IP 对应的地区编号
     *
     * @param ip IP 地址的时间戳,格式参考{@link Searcher#checkIP(String)} 的返回

View on GitHub (pinned to 477be9dd49)

Solutions

  1. Confirm ip2region.xdb exists in src/main/resources and appears in the built jar (jar tf app.jar | grep xdb).
  2. If git-lfs is used, run git lfs pull before building.
  3. Verify file size/integrity (compare checksum with the upstream ip2region release).
  4. Read getCause() to distinguish missing resource from corrupt content.
Defensive patterns

Strategy: validation

Validate before calling

if (IPUtils.class.getResource("/ip2region.xdb") == null) {
    throw new IllegalStateException("ip2region.xdb missing from classpath — check build resources");
}

Try / catch

try {
    Integer areaId = IPUtils.getAreaId(ip);
} catch (ExceptionInInitializerError e) {
    log.error("IP region lookup disabled; init failed: {}", e.getCause().getCause());
    return null; // graceful degradation for optional geo feature
}

Prevention

When it happens

Trigger: Class load triggered by first getAreaId()/search call when ip2region.xdb is absent from src/main/resources or was excluded from the packaged artifact; or the file is truncated/corrupt so Searcher.newWithBuffer throws.

Common situations: Resource excluded by build filters; large xdb stripped by git-lfs not being pulled before build; jar repackaging tools dropping binary resources; CI builds that skip copying resources.

Related errors


AI-assisted analysis of YunaiV/yudao-cloud@477be9dd49 (2026-08-14). Data as JSON: /api/errors/4218c763e960eb2f. Report an issue: GitHub.