java 使用ip2region获取IP位置信息

ip2region

根据它获取一个具体ip的信息,通过IP解析出国家、具体地址、网络服务商等相关信息。

在开发中,我们需要记录登陆的日志信息,关于登陆者的ip和位置信息,可以通过ip2region来实现。

Spring boot 集成使用

  • 首先引入需要的相关jar包,建议使用Maven构建项目,引入如下坐标:
<properties>
        <ip2region.version>1.7.2</ip2region.version>
</properties>


<dependency>
      <groupId>org.lionsoul</groupId>
      <artifactId>ip2region</artifactId>
       <version>${ip2region.version}</version>
</dependency>
  • 然后下载ip2region.db
download
来源:默认下载

下载之后找到ip2region.db复制到项目resources下

  • 编写ip2region 工具类。主要基于IP获取当前位置信息。
package cn.imyjs.utils;



import org.apache.commons.io.IOUtils;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;

/**
 * @Classname AddressUtil
 * @Description TODO
 * @Date 2022/4/21 22:01
 * @Created by YJS
 * @WebSite www.imyjs.cn
 */
public class AddressUtil {

    private static Logger log = LoggerFactory.getLogger(AddressUtil.class);

    @SuppressWarnings("all")
    public static String getCityInfo(String ip) {
        //db
        String dbPath = AddressUtil.class.getResource("/ip2region/ip2region.db").getPath();
        File file = new File(dbPath);

        if (!file.exists()) {
            log.info("地址库文件不存在,进行其他处理");
            String tmpDir = System.getProperties().getProperty("java.io.tmpdir");
            dbPath = tmpDir + File.separator + "ip2region.db";
            log.info("临时文件路径:{}", dbPath);
            file = new File(dbPath);
            if (!file.exists() || (System.currentTimeMillis() - file.lastModified() > 86400000L)) {
                log.info("文件不存在或者文件存在时间超过1天进入...");
                try {
                    InputStream inputStream = new ClassPathResource("ip2region/ip2region.db").getInputStream();
                    IOUtils.copy(inputStream, new FileOutputStream(file));
                } catch (IOException exception) {
                    exception.printStackTrace();
                }
            }
        }

        //查询算法
        int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree
        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) {
                log.error("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) {
        System.out.println(getCityInfo("127.0.0.1"));
    }
}

 

 

IOUtils

在以上代码中使用到了IOUtils工具类

所以需要在pom文件中导入如下坐标:

<dependency>
       <groupId>commons-io</groupId>
       <artifactId>commons-io</artifactId>
       <version>2.6</version>
</dependency>

 

 

IOUtils与其他Apache Commons中的类一样,都是处理IO操作的非常重要包装器,与手动编写这些功能的其他程序相比,它们实现这些方法的代码变得更小,更清晰,更易理解。

有关其使用参考:IOUtils使用介绍_码路编的博客-CSDN博客_ioutils

 

微信关注

编程那点事儿

阅读剩余
THE END