崛起于Springboot2.X之集成ip2region(31)

ip2region:可以根据他获取一个具体ip的信息,国家、具体地址、网络服务商

1、添加依赖
<dependency>
    <groupId>org.lionsoul</groupId>
    <artifactId>ip2region</artifactId>
    <version>1.7</version>
</dependency>
2、工具类
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;
    }
}
3、下载文件ip2region.db到resources文件夹下

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

    下载这个项目之后到data/文件夹下面找到ip2region.db复制到项目resources下

891fb8968b63be84f24745a6b2aecfc073a.jpg

 4、写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);
    }
}
5、结果如图

0a9d0f306fda04e68c2a250b0653e8afa81.jpg

转载于:https://my.oschina.net/mdxlcj/blog/1922106

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值