IPAddressUtil.java 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package com.webchat.common.util;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.google.common.cache.Cache;
  4. import com.google.common.cache.CacheBuilder;
  5. import com.webchat.common.enums.LocalCacheKey;
  6. import com.webchat.domain.vo.response.IpLocationResponseVO;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.apache.commons.lang3.StringUtils;
  9. import java.util.concurrent.TimeUnit;
  10. /**
  11. * @Author: 程序员七七
  12. * @Date: 2.5.22 3:59 下午
  13. */
  14. @Slf4j
  15. public class IPAddressUtil {
  16. /**
  17. * IP 归属地解析API(免费)
  18. *
  19. */
  20. private static final String IP_ADDRESS_API = "https://whois.pconline.com.cn/ipJson.jsp?ip=%s&json=true";
  21. private static final Cache<String, IpLocationResponseVO> IP_LOCAL_CACHE;
  22. static {
  23. IP_LOCAL_CACHE = CacheBuilder.newBuilder()
  24. .softValues()
  25. .maximumSize(500L)
  26. .expireAfterWrite(600L, TimeUnit.SECONDS)
  27. .build();
  28. }
  29. public static IpLocationResponseVO location(String ip) {
  30. if (StringUtils.isBlank(ip)) {
  31. return null;
  32. }
  33. String localCacheKey = LocalCacheKey.IP_LOCATION.name().concat("_").concat(ip);
  34. IpLocationResponseVO localCacheVal = IP_LOCAL_CACHE.getIfPresent(localCacheKey);
  35. if (localCacheVal != null) {
  36. log.info("{} 规则归属地解析成功 - FROM LOCAL CACHE:{}", ip, JsonUtil.toJsonString(localCacheVal));
  37. return localCacheVal;
  38. }
  39. // 通过API查询
  40. IpLocationResponseVO ipLocationResponseVO = locationFromApi(ip);
  41. // 加入本地缓存
  42. IP_LOCAL_CACHE.put(localCacheKey, ipLocationResponseVO);
  43. log.info("{} 规则归属地解析成功 - FROM API:{}", ip, JsonUtil.toJsonString(ipLocationResponseVO));
  44. return ipLocationResponseVO;
  45. }
  46. private static IpLocationResponseVO locationFromApi(String ip) {
  47. IpLocationResponseVO ipLocationResponseVO = IpLocationResponseVO.builder().build();
  48. String url = String.format(IP_ADDRESS_API, ip);
  49. try {
  50. String response = HttpClientUtil.getObjectFromUrl(url, String.class);
  51. if (StringUtils.isBlank(response)) {
  52. return ipLocationResponseVO;
  53. }
  54. JSONObject responseJson = JSONObject.parseObject(response);
  55. return IpLocationResponseVO.builder()
  56. .country(responseJson.getString("country"))
  57. .province(responseJson.getString("pro"))
  58. .city(responseJson.getString("city"))
  59. .district(responseJson.getString("region"))
  60. .build();
  61. } catch (Exception e) {
  62. log.error("IP LOCATION analysis error. ip:{}", ip, e);
  63. }
  64. return ipLocationResponseVO;
  65. }
  66. }