Explorar el Código

营销系统-解析ip2region xdb 返回常见格式

wangcl hace 6 días
padre
commit
f074f0842c

+ 27 - 8
pig-marketing/pig-marketing-biz/src/main/java/com/pig4cloud/pig/marketing/util/IPLocationUtil.java

@@ -123,15 +123,38 @@ public class IPLocationUtil {
                 return null;
             }
 
-            // ip2region xdb 返回格式通常为: 国家|区域|省|市|运营商
+            // ip2region xdb 返回常见格式:
+            // 1) 国家|区域|省|市|运营商 (5段)
+            // 2) 国家|省|市|运营商 (4段)
+            // 3) 国家|省|市 (3段)
             List<String> parts = cn.hutool.core.util.StrUtil.split(region, '|');
             if (parts == null || parts.isEmpty()) {
                 return null;
             }
 
-            String country = parts.size() >= 1 ? parts.get(0) : null;
-            String province = parts.size() >= 3 ? parts.get(2) : null;
-            String city = parts.size() >= 4 ? parts.get(3) : null;
+            String country = null;
+            String province = null;
+            String city = null;
+
+            int size = parts.size();
+            if (size >= 5) {
+                country = parts.get(0);
+                province = parts.get(2);
+                city = parts.get(3);
+            } else if (size == 4) {
+                country = parts.get(0);
+                province = parts.get(1);
+                city = parts.get(2);
+            } else if (size == 3) {
+                country = parts.get(0);
+                province = parts.get(1);
+                city = parts.get(2);
+            } else if (size == 2) {
+                country = parts.get(0);
+                province = parts.get(1);
+            } else if (size == 1) {
+                country = parts.get(0);
+            }
 
             // 标准化无效字段
             if ("0".equals(country) || cn.hutool.core.util.StrUtil.isBlank(country)) {
@@ -148,18 +171,14 @@ public class IPLocationUtil {
                 return null;
             }
 
-            // 仅返回地理层级,不包含运营商,不做重复拼接
             if (province == null) {
-                // 仅国家
                 return country;
             }
 
             if (city == null) {
-                // 国家-省
                 return country + "-" + province;
             }
 
-            // 国家-省-市
             return country + "-" + province + "-" + city;
         } catch (Exception e) {
             log.warn("查询IP[{}]归属地出错", ip, e);