崛起於Springboot2.X + ip2region(31)

《SpringBoot2.X心法總綱》java

    ip2region:能夠根據他獲取一個具體ip的信息,國家、具體地址、網絡服務商git

一、添加依賴

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

二、工具類

import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;

import java.io.File;
import java.lang.reflect.Method;

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;
    }
}

三、下載文件ip2region.db到resources文件夾下

    $ git clone https://gitee.com/lionsoul/ip2region.git算法

    下載這個項目以後到data/文件夾下面找到ip2region.db複製到項目resources下網絡

 四、寫controller測試

@Controller
public class IpController {


    @GetMapping(value = "/testIp")
    @ResponseBody
    public void testIp(){
        String ip = "220.248.12.158";
        String result = IPUtil.getCityInfo(ip);


        System.out.println(result);
    }
}

五、結果如圖

相關文章
相關標籤/搜索