获取用户ip所在都会

[复制链接]
发表于 2025-9-25 15:48:56 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
团体流程图

获取当前登任命户所在都会,是一个非经常见的需求,在许多业务场景中用到。
好比:导航的定位功能默认选择的都会,大概一些防盗体系中辨认用户两次登录的都会不一样的会有报警提示。
下载geoip2数据库

geoip2是国外的一个免费的IP库,只要注册账号就能下载IP数据库了。
官网地点:https://www.maxmind.com/。
其他下载:https://kohler.o.com/i3Fkb36wobuh
将IP库生存到电脑的某个目次下

之后利用绝对路径

引入干系依靠

引入geoip干系的依靠包:
  1. <dependency>
  2.     <groupId>com.maxmind.geoip2</groupId>
  3.     <artifactId>geoip2</artifactId>
  4.     <version>2.16.1</version>
  5. </dependency>
复制代码
增长获取都会接口

增长一个根据ip获取所在都会的接口。
创建一个GeoIpController类:
  1. @Tag( name= "geoip操作", description = "geoip操作")
  2. @RestController
  3. @RequestMapping("/v1/web/geoip")
  4. @Validated
  5. public class GeoIpController {
  6.     @Autowired
  7.     private GeoIpHelper geoIpHelper;
  8.     /**
  9.      * 根据ip获取所在城市
  10.      *
  11.      * @param ip ip地址
  12.      * @return 城市
  13.      */
  14.     @NoLogin
  15.     @Operation(summary = "根据ip获取所在城市", description = "根据ip获取所在城市")
  16.     @GetMapping("/getCity")
  17.     public CityDTO getCity(@RequestParam(value = "ip") String ip) {
  18.         return geoIpHelper.getCity(ip);
  19.     }
  20. }
复制代码
这个类中只包罗了getCity这一个接口,该接口就是通过ip获取所在国家、省份和都会。
创建GeoIpHelper类:
  1. @Slf4j
  2. @Component
  3. public class GeoIpHelper {
  4.     private static final String GEO_IP_FILE_NAME = "GeoLite2-City.mmdb";
  5.     @Value("${shop.mgt.geoIpFilePath:}")
  6.     private String geoIpFilePath;
  7.     @Value("${shop.mgt.taobaoIpUrl:}")
  8.     private String taobaoIpUrl;
  9.     @Value("${shop.mgt.taobaoIpRequestOff:false}")
  10.     private Boolean taobaoIpRequestOff;
  11.     @Autowired
  12.     private HttpHelper httpHelper;
  13.     /**
  14.      * 根据ip获取所在城市
  15.      *
  16.      * @param ip ip地址
  17.      * @return 城市
  18.      */
  19.     public CityDTO getCity(String ip) {
  20.         CityDTO cityFromGeoIp = getCityFromGeoIp(ip);
  21.         if (Objects.nonNull(cityFromGeoIp) && Objects.nonNull(cityFromGeoIp.getCity())) {
  22.             return cityFromGeoIp;
  23.         }
  24.         if (taobaoIpRequestOff) {
  25.             return null;
  26.         }
  27.         return getCityFromApi(ip);
  28.     }
  29.     private CityDTO getCityFromGeoIp(String ip) {
  30.         String fileUrl = getFileUrl();
  31.         File file = new File(fileUrl);
  32.         if (!file.exists()) {
  33.             log.warn(String.format("%s文件不存在", fileUrl));
  34.             return null;
  35.         }
  36.         try {
  37.             DatabaseReader reader = new DatabaseReader.Builder(file).build();
  38.             //解析IP地址
  39.             InetAddress ipAddress = InetAddress.getByName(ip);
  40.             // 获取查询结果
  41.             CityResponse response = reader.city(ipAddress);
  42.             if (response == null) {
  43.                 return null;
  44.             }
  45.             // 国家
  46.             String country = response.getCountry().getNames().get("zh-CN");
  47.             // 省份
  48.             String province = response.getMostSpecificSubdivision().getNames().get("zh-CN");
  49.             //城市
  50.             String city = response.getCity().getNames().get("zh-CN");
  51.             return new CityDTO(ip, country, province, city);
  52.         } catch (Exception e) {
  53.             log.error("从GeoIp库中获取城市失败,原因:", e);
  54.         }
  55.         return null;
  56.     }
  57.     private CityDTO getCityFromApi(String ip) {
  58.         String url = String.format(taobaoIpUrl, ip);
  59.         TaoboCityEntity taoboCityEntity = httpHelper.doGet(url, TaoboCityEntity.class);
  60.         if (Objects.nonNull(taoboCityEntity)) {
  61.             TaoboCityEntity.TaoboAreaEntity data = taoboCityEntity.getData();
  62.             if (Objects.nonNull(data)) {
  63.                 return new CityDTO(ip, data.getCountry(), data.getRegion(), data.getCity());
  64.             }
  65.         }
  66.         return null;
  67.     }
  68.     private String getFileUrl() {
  69.         return geoIpFilePath + "/" + GEO_IP_FILE_NAME;
  70.     }
  71. }
复制代码
这个类重要是来用读取IP库的数据,通过ip查询国家、省份和都会。
由于ip库有大概不全,大概不是最新的数据。大概会导致根据ip获取不到我们想要的数据的环境。
因此必要做兼容处理惩罚,如果从ip库查询不到数据,则再调用一下长途接口获取数据。
调用淘宝接口

创建HttpHelper类:
  1. @Slf4j
  2. @Component
  3. public class HttpHelper {
  4.     @Autowired
  5.     private RestTemplate restTemplate;
  6.     /**
  7.      * 发送get请求
  8.      *
  9.      * @param url    url地址
  10.      * @param tClass 返回值实体
  11.      * @param <T>    泛型
  12.      * @return 返回值实体
  13.      */
  14.     public <T> T doGet(String url, Class<T> tClass) {
  15.         return restTemplate.getForObject(url, tClass);
  16.     }
  17. }
复制代码
界说了doGet方法获取用户哀求。
创建了RestTemplateConfig类:
  1. @Configuration
  2. public class RestTemplateConfig {
  3.     @Value("${shop.mgt.rest.template.connectTimeout:3000}")
  4.     private int connectTimeout;
  5.     @Value("${shop.mgt.rest.template.readTimeout:50000}")
  6.     private int readTimeout;
  7.     @Bean
  8.     public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
  9.         return new RestTemplate(factory);
  10.     }
  11.     @Bean
  12.     public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
  13.         HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
  14.         factory.setConnectTimeout(connectTimeout);
  15.         factory.setReadTimeout(readTimeout);
  16.         return factory;
  17.     }
  18.     /**
  19.      * 忽略证书配置
  20.      */
  21.     public static HttpComponentsClientHttpRequestFactory generateHttpRequestFactory()
  22.             throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
  23.         TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;
  24.         SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
  25.         SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
  26.                 new NoopHostnameVerifier());
  27.         HttpClientBuilder httpClientBuilder = HttpClients.custom();
  28.         httpClientBuilder.setSSLSocketFactory(connectionSocketFactory);
  29.         CloseableHttpClient httpClient = httpClientBuilder.build();
  30.         HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
  31.         factory.setHttpClient(httpClient);
  32.         return factory;
  33.     }
  34. }
复制代码
这个类是一个设置类,重要设置了RestTemplate的一些参数,以及https哀求忽略证书的环境。
如果不忽略证书,有些环境下,好比:调用测试环境的哀求,利用的不是有效的证书,会哀求失败。
application.yml文件中增长设置:
  1. shop:
  2.   mgt:
  3.     geoIpFilePath: D:\workplace\SpringBoot\kailong_shop\shop_business\src\main\resources\files\geoip2
  4.     taobaoIpUrl: https://ip.taobao.com/outGetIpInfo?ip=%s&accessKey=alibaba-inc
复制代码
此中accessKey利用的淘宝的测试key。
测试

代码开发好之后,接下来举行测试。
在欣赏器上访问:http://localhost:8011/v1/web/geoip/getCity?ip=123.245.11.177(我的测试路径)
返回了精确的都会

分析根据ip获取所在都会的功能OK了。
必要特殊留意的是如今调用淘宝的测试接口,天天有数目限定,到达肯定测试就会返回失败。
也可以换成其他平台的接口,大概申请一个付费的accessKey。
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表