前段时间因业务需要,客户提出分析外网访问的IP,即针对一些热点区域的IP访问想做到事后预警与分析。
因为我们服务是运行在相对隔离的资源环境中,无法直接去请求外网,于是想到用离线的方式来处理从网关发来的数据。找了下,看到个开源项目
使用起来相对成本较低,本着先用满足需求再说,虽然在性能上并不能满足海量IP的分析,还有提升的空间。
看作者的例子,较为简单,也不多说。先看下我的目录结构吧
1 2 3 4 5 6 7 8 9 10
| war3-infi +---src | +---main | | +---java | | \---resources | | +---generator | | +---ipdb | | | | +---ip2region.db | | +---mapper | | +---application.yml
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| server: port: 9090
spring: redis: database: 0 host: 127.0.0.1 port: 6379
ip2region: external: false index-block-size: 4096 total-header-size: 8192 location: classpath:ipdb/ip2region.db
|
例子如下,RegionAddress
、DataBlock
两种结果返回封装。
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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| package xyz.wongs.drunkard.war3.web.controller;
import com.github.hiwepy.ip2region.spring.boot.IP2regionTemplate; import com.github.hiwepy.ip2region.spring.boot.ext.RegionAddress; import lombok.extern.slf4j.Slf4j; import org.nutz.plugins.ip2region.DataBlock; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import xyz.wongs.drunkard.base.aop.annotion.ApplicationLog; import xyz.wongs.drunkard.base.message.annoation.ResponseResult; import xyz.wongs.drunkard.base.message.exception.DrunkardException; import xyz.wongs.drunkard.war3.limit.RequestLimit;
import java.io.IOException; import java.util.HashMap; import java.util.Map;
@Slf4j @RestController @ResponseResult public class IndexController {
@Autowired IP2regionTemplate template;
@GetMapping(value = "/convert/{ip}") public DataBlock convertDataBlock(@PathVariable String ip){ DataBlock dataBlock = null; try { dataBlock = template.binarySearch(ip); } catch (IOException e) { e.printStackTrace(); } return dataBlock; }
@RequestLimit(maxCount=3) @GetMapping(value = "/region/{ip}") public RegionAddress convert(@PathVariable String ip){ RegionAddress regionAddress = null; try { regionAddress = template.getRegionAddress(ip); } catch (IOException e) { e.printStackTrace(); } return regionAddress; }
@GetMapping(value = "/region/ip={ip}") public RegionAddress caseInsensitive(@PathVariable String ip){ RegionAddress regionAddress = null; try { regionAddress = template.getRegionAddress(ip); } catch (IOException e) { e.printStackTrace(); } return regionAddress; }
}
|
2.1.1. 打开浏览器
访问 http://localhost:9090/region/ip=109.27.45.12
这是我之前一个例子,用来解析IP地址,获取地域信息的。

2.1.2. 源码地址,如果觉得对你有帮助,请Star

Github源码地址
Gitee源码地址