public static String getAddressLog(String userPhone, String ip) {
try {
HttpServletRequest request = RequestUtil.getRequest();
log.info("======> 获取客户端IP地址:clientIP:{}", ip);
if (StrUtil.isBlank(ip)) {
log.error("获取用户ip失败,用户手机号 = " + userPhone);
} else {
IpLocation ipLocation = IPUtil.getLocation(ip);
if (ObjectUtil.isNotNull(ipLocation.getProvince())) {
//根据业务需求来确定需要定位到省还是省-市,我这里就直接是定位到省
String address = ipLocation.getProvince();
log.info("======> IP解析后的地址信息:{}", address);
//注意:如果是内网IP的话,这里将查询不到归属地,而会返回内网,
//这里如果是内网IP就直接处理变成广东省。
if (StringUtils.isNotEmpty(address)){
return address.contains("内网") ? "广东省" : address;
}
}
}
} catch (Exception e) {
log.error("通过ip获取用户位置失败,用户phone = {}", userPhone);
log.error("通过ip获取用户位置失败,e = {}", e);
}
}
/**
* 根据iP获取归属地信息
*/
public static IpLocation getLocation(String ip) {
IpLocation location = new IpLocation();
location.setIp(ip);
try (InputStream inputStream = IPUtil.class.getResourceAsStream("/ipdb/ip2region.xdb");) {
byte[] bytes = IoUtil.readBytes(inputStream);
Searcher searcher = Searcher.newWithBuffer(bytes);
String region = searcher.search(ip);
log.info("============> region:{}", region);
if (StrUtil.isNotBlank(region)) {
// xdb返回格式 国家|区域|省份|城市|ISP,
// 只有中国的数据绝大部分精确到了城市,其他国家部分数据只能定位到国家,后前的选项全部是0
String[] result = region.split("\\|");
location.setCountry(ZERO.equals(result[0]) ? StrUtil.EMPTY : result[0]);
location.setProvince(ZERO.equals(result[2]) ? StrUtil.EMPTY : result[2]);
location.setCity(ZERO.equals(result[3]) ? StrUtil.EMPTY : result[3]);
location.setIsp(ZERO.equals(result[4]) ? StrUtil.EMPTY : result[4]);
}
searcher.close();
} catch (Exception e) {
e.printStackTrace();
return location;
}
return location;
}
|