springboot免费的IP定位服务

2020-01-16  本文已影响0人  neko_11

简介

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
上一篇下一篇

猜你喜欢

热点阅读