- ip2region
准确率99.9%的ip地址定位库,0.0x毫秒级查询,数据库文件大小只有1.5M,提供了java,php,c,python,nodejs,golang查询绑定和Binary,B树,内存三种查询算法
github地址:https://github.com/lionsoul2014/ip2region
解压目录如下图:
- 新建java项目,导入binding/java下的代码,并复制”data/ip2region.db”到“src目录
创建“IPUtil”.java ,内容参考”org.lionsoul.ip2region.test.TestSearcher.java“
1 package com.xx; 2 3 import java.io.File; 4 import java.lang.reflect.Method; 5 6 import org.lionsoul.ip2region.DataBlock; 7 import org.lionsoul.ip2region.DbConfig; 8 import org.lionsoul.ip2region.DbSearcher; 9 import org.lionsoul.ip2region.Util; 10 11 public class IPUtil { 12 13 public static String getCityInfo(String ip){ 14 15 //db 16 String dbPath = IPUtil.class.getResource("/ip2region.db").getPath(); 17 18 File file = new File(dbPath); 19 if ( file.exists() == false ) { 20 System.out.println("Error: Invalid ip2region.db file"); 21 } 22 23 //查询算法 24 int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree 25 //DbSearcher.BINARY_ALGORITHM //Binary 26 //DbSearcher.MEMORY_ALGORITYM //Memory 27 try { 28 DbConfig config = new DbConfig(); 29 DbSearcher searcher = new DbSearcher(config, dbPath); 30 31 //define the method 32 Method method = null; 33 switch ( algorithm ) 34 { 35 case DbSearcher.BTREE_ALGORITHM: 36 method = searcher.getClass().getMethod("btreeSearch", String.class); 37 break; 38 case DbSearcher.BINARY_ALGORITHM: 39 method = searcher.getClass().getMethod("binarySearch", String.class); 40 break; 41 case DbSearcher.MEMORY_ALGORITYM: 42 method = searcher.getClass().getMethod("memorySearch", String.class); 43 break; 44 } 45 46 DataBlock dataBlock = null; 47 if ( Util.isIpAddress(ip) == false ) { 48 System.out.println("Error: Invalid ip address"); 49 } 50 51 dataBlock = (DataBlock) method.invoke(searcher, ip); 52 53 return dataBlock.getRegion(); 54 55 } catch (Exception e) { 56 e.printStackTrace(); 57 } 58 59 return null; 60 } 61 62 63 public static void main(String[] args) throws Exception{ 64 System.err.println(getCityInfo("220.248.12.158")); 65 } 66 }
转自:https://www.cnblogs.com/face-ghost-coder/p/8867855.html