feat: 包结构调整,整合ip2region解析ip的所在区域

This commit is contained in:
Ray.Hao
2024-06-27 14:47:50 +08:00
parent a0530dc380
commit d13adf233d
32 changed files with 90 additions and 42 deletions

View File

@@ -3,12 +3,20 @@ package com.youlai.system.common.util;
import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* IP工具类
* IP工具类
* <p>
* 获取客户端IP地址和IP地址对应的地理位置信息
* <p>
* 使用Nginx等反向代理软件 则不能通过request.getRemoteAddr()获取IP地址
* 如果使用了多级反向代理的话X-Forwarded-For的值并不止一个而是一串IP地址X-Forwarded-For中第一个非unknown的有效IP字符串则为真实IP地址
* </p>
*
* @author Ray
* @since 2.10.0
@@ -16,10 +24,13 @@ import java.net.UnknownHostException;
@Slf4j
public class IPUtils {
private static final String DB_PATH = "src/main/resources/data/ip2region.xdb";
/**
* 获取IP地址
* 使用Nginx等反向代理软件 则不能通过request.getRemoteAddr()获取IP地址
* 如果使用了多级反向代理的话X-Forwarded-For的值并不止一个而是一串IP地址X-Forwarded-For中第一个非unknown的有效IP字符串则为真实IP地址
*
* @param request HttpServletRequest对象
* @return 客户端IP地址
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = null;
@@ -51,7 +62,7 @@ public class IPUtils {
log.error("IPUtils ERROR, {}", e.getMessage());
}
//使用代理则获取第一个IP地址
// 使用代理则获取第一个IP地址
if (StrUtil.isNotBlank(ip) && ip.indexOf(",") > 0) {
ip = ip.substring(0, ip.indexOf(","));
}
@@ -59,14 +70,15 @@ public class IPUtils {
return ip;
}
private static boolean checkIp(String ip) {
String unknown = "unknown";
return StrUtil.isEmpty(ip) || ip.isEmpty() || unknown.equalsIgnoreCase(ip);
return StrUtil.isEmpty(ip) || unknown.equalsIgnoreCase(ip);
}
/**
* 获取本机的IP地址
*
* @return 本机IP地址
*/
private static String getLocalAddr() {
try {
@@ -77,5 +89,28 @@ public class IPUtils {
return null;
}
/**
* 根据IP地址获取地理位置信息
*
* @param ip IP地址
* @return 地理位置信息
*/
public static String getRegion(String ip) {
Searcher searcher = null;
try {
searcher = Searcher.newWithFileOnly(DB_PATH);
return searcher.search(ip);
} catch (Exception e) {
log.error("IpRegionUtil ERROR, {}", e.getMessage());
return null;
} finally {
if (searcher != null) {
try {
searcher.close();
} catch (IOException e) {
log.error("IpRegionUtil close ERROR, {}", e.getMessage());
}
}
}
}
}