springboot通过ip获取ip属地信息的api
时间: 2023-12-31 14:19:48 浏览: 137
Spring Boot本身并没有提供获取IP地址属地信息的API,需要借助第三方库实现。
可以使用IP2Region进行IP地址归属地查询,具体使用方法如下:
1.引入IP2Region依赖:
```xml
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>1.7.2</version>
</dependency>
```
2.创建IP2Region查询类:
```java
import org.lionsoul.ip2region.*;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class Ip2RegionUtil {
private static final String DB_FILE_PATH = "ip2region.db";
public String getCityInfo(String ip) {
try {
DbConfig config = new DbConfig();
String dbPath = getClass().getResource("/").getPath() + DB_FILE_PATH;
DbSearcher searcher = new DbSearcher(config, dbPath);
DataBlock dataBlock = searcher.memorySearch(ip);
String region = dataBlock.getRegion();
String[] regionArr = region.split("\\|");
return regionArr[2] + " " + regionArr[3] + " " + regionArr[4];
} catch (DbMakerConfigException | IOException e) {
e.printStackTrace();
}
return "未知";
}
}
```
3.调用IP2Region查询方法:
```java
@Autowired
private Ip2RegionUtil ip2RegionUtil;
@GetMapping("/ip-info")
public String getIpInfo(HttpServletRequest request) {
String ip = request.getRemoteAddr();
String cityInfo = ip2RegionUtil.getCityInfo(ip);
return cityInfo;
}
```
其中,Ip2RegionUtil类中的getCityInfo方法用于查询IP地址对应的城市信息,DB_FILE_PATH为IP2Region数据库文件路径,需要将该文件放入resources目录下。
在Controller中调用getIpInfo方法,即可获取当前请求的IP地址对应的城市信息。
需要注意的是,由于IP2Region查询操作较为耗时,建议将查询结果缓存起来,避免频繁查询导致系统性能下降。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![jar](https://img-home.csdnimg.cn/images/20210720083455.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![java](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)