springboot获取当前服务ip_springboot免费的IP定位服务

本文介绍了如何在SpringBoot应用中利用ip2region库进行IP地址定位。首先,通过maven引入ip2region依赖,然后创建Java工具类并设置数据库路径,提供三种查询算法:B-tree、Binary和Memory。最后,创建API接口进行测试,成功返回IP对应的城市信息。
摘要由CSDN通过智能技术生成

简介

ip2region 是准确率99.9%的ip地址定位库,0.0x毫秒级查询,数据库文件大小只有1.5M,提供了java,php,c,python,nodejs,golang,c#查询绑定和Binary,B树,内存三种查询算法!

maven依赖

org.lionsoul

ip2region

1.7.2

下载这个项目之后到data/文件夹下面找到ip2region.db,我放在了/user/home目录下

Java 工具类

public class IpUtil {

public static String getCityInfo(String ip, int type) {

//db

String dbPath = "/usr/home/ip2region.db";

File file = new File(dbPath);

if (!file.exists()) {

return "Error: Invalid ip2region.db file";

}

// 查询算法

// DbSearcher.BTREE_ALGORITHM B-tree

// DbSearcher.BINARY_ALGORITHM Binary

// DbSearcher.MEMORY_ALGORITYM Memory

// int algorithm = DbSearcher.BINARY_ALGORITHM;

try {

DbConfig config = new DbConfig();

DbSearcher searcher = new DbSearcher(config, dbPath);

//define the method

Method method = null;

switch (type) {

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;

default:

break;

}

DataBlock dataBlock;

if (!Util.isIpAddress(ip)) {

return "Error: Invalid ip address";

}

dataBlock = (DataBlock) method.invoke(searcher, ip);

return dataBlock.getRegion();

} catch (Exception e) {

e.printStackTrace();

return "exception";

}

}

}

写个接口用于测试

@ApiOperation(value = "IP定位")

@GetMapping("/test")

public ResponseEntity test(String ip, int type) {

return ResponseEntity.ok(IpUtil.getCityInfo(ip, type));

}

请求接口,定位成功:

image.png

有疑问加站长微信联系(非本文作者)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值