学习ip2region

Springboot在使用ip2region的时候一直在报

java.io.FileNotFoundException: ip2region.xdb file path (系统找不到指定的文件。)

找了半天找到了这个(spring boot 整合 ip2region(ip地址库)
直接解决了

// 官网的例子
//searcher = Searcher.newWithFileOnly(dbPath);   
// 解决方法
File file = ResourceUtils.getFile("classpath:" + "ip2region.xdb");  
searcher = Searcher.newWithFileOnly(file.getAbsolutePath());

完整代码

public static void main(String[] args) {
        // 1、创建 searcher 对象
        String dbPath = "ip2region.xdb file path";
        Searcher searcher = null;

        try {
            //searcher = Searcher.newWithFileOnly(dbPath);
            File file = ResourceUtils.getFile("classpath:" + "ip2region.xdb");
            searcher = Searcher.newWithFileOnly(file.getAbsolutePath());
        } catch (Exception e) {
            System.out.printf("failed to create searcher with `%s`: %s\n", dbPath, e);
            return;
        }

        String ip = "127.0.0.1";
        // 2、查询
        try {
            long sTime = System.nanoTime();
            String region = searcher.search(ip);
            long cost = TimeUnit.NANOSECONDS.toMicros((long) (System.nanoTime() - sTime));
            System.out.printf("{region: %s, ioCount: %d, took: %d μs}\n", region, searcher.getIOCount(), cost);
        } catch (Exception e) {
            System.out.printf("failed to search(%s): %s\n", ip, e);
        }

        // 3、关闭资源
        try {
            searcher.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 备注:并发使用,每个线程需要创建一个独立的 searcher 对象单独使用。
    }

xdb文件官网所在路径
xdb路径
xdb文件本地所在路径
在这里插入图片描述
maven

		<!-- ip地址库	-->
		<dependency>
			<groupId>org.lionsoul</groupId>
			<artifactId>ip2region</artifactId>
			<version>2.6.4</version>
		</dependency>

官网地址https://github.com/lionsoul2014/ip2region/tree/master/binding/java

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值