springboot免费的IP定位服务

简介

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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、简历准备 1、个人技能 (1)自定义控件、UI设计、常用动画特效 自定义控件 ①为什么要自定义控件? Andr...
    lucas777阅读 5,266评论 2 54
  • 摘要 毕达哥拉斯发现,拨琴弦所发出的声音与琴弦的长度有关,音高与弦长成反比,建立了“五度相生律”。巴赫的作品既具有...
    言千悟阅读 21,384评论 2 3
  • 底层知识分子是政治、思想倾向最为飘忽的群体。虽然能有机会获得晋升阶层的渠道,但奈何他们人太多,拥堵在一起,把渠道都...
    秋慕苏阅读 417评论 0 0
  • 文 | 鲸鱼 最近,有一部新剧《第二次也很美》开播,你们都看了吗? 单身带娃的律师爸爸许朗,遇到了一毕业就结婚、自...
    她刊V阅读 431评论 1 4