强大的IP地址定位库--ip2region 的初步使用
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)); }}
总结:很方便,其实我觉得比纯真的要好多了~
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。