使用ip2region来完成城市定位(java)

一、背景

1.因为最近有个需求需要城市定位这个功能,然后就去搜了下有关城市定位的资料,有纯真的,有阿里开源的,经过考虑还是使用了ip2region自己写了一个版本,这个大家可以放心使用,这个是开源的,下面分享给大家,以及在使用的过程中所遇到的问题。

二、项目结构

1.使用的springboot与ip2region整合的方式,ip2region.db文件放在resources下面的city文件夹下面了,然后写一个主线程进行测试,下面就开始具体上代码。

三、pom.xml

1.pom.xml

<dependency>
   <groupId>org.lionsoul</groupId>
   <artifactId>ip2region</artifactId>
   <version>1.7</version>
</dependency>

四、工具类

1.代码(IpUtils)

public class IpUtils {
    public static String getCityInfo(String ip) {

        //db
        String dbPath = IpUtils.class.getResource("/city/ip2region.db").getPath();

        File file = new File(dbPath);
        if (file.exists() == false) {
            System.out.println("Error: Invalid ip2region.db file");
        }

        //查询算法
        int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree
        //DbSearcher.BINARY_ALGORITHM //Binary
        //DbSearcher.MEMORY_ALGORITYM //Memory
        try {
            DbConfig config = new DbConfig();
            DbSearcher searcher = new DbSearcher(config, dbPath);

            //define the method
            Method method = null;
            switch (algorithm) {
                case DbSearcher.BTREE_ALGORITHM:
                    method = searcher.getClass().getMethod("btreeSearch", String.class);
                    break;
                case DbSearcher.BINARY_ALGORITHM:
                    method = searcher.getClass().getMethod("binarySearch", String.class);
                    break;
                case DbSearcher.MEMORY_ALGORITYM:
                    method = searcher.getClass().getMethod("memorySearch", String.class);
                    break;
            }

            DataBlock dataBlock = null;
            if (Util.isIpAddress(ip) == false) {
                System.out.println("Error: Invalid ip address");
            }

            dataBlock = (DataBlock) method.invoke(searcher, ip);

            return dataBlock.getRegion();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static void main(String[] args) throws Exception {
        String ip="220.248.12.158";
        String cityIpString = getCityInfo(ip);
        System.out.println(cityIpString);
        String[] splitIpString = cityIpString.split("\\|");
        cityIpString =splitIpString[3].replaceAll("市","");
        System.err.println(cityIpString);
    }
}

五、测试结果

1.结果

中国|0|上海|上海市|联通
上海

 2.注释:结果中的第一行,数据格式都是一样的,就是说数据比较规范,第二行就是我们想要的结果了。

六、遇到的问题

1.上面的是在本地测试的,是没啥问题的,但是我们的项目上到服务器上面就会出现问题,获取不到我们的资源文件,针对这个问题,我的做法就是把我们的资源放在jar包的外面进行读取的。

发布了122 篇原创文章 · 获赞 64 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/chenmingxu438521/article/details/103727449