12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- package com.webchat.common.util;
- import com.alibaba.fastjson.JSONObject;
- import com.google.common.cache.Cache;
- import com.google.common.cache.CacheBuilder;
- import com.webchat.common.enums.LocalCacheKey;
- import com.webchat.domain.vo.response.IpLocationResponseVO;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.commons.lang3.StringUtils;
- import java.util.concurrent.TimeUnit;
- /**
- * @Author: 程序员七七
- * @Date: 2.5.22 3:59 下午
- */
- @Slf4j
- public class IPAddressUtil {
- /**
- * IP 归属地解析API(免费)
- *
- */
- private static final String IP_ADDRESS_API = "https://whois.pconline.com.cn/ipJson.jsp?ip=%s&json=true";
- private static final Cache<String, IpLocationResponseVO> IP_LOCAL_CACHE;
- static {
- IP_LOCAL_CACHE = CacheBuilder.newBuilder()
- .softValues()
- .maximumSize(500L)
- .expireAfterWrite(600L, TimeUnit.SECONDS)
- .build();
- }
- public static IpLocationResponseVO location(String ip) {
- if (StringUtils.isBlank(ip)) {
- return null;
- }
- String localCacheKey = LocalCacheKey.IP_LOCATION.name().concat("_").concat(ip);
- IpLocationResponseVO localCacheVal = IP_LOCAL_CACHE.getIfPresent(localCacheKey);
- if (localCacheVal != null) {
- log.info("{} 规则归属地解析成功 - FROM LOCAL CACHE:{}", ip, JsonUtil.toJsonString(localCacheVal));
- return localCacheVal;
- }
- // 通过API查询
- IpLocationResponseVO ipLocationResponseVO = locationFromApi(ip);
- // 加入本地缓存
- IP_LOCAL_CACHE.put(localCacheKey, ipLocationResponseVO);
- log.info("{} 规则归属地解析成功 - FROM API:{}", ip, JsonUtil.toJsonString(ipLocationResponseVO));
- return ipLocationResponseVO;
- }
- private static IpLocationResponseVO locationFromApi(String ip) {
- IpLocationResponseVO ipLocationResponseVO = IpLocationResponseVO.builder().build();
- String url = String.format(IP_ADDRESS_API, ip);
- try {
- String response = HttpClientUtil.getObjectFromUrl(url, String.class);
- if (StringUtils.isBlank(response)) {
- return ipLocationResponseVO;
- }
- JSONObject responseJson = JSONObject.parseObject(response);
- return IpLocationResponseVO.builder()
- .country(responseJson.getString("country"))
- .province(responseJson.getString("pro"))
- .city(responseJson.getString("city"))
- .district(responseJson.getString("region"))
- .build();
- } catch (Exception e) {
- log.error("IP LOCATION analysis error. ip:{}", ip, e);
- }
- return ipLocationResponseVO;
- }
- }
|