强大的IP地址定位库--ip2region的初步使用
                                            2019年05月05日 开源的IP 地址定位库 ip2region 1.9.0 发布了,功能还是很不错的,下面我就应用下ip2region,来解析ip的地址
成都创新互联是一家专业提供吉安企业网站建设,专注与网站设计、网站建设、H5高端网站建设、小程序制作等业务。10年已为吉安众多企业、政府机构等服务。创新互联专业的建站公司优惠进行中。
一、下载ip库并解压
地址为:https://github.com/lionsoul2014/ip2region/archive/v1.9.0-release.tar.gz
解压
把ip2region.db粘贴到我们maven工程的resources下
二、添加ip2region依赖
            org.lionsoul 
            ip2region 
            1.7.2 
 三、实现IPUtil工具类
import java.io.File;
import java.lang.reflect.Method;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;
public class IPUtil {
    public static String getCityInfo(String ip){
    //db
    String dbPath = IPUtil.class.getResource("/ip2region.db").getPath();
    File file = new File(dbPath);
        if ( file.exists() == false ) {
        System.out.println("Error: Invalid ip2region.db file");
    }
    //查询算法
    int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree
    //DbSearcher.BINARY_ALGORITHM //Binary
    //DbSearcher.MEMORY_ALGORITYM //Memory
        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 ) {
            System.out.println("Error: Invalid ip address");
        }
        dataBlock  = (DataBlock) method.invoke(searcher, ip);
        return dataBlock.getRegion();
    } catch (Exception e) {
        e.printStackTrace();
    }
        return null;
}
}四、测试
这里我是用的Junit进行单元测试,你也可以自己写个main方法测试即可
添加junit依赖
            junit 
            junit 
            4.12 
 编写测试类
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class IPUtilTest {
    private IPUtil ipUtil;
    @Before
    public void setUp(){
        ipUtil=new IPUtil();
    }
    @After
    public void tearDown(){
        ipUtil=null;
    }
    @Test
    public void getCityInfo(){
        String ip = "220.248.12.158";
        System.out.println(ipUtil.getCityInfo(ip));
    }
}
总结:很方便,其实我觉得比纯真的要好多了~
本文题目:强大的IP地址定位库--ip2region的初步使用
文章分享:http://www.cqwzjz.cn/article/gggjid.html

 建站
建站
 咨询
咨询 售后
售后
 建站咨询
建站咨询 
 