JAVA + GeoLite2+ip定位,查詢國家地理位置信息

      最新要用到地理位置做區域劃分,需要知道哪個ip屬於哪個區,五大洲的區域劃分,有兩千個IP需要知道,並且查詢頻率比較高,每十分鐘去查詢一次,

          最開始是用的第三方API去調用,比如淘寶,百度等,但是就怕請求太頻繁了,哪天給我黑名單了, 那我線上程序就掛了,還有一個,在國內用的話,是比較方便的,IP純真數據庫,但是我的IP大部分都是國外,定位在國內是沒有什麼問題,國外就不太準確了,巴西的IP取出來是美國的地址,這個數據庫比較小,用起來簡單,由於對國外的IP不準確,就放棄了,

        然後纔開始選擇GeoLite2 IP庫作爲查詢目的,不過這個庫要手動去更新,不更新其實也能滿足現在的需要 用起來也比較簡單,文件可能有些大了,63M 大小,

下面開始 試用 

1 下載mmdb文件數據庫和添加依賴

GeoLite2.mmdb官方下載地址

maven 依賴 下面的配置

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

代碼部分   IP庫GeoLite2-City.mmdb 我是放在項目的根目錄下,

public static void getLiteIPinit() throws IOException, GeoIp2Exception {
        //GeoIP2-City 數據庫文件

        File database = new File(Thread.currentThread().getContextClassLoader().getResource("GeoLite2-City.mmdb").getPath());
        // this.getClass().getClassLoader().getResource("").getPath();  得到的是 ClassPath的絕對URI路徑。

        // 創建 DatabaseReader對象
        DatabaseReader reader = new DatabaseReader.Builder(database).build();

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

        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

    }

2   IP純真數據庫  簡單使用也說下, 國內還是很不錯

maven 依賴  

下載的包 https://search.maven.org/remotecontent?filepath=com/github/jarod/qqwry-java/0.7.0/qqwry-java-0.7.0.jar

<dependency>
    <groupId>com.github.jarod</groupId>
    <artifactId>qqwry-java</artifactId>
    <version>0.7.0</version>
</dependency>

Java 代碼實現

public static void main(String[] args) throws IOException {
    //這裏因爲是去讀取本地的純真庫,所以有一個IO異常拋出
    QQWry wry = new QQWry();
    IPZone zone = wry.findIP("123.123.123.123");
    System.out.println(zone.getMainInfo());
    System.out.println(zone.getSubInfo());
}

輸出:
北京市
聯通

發佈了144 篇原創文章 · 獲贊 28 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章