Springboot整合ip2region实现获取用户ip归属地

1、 Ip2region 是什么

ip2region - 是一个离线IP地址定位库和IP定位数据管理框架,10微秒级别的查询效率,提供了众多主流编程语言的 xdb 数据生成和查询客户端实现。

2、Ip2region 特性

2.1、IP 数据管理框架

xdb 支持亿级别的 IP 数据段行数,默认的 region 信息都固定了格式:国家|区域|省份|城市|ISP,缺省的地域信息默认是0。 region 信息支持完全自定义,例如:你可以在 region 中追加特定业务需求的数据,例如:GPS信息/国际统一地域信息编码/邮编等。也就是你完全可以使用 ip2region 来管理你自己的 IP 定位数据。

2.2、数据去重和压缩

xdb 格式生成程序会自动去重和压缩部分数据,默认的全部 IP 数据,生成的 ip2region.xdb 数据库是 11MiB,随着数据的详细度增加数据库的大小也慢慢增大。

2.3、极速查询响应

即使是完全基于 xdb 文件的查询,单次查询响应时间在十微秒级别,可通过如下两种方式开启内存加速查询:

  1. vIndex 索引缓存 :使用固定的 512KiB 的内存空间缓存 vector index 数据,减少一次 IO 磁盘操作,保持平均查询效率稳定在10-20微秒之间。
  2. xdb 整个文件缓存:将整个 xdb 文件全部加载到内存,内存占用等同于 xdb 文件大小,无磁盘 IO 操作,保持微秒级别的查询效率。

3、Ip2region的使用

步骤:
   1、生成ip2region.xdb文件,做好ip2region的相关配置
   2、从请求中获取用户的ip地址
   3、通过ip2redion.xdb中的对应关系找到用户的ip对应的地点(格式:`国家|区域|省份|城市|运营商`,缺省的地域信息默认是0)

3.1、生成ip2region.xdb文件

3.1.1、下载ip2region的master分支
3.1.2、编译安装

通过 maven 来编译可运行 jar 程序:

# cd 到 maker/java 根目录
mvn clean compile package

然会会在当前目录的 target 目录下得到一个 ip2region-maker-{version}.jar 的打包文件。

3.1.3数据生成

通过 java -jar ip2region-maker-{version}.jar 来生成 ip2region.xdb 二进制文件:

➜  java git:(java_xdb_maker) ✗ java -jar ./target/ip2region-maker-1.0.0.jar 
ip2region xdb maker
java -jar ip2region-maker-{version}.jar [command options]
options:
 --src string    source ip text file path
 --dst string    destination binary xdb file path

例如,通过默认的 data/ip.merge.txt 原数据,在当前目录生成一个 ip2region.xdb 二进制文件:

在控制台中输入:java -jar ./target/ip2region-maker-1.0.0.jar --src=../../data/ip.merge.txt --dst=./ip2region.xdb

3.2、导入Ip2region的依赖

 <!-- ip2region  -->
        <dependency>
            <groupId>org.lionsoul</groupId>
            <artifactId>ip2region</artifactId>
            <version>2.6.3</version>
        </dependency>

3.3、从请求中获取用户的ip

3.3.1、全局获取HttpServletRequest的工具类
/**
 * 全局获取HttpServletRequest、HttpServletResponse的工具类
 */
public class HttpContextUtil {

    private HttpContextUtil() {

    }

    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    public static HttpServletResponse getHttpServletResponse() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
    }
}
3.3.2 、从请求中获取IP的类
public class IPUtil {

    private static final String UNKNOWN = "unknown";

    protected IPUtil() {

    }

    /**
     * 获取 IP地址
     * 使用 Nginx等反向代理软件, 则不能通过 request.getRemoteAddr()获取 IP地址
     * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,
     * X-Forwarded-For中第一个非 unknown的有效IP字符串,则为真实IP地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

}

3.3.3通过ip从ip2region.xdb中获取用户归属地

共有三种方法:

  • 完全基于文件查询
  • 缓存VectorIndex索引
  • 缓存整个xdb文件
public class AddressUtil {

    public static String dbPath = "src/main/resources/ip2region/ip2region.xdb";

    public static String region = "UNKOWN";

    //方法一:完全基于文件的查询
    public static String getInfoByFie(String ip) throws IOException {
        // 1、创建 searcher 对象
        Searcher searcher = null;
        try {
            searcher = Searcher.newWithFileOnly(dbPath);
        } catch (IOException e) {
            System.out.printf("failed to create searcher with `%s`: %s\n", dbPath, e);
            return "";
        }

        // 2、查询
        try {
            //ip = "119.39.183.117";
            long sTime = System.nanoTime();
            region = searcher.searchByStr(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);
        }


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

    //方法二:缓存 VectorIndex 索引
    //我们可以提前从 xdb 文件中加载出来 VectorIndex 数据,然后全局缓存,
    // 每次创建 Searcher 对象的时候使用全局的 VectorIndex 缓存可以减少一次固定的 IO 操作,从而加速查询,减少 IO 压力。
    public static String getInfoByVectorIndex(String ip) throws IOException {

        // 1、从 dbPath 中预先加载 VectorIndex 缓存,并且把这个得到的数据作为全局变量,后续反复使用。
        byte[] vIndex;
        try {
            vIndex = Searcher.loadVectorIndexFromFile(dbPath);
        } catch (Exception e) {
            System.out.printf("failed to load vector index from `%s`: %s\n", dbPath, e);
            return "";
        }

        // 2、使用全局的 vIndex 创建带 VectorIndex 缓存的查询对象。
        Searcher searcher;
        try {
            searcher = Searcher.newWithVectorIndex(dbPath, vIndex);
        } catch (Exception e) {
            System.out.printf("failed to create vectorIndex cached searcher with `%s`: %s\n", dbPath, e);
            return "";
        }

        // 2、查询
        try {
            //ip = "119.39.183.117";
            long sTime = System.nanoTime();
            region = searcher.searchByStr(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);
        }

        return region;
        // 备注:每个线程需要单独创建一个独立的 Searcher 对象,但是都共享全局的制度 vIndex 缓存。
    }

    //方法三:缓存整个 xdb 数据
    //我们也可以预先加载整个 ip2region.xdb 的数据到内存,
    //然后基于这个数据创建查询对象来实现完全基于文件的查询,类似之前的 memory search。
    public static String getInfoByBuffer(String ip) throws IOException {

        // 1、从 dbPath 中预先加载 VectorIndex 缓存,并且把这个得到的数据作为全局变量,后续反复使用。
        byte[] vIndex;
        try {
            vIndex = Searcher.loadVectorIndexFromFile(dbPath);
        } catch (Exception e) {
            System.out.printf("failed to load vector index from `%s`: %s\n", dbPath, e);
            return "";
        }

        // 2、使用全局的 vIndex 创建带 VectorIndex 缓存的查询对象。
        Searcher searcher;
        try {
            searcher = Searcher.newWithVectorIndex(dbPath, vIndex);
        } catch (Exception e) {
            System.out.printf("failed to create vectorIndex cached searcher with `%s`: %s\n", dbPath, e);
            return "";
        }

        // 2、查询
        try {
            //ip = "119.39.183.117";
            long sTime = System.nanoTime();
            String region = searcher.searchByStr(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);
        }


        return region;
        // 备注:每个线程需要单独创建一个独立的 Searcher 对象,但是都共享全局的制度 vIndex 缓存。
    }

    public static void main(String[] args) throws IOException {
        //1、完全基于文件查询
        String info1 = AddressUtil.getInfoByFie("203.15.235.101");
        System.out.println(info1);
        //2、缓存VectorIndex索引
        String info2 = AddressUtil.getInfoByVectorIndex("203.15.235.101");
        System.out.println(info2);
        //3、缓存整个xdb文件
        String info3 = AddressUtil.getInfoByVectorIndex("203.15.235.101");
        System.out.println(info3);
    }
}

测试结果

在这里插入图片描述
源码链接:https://pan.baidu.com/s/1D4cobr4ssFbiX2yya0cbcg
提取码:yxht

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值