目录
从gitee拉取ip2region.xdb资源文件
写测试类
注意要写对资源路径
本地测试结果
编辑 远端测试结果
从gitee拉取ip2region.xdb资源文件
git clone https://gitee.com/lionsoul/ip2region.git
将xdb放入resources资源文件夹
引入依赖
<dependency><groupId>org.lionsoul</groupId><artifactId>ip2region</artifactId><version>2.7.0</version>
</dependency>
写测试类
private Searcher searcher;@GetMapping("test")@ApiOperation("test")public String test() throws IOException {HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();String ipAddress = null;try {// 获取请求客户端的ipipAddress = request.getHeader("x-forwarded-for");if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {ipAddress = request.getHeader("Proxy-Client-IP");}if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {ipAddress = request.getHeader("WL-Proxy-Client-IP");}if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {ipAddress = request.getRemoteAddr();if (ipAddress.equals("127.0.0.1")||ipAddress.equals("0:0:0:0:0:0:0:1")) {ipAddress = "127.0.0.1";}}// 判断ip是否符合规格if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()// = 15if (ipAddress.indexOf(",") > 0) {ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));}}} catch (Exception e) {ipAddress="";}if ("127.0.0.1".equals(ipAddress) || ipAddress.startsWith("192.168")) {return "局域网 ip";}String dbPath;if (searcher == null) {try {// 加载ip2region 文件searcher=Searcher.newWithFileOnly("pipayshop-api/src/main/resources/ipdb/ip2region.xdb");} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}String region = null;String errorMessage = null;try {// 获取地区region = searcher.search(ipAddress);} catch (Exception e) {errorMessage = e.getMessage();if (errorMessage != null && errorMessage.length() > 256) {errorMessage = errorMessage.substring(0,256);}e.printStackTrace();}// 输出 regionreturn region;}
注意要写对资源路径
本地的资源路径
远端服务器资源路径(需要与你写的路径一一对应,不然找不到文件)