积累篇>>使用GeoLite2数据库,获取当前登录用户地区

需求:获取当前登录用户地区(省/市)。感谢Max Mind!(^v^)

GeoLite2数据库是免费的IP地理定位数据库......可能是免费版的,有点不太准(=_=)

详情:https://dev.maxmind.com/geoip/geoip2/geolite2/

积累篇>>使用GeoLite2数据库,获取当前登录用户地区_第1张图片 我选的第一个,当然不确定的都下载,总有一款适合你

官方文档,demo,详情:https://maxmind.github.io/GeoIP2-java/

// A File object pointing to your GeoIP2 or GeoLite2 database
File database = new File("/path/to/GeoIP2-City.mmdb");

// This creates the DatabaseReader object. To improve performance, reuse
// the object across lookups. The object is thread-safe.
DatabaseReader reader = new DatabaseReader.Builder(database).build();

InetAddress ipAddress = InetAddress.getByName("128.101.101.101");

// Replace "city" with the appropriate method for your database, e.g.,
// "country".
CityResponse response = reader.city(ipAddress);

Country country = response.getCountry();
System.out.println(country.getIsoCode());            // 'US'
System.out.println(country.getName());               // 'United States'
System.out.println(country.getNames().get("zh-CN")); // '美国'

Subdivision subdivision = response.getMostSpecificSubdivision();
System.out.println(subdivision.getName());    // 'Minnesota'
System.out.println(subdivision.getIsoCode()); // 'MN'

City city = response.getCity();
System.out.println(city.getName()); // 'Minneapolis'

Postal postal = response.getPostal();
System.out.println(postal.getCode()); // '55455'

Location location = response.getLocation();
System.out.println(location.getLatitude());  // 44.9733
System.out.println(location.getLongitude()); // -93.2323

应用到项目中

把下载好的文件放到静态资源下

积累篇>>使用GeoLite2数据库,获取当前登录用户地区_第2张图片

依赖包

        
		
			com.maxmind.geoip2
			geoip2
			2.12.0
		

业务层逻辑代码,有坑!!!

 /**
     * 根据ip获取地区
     * @param ip
     * @return
     * @throws IOException
     */
    public String getLoginArea(String ip) throws Exception {
        //io流读取文件,这里是个坑,如果官方文档用File,项目打包上传到服务器后会报错,找不到文件
        InputStream inputStream=this.getClass().getResourceAsStream("/db/GeoLite2-City.mmdb");
        // 读取数据库内容
        DatabaseReader reader = new DatabaseReader.Builder(inputStream).build();
        InetAddress ipAddress = InetAddress.getByName(ip);

        // 获取查询结果
        CityResponse response = reader.city(ipAddress);

        //获取国家信息
        Country country = response.getCountry();
        String countryStr = country.getNames().get("zh-CN");
        if (countryStr==null){
            countryStr = "";
        }

        // 获取省份
        Subdivision subdivision = response.getMostSpecificSubdivision();
        String subdivisionStr = subdivision.getNames().get("zh-CN");
        if (subdivisionStr==null){
            subdivisionStr = "";
        }

        //获取城市
        City city = response.getCity();
        String cityStr = city.getNames().get("zh-CN");
        if (cityStr==null){
            cityStr = "";
        }
        String loginArea = countryStr+subdivisionStr+cityStr;
        return loginArea;
    }

 

controller层逻辑代码

String ipAddress = IPUtils.getIpAddress(request);
  if (!ipAddress.equals("127.0.0.1")){//本地测试忽略
  //获取登录地区
  String loginArea = ipManagerService.getLoginArea(ipAddress);//业务层
  logger.info("当前ip的登录地区是=============="+loginArea);
  }

补充:获取ip工具类

public class IPUtils {

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.contains(",")) {
            return ip.split(",")[0];
        } else {
            return ip;
        }
    }
}

本人自己的总结。不足之处,望请谅解!

 

你可能感兴趣的:(碎片总结)