1. 程式人生 > >強大的IP地址定位庫--ip2region 的初步使用

強大的IP地址定位庫--ip2region 的初步使用

after 1.7 invalid ons valid println static res sip

2019年05月05日 開源的IP 地址定位庫 ip2region 1.9.0 發布了,功能還是很不錯的,下面我就應用下ip2region,來解析ip的地址

一、下載ip庫並解壓
地址為:https://github.com/lionsoul2014/ip2region/archive/v1.9.0-release.tar.gz
解壓
技術分享圖片

把ip2region.db粘貼到我們maven工程的resources下
技術分享圖片

二、添加ip2region依賴

<dependency>
            <groupId>org.lionsoul</groupId>
            <artifactId>ip2region</artifactId>
            <version>1.7.2</version>
</dependency>

三、實現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依賴

<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
</dependency>

編寫測試類

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 的初步使用