1.下载文件
官网地址:https://dev.maxmind.com/?lang=en
最下方从Products→GeoLite2 Free Geolocation Data 进入
进入之后,按照登陆→生成通行证→下载文件步骤
注册和生成通行证这里略过,点击Download Files
下载文件,
分别包含:ASN版本、Country版本、City版本,每个都包涵.mmdb
和.csv
格式
ASN.mmdb
用于查看IP地址的拥有者(7M左右)
ASN.csv
用于查看IP地址的拥有者(7M左右)
Country.mmdb
精确到国家(4M左右)
Country.csv
精确到国家(4M左右)
City.mmdb
精确到城市(大小70M左右)
City.csv
精确到城市(大小70M左右)
这里我选择City.mmdb
,下载
2.引入依赖
<dependency>
<groupId>com.maxmind.db</groupId>
<artifactId>maxmind-db</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>2.16.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.30</version>
</dependency>
3.引入工具类
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.AddressNotFoundException;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import com.tiens.lark.common.exception.BusinessException;
import org.apache.commons.lang.StringUtils;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.Map;
public class GeoIPReader {
private static DatabaseReader databaseReader;
static {
try {
InputStream inputStream = GeoIPReader.class.getClassLoader().getResourceAsStream("GeoLite2-City.mmdb");
databaseReader = new DatabaseReader.Builder(inputStream).build();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException, GeoIp2Exception {
String addeassByIP = getCountryAndRegionByIP("1.203.160.07");
System.out.println("addeassByIP = " + addeassByIP);
}
public static String getCountryAndRegionByIP(String ip) throws IOException, GeoIp2Exception {
String ipRegex = "^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
if(!ip.matches(ipRegex)){
throw new BusinessException("ip 地址不合法");
}
String[] countryAndRegion = getCountryAndRegion(ip,"zh-CN");
String country = countryAndRegion[0];
String region = countryAndRegion[1];
return StringUtils.isBlank(region) ? country : country + "-" + region;
}
/**
* 根据ip获取国家和地区
* @param ip IP地址
* @param language 语言,包含:{de=China, ru=Китай, pt-BR=China, ja=中国, en=China, fr=Chine, zh-CN=中国, es=China}
* @return
* @throws IOException
* @throws GeoIp2Exception
*/
private static String[] getCountryAndRegion(String ip, String language) throws IOException, GeoIp2Exception {
try {
InetAddress ipAddress = InetAddress.getByName(ip);
CityResponse response = databaseReader.city(ipAddress);
Map<String, String> countryNames = response.getCountry().getNames();
String country = countryNames.get(language);
Map<String, String> subNames = response.getMostSpecificSubdivision().getNames();
String region = subNames.get(language);
return new String[]{country, region};
} catch (AddressNotFoundException e) {
return new String[]{null, null};
}
}
}
4.本地测试
打印成功~
5.写在最后
在自测的过程中,发现了很多ip都是只能显示国家,没有地区,由于我当前下载的是70MB的city.mmdb,但是里面囊括的ip还是太少,截止到2023年3月21日,里面收录的ip总共有将近380w个,而中国ip仅有19600余个,所以选择这个免费版还是有很大局限性,另外如果需要部署到公司的线上环境,70MB的内存还是比较损耗资源的(测试发现读取这个文件到JVM实际占用了120MB内存)
这里就推荐大家下载CSV格式,自行导入mysql,以下是mysql的相关脚本代码
CREATE TABLE `GeoLite2_IPv4` (
`network` varchar(20) NOT NULL COMMENT 'IP',
`geoname_id` varchar(20) DEFAULT '' COMMENT '城市编号',
`registered_country_geoname_id` varchar(20) DEFAULT '' COMMENT '国家编号',
PRIMARY KEY (`network`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=DYNAMIC COMMENT='IP城市表';
CREATE TABLE `GeoLite2_City_CN` (
`geoname_id` varchar(20) NOT NULL COMMENT '城市编号',
`country_iso_code` varchar(20) NOT NULL COMMENT '国家编码',
`country_name` varchar(20) DEFAULT '' COMMENT '国家名称',
`subdivision_1_name` varchar(20) NOT NULL COMMENT '省份名称',
`city_name` varchar(20) DEFAULT '' COMMENT '城市名称',
`time_zone` varchar(20) NOT NULL COMMENT '时区',
PRIMARY KEY (`geoname_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=DYNAMIC COMMENT='城市表';
将下载好的文件导入到对应mysql表中即可