From 4b6b1f8138d22bb868b7edd52098c16172ba3b1a Mon Sep 17 00:00:00 2001 From: Harry Yang Date: Sat, 21 Oct 2023 10:15:34 +0800 Subject: [PATCH] =?UTF-8?q?:memo:=20=E6=9B=B4=E6=96=B0=E4=BD=BF=E7=94=A8?= =?UTF-8?q?=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 110 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) diff --git a/README.md b/README.md index d8abcdb..579bb8f 100644 --- a/README.md +++ b/README.md @@ -7,9 +7,24 @@ 核心算法代码来自 [Ip2region](https://github.com/lionsoul2014/ip2region) +## 安装 + +```groovy +implementation 'cn.taketoday:ip2region-java:1.0-SNAPSHOT' +``` + +```xml + + cn.taketoday + ip2region-java + 1.0-SNAPSHOT + +``` ## 最佳实践 +### 静态工具类方式 + ```java // 应用里有多处会用到搜索则可以使用一个静态工具类来调用 // 由于 ip2region.xdb 不算小,全局共享一个实例即可 @@ -27,12 +42,107 @@ public abstract class IpUtils { } } +``` + +### 依赖注入方式 + +```java +// 方式一 + +/** + * 声明自己的API(也可以按需面向接口)到 IoC 容器,该方法可维护性更强 + */ +@Component +public class IpSearcherOperations { + + static final IpSearcher ipSearcher = IpSearcher.forDefaultResourceLocation(); + // static final IpSearcher ipSearcher = IpSearcher.forResource(new ClassPathResource("ip2region.xdb")); + + public String search(String ip) { + return ipSearcher.search(ip); + } + + public IpLocation find(String ip) { + return ipSearcher.find(ip); + } + +} + +// 调用 + +/** + * 调用端直接使用依赖注入 + */ +@Component +public class Client { + + final IpSearcherOperations operations; + + Client(IpSearcherOperations operations) { + this.operations = operations; + } + + public void test() { + String ip = "1.1.1.1"; + // String result = operations.search(ip); + IpLocation ipLocation = operations.find(ip); + if (ipLocation != null) { + model.setIpCountry(ipLocation.getCountry()); + model.setIpProvince(ipLocation.getProvince()); + model.setIpCity(ipLocation.getCity()); + model.setIpArea(ipLocation.getArea()); + model.setIpIsp(ipLocation.getIsp()); + } + } +} + +// 方式二 + +/** + * 直接声明 IpSearcher 组件,该方法代码更少可维护性不强 + */ +@Configuration +public class AppConfig { + + @Bean + static IpSearcher ipSearcher() { + return IpSearcher.forDefaultResourceLocation(); + } + +} + +/** + * 调用端直接使用依赖注入 + */ +@Component +public class Client { + + final IpSearcher ipSearcher; + + Client(IpSearcher ipSearcher) { + this.ipSearcher = ipSearcher; + } + + public void test() { + String ip = "1.1.1.1"; + // String result = ipSearcher.search(ip); + IpLocation ipLocation = ipSearcher.find(ip); + if (ipLocation != null) { + model.setIpCountry(ipLocation.getCountry()); + model.setIpProvince(ipLocation.getProvince()); + model.setIpCity(ipLocation.getCity()); + model.setIpArea(ipLocation.getArea()); + model.setIpIsp(ipLocation.getIsp()); + } + } +} ``` ## 🙏 鸣谢 本项目的诞生离不开以下项目: + * [Ip2region](https://github.com/lionsoul2014/ip2region) 核心算法代码 * [Jetbrains](https://www.jetbrains.com/?from=https://github.com/TAKETODAY/ip2region-java) 感谢 Jetbrains 提供免费开源授权