美文网首页
springboot免费的IP定位服务

springboot免费的IP定位服务

作者: neko_11 | 来源:发表于2020-01-16 20:57 被阅读0次

    简介

    ip2region 是准确率99.9%的ip地址定位库,0.0x毫秒级查询,数据库文件大小只有1.5M,提供了java,php,c,python,nodejs,golang,c#查询绑定和Binary,B树,内存三种查询算法!

    maven依赖

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

    DB文件下载地址:
    https://github.com/lionsoul2014/ip2region/archive/v1.9.0-release.tar.gz

    下载这个项目之后到data/文件夹下面找到ip2region.db,我放在了/user/home目录下

    Java 工具类

    public class IpUtil {
    
        public static String getCityInfo(String ip, int type) {
            //db
            String dbPath = "/usr/home/ip2region.db";
            File file = new File(dbPath);
            if (!file.exists()) {
                return "Error: Invalid ip2region.db file";
            }
            // 查询算法
            // DbSearcher.BTREE_ALGORITHM B-tree
            // DbSearcher.BINARY_ALGORITHM Binary
            // DbSearcher.MEMORY_ALGORITYM Memory
            // int algorithm = DbSearcher.BINARY_ALGORITHM;
            try {
                DbConfig config = new DbConfig();
                DbSearcher searcher = new DbSearcher(config, dbPath);
                //define the method
                Method method = null;
                switch (type) {
                    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;
                    default:
                        break;
                }
                DataBlock dataBlock;
                if (!Util.isIpAddress(ip)) {
                    return "Error: Invalid ip address";
                }
                dataBlock = (DataBlock) method.invoke(searcher, ip);
                return dataBlock.getRegion();
            } catch (Exception e) {
                e.printStackTrace();
                return "exception";
            }
        }
    }
    

    写个接口用于测试

        @ApiOperation(value = "IP定位")
        @GetMapping("/test")
        public ResponseEntity<String> test(String ip, int type) {
            return ResponseEntity.ok(IpUtil.getCityInfo(ip, type));
        }
    

    请求接口,定位成功:


    image.png

    相关文章

      网友评论

          本文标题:springboot免费的IP定位服务

          本文链接:https://www.haomeiwen.com/subject/qqdqzctx.html