積累篇>>使用GeoLite2數據庫,獲取當前登錄用戶地區

需求:獲取當前登錄用戶地區(省/市)。感謝Max Mind!(^v^)

GeoLite2數據庫是免費的IP地理定位數據庫......可能是免費版的,有點不太準(=_=)

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

 我選的第一個,當然不確定的都下載,總有一款適合你

官方文檔,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

應用到項目中

把下載好的文件放到靜態資源下

依賴包

        <!--GeoIP2-->
		<dependency>
			<groupId>com.maxmind.geoip2</groupId>
			<artifactId>geoip2</artifactId>
			<version>2.12.0</version>
		</dependency>

業務層邏輯代碼,有坑!!!

 /**
     * 根據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;
        }
    }
}

本人自己的總結。不足之處,望請諒解!

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章