日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

SpringBoot 集成ip2region

發布時間:2025/3/15 javascript 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringBoot 集成ip2region 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、 什么是ip2region

ip2region:可以根據他獲取一個具體ip的信息,國家、具體地址、網絡服務商

二、添加依賴

<dependency><groupId>org.lionsoul</groupId><artifactId>ip2region</artifactId><version>1.7</version> </dependency>

三、工具類

public class AddressUtils {/*** 根據IP地址獲取地理位置*/public static String getAddressByIP(String ip) {if (StringUtils.isBlank(ip)) {return "";}if ("127.0.0.1".equals(ip)||"0:0:0:0:0:0:0:1".equals(ip)) {return "局域網,無法獲取位置";}// //開發時使用的代碼 // String dbPath = AddressUtils.class.getResource("/ip2region.db").getPath(); // File file = new File(dbPath); // if ( file.exists() == false ) { // System.out.println("Error: Invalid ip2region.db file"); // } // //查詢算法 int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree // //DbSearcher.BINARY_ALGORITHM //Binary // int algorithm =DbSearcher.MEMORY_ALGORITYM; //Memory // try { // DbConfig config = new DbConfig(); // DbSearcher searcher = new DbSearcher(config, dbPath); // //define the method // Method method = null; // switch ( algorithm ) // { // case DbSearcher.BTREE_ALGORITHM: // method = searcher.getClass().getMethod("btreeSearch", String.class); // break; // case DbSearcher.BINARY_ALGORITHM: // method = searcher.getClass().getMethod("binarySearch", String.class); // break; // case DbSearcher.MEMORY_ALGORITYM: // method = searcher.getClass().getMethod("memorySearch", String.class); // break; // } // DataBlock dataBlock = null; // if (Util.isIpAddress(ip) == false ) { // System.out.println("Error: Invalid ip address"); // } // dataBlock = (DataBlock) method.invoke(searcher, ip); // return dataBlock.getRegion();//部署時使用的代碼try{// 讀取jar包內的配置文件信息ClassPathResource resource = new ClassPathResource("/ip2region.db");InputStream inputStream = resource.getInputStream();byte[] dbBinStr = IoUtil.readBytes(inputStream);DbConfig config = new DbConfig();DbSearcher searcher = new DbSearcher(config, dbBinStr);// 查詢算法memory,采用二進制方式初始化DBSearcher需要使用MEMORY_ALGORITYM,//否則會拋出null。Method method = searcher.getClass().getMethod("memorySearch", String.class);return ((DataBlock) method.invoke(searcher, ip)).getRegion();} catch (Exception e) {e.printStackTrace();}return null;} }

三、遇到的錯誤

如我上面工具類所寫的,開發時的代碼和部署時的代碼是不一樣的,這是因為,ip2region所依賴的ip2region文件(如下:)在打包成jar時,使用開發時所寫的代碼是讀取不到的,必須以部署時的代碼,才能讀取到。

這個問題的參考文章

與50位技術專家面對面20年技術見證,附贈技術全景圖

總結

以上是生活随笔為你收集整理的SpringBoot 集成ip2region的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。