找回密码
 立即注册
首页 业界区 安全 获取用户ip所在城市

获取用户ip所在城市

后仲舒 6 天前
整体流程图
1.png

获取当前登录用户所在城市,是一个非常常见的需求,在很多业务场景中用到。
比如:导航的定位功能默认选择的城市,或者一些防盗系统中识别用户两次登录的城市不一样的会有报警提示。
下载geoip2数据库

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

之后使用绝对路径
3.png

引入相关依赖

引入geoip相关的依赖包:
  1. <dependency>
  2.     <groupId>com.maxmind.geoip2</groupId>
  3.     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(我的测试路径)
返回了正确的城市
4.png

说明根据ip获取所在城市的功能OK了。
需要特别注意的是目前调用淘宝的测试接口,每天有数量限制,达到一定测试就会返回失败。
也可以换成其他平台的接口,或者申请一个付费的accessKey。

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册