IP转地址
官方链接:
参考文章:
简介
ip2region v2.0 - 是一个离线IP地址定位库和IP定位数据管理框架,10微秒级别的查询效率,提供了众多主流编程语言的 xdb
数据生成和查询客户端实现。每个 ip 数据段的 region 信息都固定了格式:国家|区域|省份|城市|ISP(网络服务提供商)
使用
获取离线包
从网站上获取ip2region离线包,并将ip2region.xdb
放在resource
目录下
导入依赖
1 2 3 4 5 6 7 8 9 10 11 12 13
| <dependency> <groupId>org.lionsoul</groupId> <artifactId>ip2region</artifactId> <version>2.6.5</version> </dependency>
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.8.4</version> </dependency>
|
简单使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import cn.hutool.core.io.resource.ResourceUtil; import org.lionsoul.ip2region.xdb.Searcher;
public class Main { public static void main(String[] args) { byte[] bytes = ResourceUtil.readBytes("ip2region.xdb"); try { Searcher searcher = Searcher.newWithBuffer(bytes); System.out.println(searcher.search("1.2.3.4")); } catch (Exception e) { e.printStackTrace(); } } }
|
工具类封装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| import cn.hutool.core.io.resource.ResourceUtil; import lombok.SneakyThrows; import org.springframework.stereotype.Component; import org.lionsoul.ip2region.xdb.Searcher; import javax.annotation.PostConstruct;
@Component public final class IpUtils {
private static Searcher searcher;
private static final String UNKNOWN_ADDRESS = "UNKNOWN";
@PostConstruct public static void init() { try { searcher = Searcher.newWithBuffer(ResourceUtil.readBytes("ip2region.xdb")); } catch (Exception e) { throw new RuntimeException("failed to create content cached searcher", e); } }
public static String ipToAddress(String ip) { try { return searcher.search(ip); } catch (Exception e) { return UNKNOWN_ADDRESS; } } }
|