當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot 集成ip2region
生活随笔
收集整理的這篇文章主要介紹了
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時,使用開發時所寫的代碼是讀取不到的,必須以部署時的代碼,才能讀取到。
這個問題的參考文章
總結
以上是生活随笔為你收集整理的SpringBoot 集成ip2region的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Shrio Unable to exec
- 下一篇: B端SaaS产品工作流程