springboot 学习之路 23 (ip2region的使用)
ip2region:
在开发中,我们需要记录登陆的日志信息,关于登陆者的ip和位置信息,我们可以通过ip2region来实现。
ip2region:可以根据他获取一个具体ip的信息,国家、具体地址、网络服务商
springboot和 ipregion的整合步骤:
第一步:引入依赖pom
    
第二步:下载ip2region.db
$ git clone https://gitee.com/lionsoul/ip2region.git
下载这个项目之后到data/文件夹下面找到ip2region.db复制到项目resources下
第三步:写工具类:
package com.huhy.demo.ip2region; import org.lionsoul.ip2region.DataBlock; import org.lionsoul.ip2region.DbConfig; import org.lionsoul.ip2region.DbSearcher; import org.lionsoul.ip2region.Util; import java.io.File; import java.lang.reflect.Method; /** * @author : huhy on 2018/10/10. * @Project_name:springboot_self_gitlab * @LOCAL:com.huhy.demo.ip2region * @description:获取外网ip位置的工具类 */ public class IPUtils { /** * @author huhy * @ClassName:IPUtils * @date 2018/10/10 15:01 * @Description: 根据外网ip获取位置信息 */ public static String getIPInfo(String ip){ //加载ip2region.db String dbPath = IPUtils.class.getResource("/ip2region/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 //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(); } catch (Exception e) { e.printStackTrace(); } return null; } }
第四步:测试:
    
本文来自博客园,作者:huhy,转载请注明原文链接:https://www.cnblogs.com/huhongy/p/9766449.html


                
            
        
浙公网安备 33010602011771号