GeoLite2 提供了两种方式根据 IP 获取地理位置:
:point_down:以本地数据库方式演示,请注意数据库 License: CC BY-SA 4.0 。
编辑 pom.xml 文件,添加依赖:
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>2.12.0</version>
</dependency>
本地数据库 下载地址 ,解压缩到工程的 Resources 目录。
try (InputStream in = getClass().getClassLoader().getResourceAsStream("GeoLite2-City/GeoLite2-City.mmdb")) {
DatabaseReader reader = new DatabaseReader
.Builder(in)
.withCache(new CHMCache())
.build(); // ①
InetAddress ip = InetAddress.getByName("8.8.8.8");
CityResponse city = this.geoIPReader.city(ip); // ②
city.getCity().getNames().get("zh-CN"); // ③
city.getCity().getNames().get("en");
}
① 读取本地数据库;
② 根据 IP 地址获取城市信息;
③ 获取简体中文(zh-CN)和英文城市名称。