SpringBoot輕松實(shí)現(xiàn)ip解析(含源碼)
應(yīng)用場(chǎng)景

(1)網(wǎng)站訪問分析
可以解析用戶IP地址,分析網(wǎng)站訪問量的地域分布,以便進(jìn)行針對(duì)性推廣。
(2)欺詐風(fēng)險(xiǎn)控制
某地區(qū)IP地址多次進(jìn)行惡意刷單、刷票等行為,可以通過IP地址解析加以攔截。
(3)限制服務(wù)區(qū)域
解析用戶IP地址,限制僅為某地區(qū)的用戶提供服務(wù)。
(4)顯示訪問者來源
在博客、論壇等,解析并顯示每個(gè)帖子的發(fā)帖人來自哪個(gè)地區(qū)。
下面帶大家實(shí)踐在spring boot 項(xiàng)目中獲取請(qǐng)求的ip與詳細(xì)地址。
示例
前期準(zhǔn)備
引用框架:Ip2region
下載地址: https://gitee.com/lionsoul/ip2region.git
注意:如果需要離線獲取需要下載 /data/ip2region.xdb 文件
Ip2region 特性
1、IP 數(shù)據(jù)管理框架
xdb 支持億級(jí)別的 IP 數(shù)據(jù)段行數(shù),默認(rèn)的 region 信息都固定了格式:國家|區(qū)域|省份|城市|ISP,缺省的地域信息默認(rèn)是0。 region 信息支持完全自定義,例如:你可以在 region 中追加特定業(yè)務(wù)需求的數(shù)據(jù),例如:GPS信息/國際統(tǒng)一地域信息編碼/郵編等。也就是你完全可以使用 ip2region 來管理你自己的 IP 定位數(shù)據(jù)。
2、數(shù)據(jù)去重和壓縮
xdb 格式生成程序會(huì)自動(dòng)去重和壓縮部分?jǐn)?shù)據(jù),默認(rèn)的全部 IP 數(shù)據(jù),生成的 ip2region.xdb 數(shù)據(jù)庫是 11MiB,隨著數(shù)據(jù)的詳細(xì)度增加數(shù)據(jù)庫的大小也慢慢增大。
3、極速查詢響應(yīng)
即使是完全基于 xdb 文件的查詢,單次查詢響應(yīng)時(shí)間在十微秒級(jí)別,可通過如下兩種方式開啟內(nèi)存加速查詢:
vIndex索引緩存 :使用固定的512KiB的內(nèi)存空間緩存 vector index 數(shù)據(jù),減少一次 IO 磁盤操作,保持平均查詢效率穩(wěn)定在10-20微秒之間。xdb整個(gè)文件緩存:將整個(gè)xdb文件全部加載到內(nèi)存,內(nèi)存占用等同于xdb文件大小,無磁盤 IO 操作,保持微秒級(jí)別的查詢效率。
版本依賴
| 框架名 | 版本號(hào) |
|---|---|
| SpringBoot | 3.1.4 |
| jdk | 17 |
| tomcat-embed-core | 10.1.8 |
| lombok | 1.18.26 |
| fastjson | 1.2.73 |
| ip2region | 2.7.0 |
導(dǎo)入庫
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--ip庫-->
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>10.1.8</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.26</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
具體代碼
Constant
public interface Constant {
// IP地址查詢
public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";
/**
* 本地ip
*/
public static final String LOCAL_IP = "127.0.0.1";
/**
* 數(shù)據(jù)庫訪問地址
*/
public static final String DB_PATH = "springboot-ip/src/main/resources/ip2region/ip2region.xdb";
}
AddressUtils(在線解析)
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import static com.example.springbootip.constant.Constant.IP_URL;
import static com.example.springbootip.constant.Constant.LOCAL_IP;
/**
* @author coderJim
* @date 2023-10-16 14:07
*/
@Slf4j
public class AddressUtils {
// 未知地址
public static final String UNKNOWN = "XX XX";
public static String getRealAddressByIP(String ip) {
String address = UNKNOWN;
// 內(nèi)網(wǎng)不查詢
if (ip.equals(LOCAL_IP)) {
return "內(nèi)網(wǎng)IP";
}
if (true) {
try {
String rspStr = sendGet(IP_URL, "ip=" + ip + "&json=true" ,"GBK");
if (StringUtils.isEmpty(rspStr)) {
log.error("獲取地理位置異常 {}" , ip);
return UNKNOWN;
}
JSONObject obj = JSONObject.parseObject(rspStr);
String region = obj.getString("pro");
String city = obj.getString("city");
return String.format("%s %s" , region, city);
} catch (Exception e) {
log.error("獲取地理位置異常 {}" , ip);
}
}
return address;
}
public static String sendGet(String url, String param, String contentType) {
StringBuilder result = new StringBuilder();
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
log.info("sendGet - {}" , urlNameString);
URL realUrl = new URL(urlNameString);
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("accept" , "*/*");
connection.setRequestProperty("connection" , "Keep-Alive");
connection.setRequestProperty("user-agent" , "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.connect();
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
log.info("recv - {}" , result);
} catch (ConnectException e) {
log.error("調(diào)用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
} catch (SocketTimeoutException e) {
log.error("調(diào)用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
} catch (IOException e) {
log.error("調(diào)用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
} catch (Exception e) {
log.error("調(diào)用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception ex) {
log.error("調(diào)用in.close Exception, url=" + url + ",param=" + param, ex);
}
}
return result.toString();
}
}
IpUtil(離線解析)
import static com.example.springbootip.constant.Constant.DB_PATH;
import static com.example.springbootip.constant.Constant.LOCAL_IP;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* @author coderJim
* @date 2023-10-16 11:02
*/
@Slf4j
public class IpUtil {
protected IpUtil(){ }
/**
* 獲取 IP地址
* 使用 Nginx等反向代理軟件, 則不能通過 request.getRemoteAddr()獲取 IP地址
* 如果使用了多級(jí)反向代理的話,X-Forwarded-For的值并不止一個(gè),而是一串IP地址,
* X-Forwarded-For中第一個(gè)非 unknown的有效IP字符串,則為真實(shí)IP地址
*/
public static String getIpAddr(HttpServletRequest request) {
String ipAddress;
try {
ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if (ipAddress.equals(LOCAL_IP)) {
// 根據(jù)網(wǎng)卡取本機(jī)配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
log.error(e.getMessage(), e);
}
ipAddress = inet.getHostAddress();
}
}
// 對(duì)于通過多個(gè)代理的情況,第一個(gè)IP為客戶端真實(shí)IP,多個(gè)IP按照','分割
if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
// = 15
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
} catch (Exception e) {
ipAddress = "";
}
return ipAddress;
}
public static String getAddr(String ip) {
String project_dir = System.getProperty("user.dir") +"";
String dbPath = project_dir + "/" + DB_PATH;
// 1、從 dbPath 加載整個(gè) xdb 到內(nèi)存。
byte[] cBuff;
try {
cBuff = Searcher.loadContentFromFile(dbPath);
} catch (Exception e) {
log.info("failed to load content from `%s`: %s\n", dbPath, e);
return null;
}
// 2、使用上述的 cBuff 創(chuàng)建一個(gè)完全基于內(nèi)存的查詢對(duì)象。
Searcher searcher;
try {
searcher = Searcher.newWithBuffer(cBuff);
} catch (Exception e) {
log.info("failed to create content cached searcher: %s\n", e);
return null;
}
// 3、查詢
try {
String region = searcher.search(ip);
return region;
} catch (Exception e) {
log.info("failed to search(%s): %s\n", ip, e);
}
return null;
}
}
IpController
import com.example.springbootip.util.AddressUtils;
import com.example.springbootip.util.IpUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
/**
* @author coderJim
*/
@RestController
@RequestMapping("/demo")
public class IpController {
@ResponseBody
@GetMapping("/realAddress")
public String realAddress(HttpServletRequest request){
String ip = IpUtil.getIpAddr(request);
//在線獲取
// String realAddress = AddressUtils.getRealAddressByIP(ip);
//離線獲取
String realAddress = IpUtil.getAddr(ip);
return "您的ip所在地為:"+ realAddress;
}
}
執(zhí)行結(jié)果
運(yùn)行請(qǐng)求 http://127.0.0.1:8080/demo/realAddress
如果執(zhí)行:
String realAddress = AddressUtils.getRealAddressByIP(ip);
顯示結(jié)果:
您的ip所在地為:浙江省 杭州市
如果執(zhí)行:
String realAddress = IpUtil.getAddr(ip);
顯示結(jié)果:
您的ip所在地為:中國|0|浙江省|杭州市|電信
總結(jié)
通過這樣的一套流程下來,我們就能實(shí)現(xiàn)對(duì)每一個(gè)請(qǐng)求進(jìn)行ip 獲取、ip解析
以上就是SpringBoot輕松實(shí)現(xiàn)ip解析(含源碼)的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot實(shí)現(xiàn)ip解析的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Spring boot actuator端點(diǎn)啟用和暴露操作
這篇文章主要介紹了Spring boot actuator端點(diǎn)啟用和暴露操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
SpringBoot 集成 Jasypt 對(duì)數(shù)據(jù)庫加密以及踩坑的記錄分享
這篇文章主要介紹了SpringBoot 集成 Jasypt 對(duì)數(shù)據(jù)庫加密以及踩坑,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08
Java數(shù)據(jù)結(jié)構(gòu)之圖的路徑查找算法詳解
這篇文章主要為大家詳細(xì)介紹了java數(shù)據(jù)結(jié)構(gòu)中圖的路徑查找算法,文中的示例代碼講解詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-11-11
解析Tomcat 6、7在EL表達(dá)式解析時(shí)存在的一個(gè)Bug
這篇文章主要是對(duì)Tomcat 6、7在EL表達(dá)式解析時(shí)存在的一個(gè)Bug進(jìn)行了詳細(xì)的分析介紹,需要的朋友可以過來參考下,希望對(duì)大家有所幫助2013-12-12
Java使用JSONObject需要的6個(gè)jar包下載地址
這篇文章主要介紹了Java使用JSONObject需要的6個(gè)jar包下載地址,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11

