2
2
3
3
import lombok .extern .slf4j .Slf4j ;
4
4
import org .apache .commons .lang3 .StringUtils ;
5
- import org .lionsoul .ip2region .DataBlock ;
6
- import org .lionsoul .ip2region .DbConfig ;
7
- import org .lionsoul .ip2region .DbSearcher ;
8
- import org .lionsoul .ip2region .Util ;
5
+ import org .lionsoul .ip2region .xdb .Searcher ;
9
6
import org .springframework .core .io .ClassPathResource ;
10
7
import org .springframework .stereotype .Component ;
11
8
import org .springframework .util .FileCopyUtils ;
@@ -64,7 +61,7 @@ public static String getIpAddress(HttpServletRequest request) {
64
61
return StringUtils .substringBefore (ip , "," );
65
62
}
66
63
67
- private static DbSearcher searcher ;
64
+ private static Searcher searcher ;
68
65
private static Method method ;
69
66
70
67
/**
@@ -75,13 +72,13 @@ public static String getIpAddress(HttpServletRequest request) {
75
72
*/
76
73
@ PostConstruct
77
74
private void initIp2regionResource () throws Exception {
78
- InputStream inputStream = new ClassPathResource ("/ipdb/ip2region.db " ).getInputStream ();
75
+ InputStream inputStream = new ClassPathResource ("/ipdb/ip2region.xdb " ).getInputStream ();
79
76
//将 ip2region.db 转为 ByteArray
80
77
byte [] dbBinStr = FileCopyUtils .copyToByteArray (inputStream );
81
- DbConfig dbConfig = new DbConfig ();
82
- searcher = new DbSearcher ( dbConfig , dbBinStr );
78
+ // 2、使用上述的 dbBinStr 创建一个完全基于内存的查询对象。
79
+ searcher = new Searcher ( null , null , dbBinStr );
83
80
//二进制方式初始化 DBSearcher,需要使用基于内存的查找算法 memorySearch
84
- method = searcher .getClass ().getMethod ("memorySearch " , String .class );
81
+ method = searcher .getClass ().getMethod ("search " , String .class );
85
82
}
86
83
87
84
/**
@@ -91,21 +88,22 @@ private void initIp2regionResource() throws Exception {
91
88
* @return
92
89
*/
93
90
public static String getCityInfo (String ip ) {
94
- if (ip == null || !Util .isIpAddress (ip )) {
95
- log .error ("Error: Invalid ip address" );
96
- return "" ;
97
- }
98
91
try {
99
- DataBlock dataBlock = (DataBlock ) method .invoke (searcher , ip );
100
- String ipInfo = dataBlock .getRegion ();
92
+ String ipInfo = (String ) method .invoke (searcher , ip );
101
93
if (!StringUtils .isEmpty (ipInfo )) {
102
94
ipInfo = ipInfo .replace ("|0" , "" );
103
95
ipInfo = ipInfo .replace ("0|" , "" );
104
- return ipInfo ;
105
96
}
97
+ return ipInfo ;
106
98
} catch (Exception e ) {
107
99
log .error ("getCityInfo exception:" , e );
108
100
}
109
101
return "" ;
110
102
}
103
+ public static void main (String [] args ) throws Exception {
104
+ IpAddressUtils ipAddressUtils = new IpAddressUtils ();
105
+ ipAddressUtils .initIp2regionResource ();
106
+ String cityInfo = IpAddressUtils .getCityInfo ("14.215.177.39" );
107
+ System .out .println (cityInfo );
108
+ }
111
109
}
0 commit comments