ip2region - 是一个离线IP地址定位库和IP定位数据管理框架,10微秒级别的查询效率,提供了众多主流编程语言的 xdb
数据生成和查询客户端实现。
pom.xml<dependency> <groupId>org.lionsoul</groupId> <artifactId>ip2region</artifactId> <version>2.7.0</version> </dependency>
|
RegionUtils.javaimport cn.hutool.core.io.FileUtil; import cn.hutool.core.io.resource.ClassPathResource; import cn.hutool.core.util.ObjectUtil; import org.dromara.common.core.exception.ServiceException; import org.dromara.common.core.utils.file.FileUtils; import lombok.extern.slf4j.Slf4j; import org.lionsoul.ip2region.xdb.Searcher;
import java.io.File;
@Slf4j public class RegionUtils {
private static final Searcher SEARCHER;
static { String fileName = "/ip2region.xdb"; File existFile = FileUtils.file(FileUtil.getTmpDir() + FileUtil.FILE_SEPARATOR + fileName); if (!FileUtils.exist(existFile)) { ClassPathResource fileStream = new ClassPathResource(fileName); if (ObjectUtil.isEmpty(fileStream.getStream())) { throw new ServiceException("RegionUtils初始化失败,原因:IP地址库数据不存在!"); } FileUtils.writeFromStream(fileStream.getStream(), existFile); }
String dbPath = existFile.getPath();
byte[] cBuff; try { cBuff = Searcher.loadContentFromFile(dbPath); } catch (Exception e) { throw new ServiceException("RegionUtils初始化失败,原因:从ip2region.xdb文件加载内容失败!" + e.getMessage()); } try { SEARCHER = Searcher.newWithBuffer(cBuff); } catch (Exception e) { throw new ServiceException("RegionUtils初始化失败,原因:" + e.getMessage()); } }
public static String getCityInfo(String ip) { try { ip = ip.trim(); String region = SEARCHER.search(ip); return region.replace("0|", "").replace("|0", ""); } catch (Exception e) { log.error("IP地址离线获取城市异常 {}", ip); return "未知"; } }
}
|
参考