Compare commits
19
Commits
51eb838a36
...
5.7.2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
53e30351a7
|
||
|
|
d43f273aa7
|
||
|
|
838a03560e
|
||
|
|
c169064637
|
||
|
|
ae41240806
|
||
|
|
cb7fdb4f19
|
||
|
|
3d1896bd64
|
||
|
|
0e0d2b03cc
|
||
|
|
2e54e3d651
|
||
|
|
528802d881
|
||
|
|
487f956f4f
|
||
|
|
64e3af50ed
|
||
|
|
7760201639
|
||
|
|
713342bbc6
|
||
|
|
988a0c0dc1
|
||
|
|
44ea9b114d
|
||
|
|
3bacf90940
|
||
|
|
28a2987dc3
|
||
|
|
8069de37f2
|
+1
-1
@@ -43,6 +43,6 @@ bin/
|
|||||||
log
|
log
|
||||||
.idea
|
.idea
|
||||||
node_modules
|
node_modules
|
||||||
*lock*
|
*.lock
|
||||||
.kotlin
|
.kotlin
|
||||||
secret.gpg
|
secret.gpg
|
||||||
|
|||||||
+147
-1
@@ -1,10 +1,150 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
本文件记录 mingli-utils 各版本的主要变更。
|
本文件记录 mingli-utils 各版本的主要变更。
|
||||||
|
|
||||||
|
## [5.7.2] - 2026-11-23
|
||||||
|
|
||||||
|
### 新增
|
||||||
|
|
||||||
|
- **spring**:新增 `@FastServiceScan` 注解及 `FastServiceScanRegistrar`、
|
||||||
|
`FastServiceScannerProcessor`——扫描继承 `FastBaseIService` 或 `FastBaseIServiceNew3518`
|
||||||
|
的具体类并注册为 Spring Bean;仅在启动类/配置类标注该注解时生效,扫描时机在所有
|
||||||
|
`BeanDefinitionRegistryPostProcessor`(包括 `@MapperScan` 的 `MapperScannerConfigurer`)之后。
|
||||||
|
支持 `value` / `basePackages` / `basePackageClasses`,`value` 与 `basePackages` 通过
|
||||||
|
`@AliasFor` 互为别名;未指定包时使用标注类所在包;已标注 `@Component` / `@Service`
|
||||||
|
的类自动跳过,避免重复注册。
|
||||||
|
- **test**:新增 `FastServiceScanRegistrarTest`(5 个用例)与
|
||||||
|
`FastServiceScannerProcessorTest`(2 个用例,覆盖两个基类与某个基类缺失时的跳过逻辑)。
|
||||||
|
|
||||||
|
### 变更
|
||||||
|
|
||||||
|
- **spring**:`ApplicationDestroyedRunner`、`ApplicationReadyEventListener`、
|
||||||
|
`ApplicationStartedRunner`、`ContextClosedEventListener` 由 Java 迁移为 Kotlin 实现,
|
||||||
|
包名、属性及 `@AliasFor` 关系保持不变。
|
||||||
|
- **spring**:`ApplicationDestroyedRunner` / `ApplicationStartedRunner` 补全
|
||||||
|
`@Deprecated` + `ReplaceWith`,IDE 可一键替换为 `ContextClosedEventListener` /
|
||||||
|
`ApplicationReadyEventListener`;旧 Java 版本只有 `@Deprecated(since = ...)`。
|
||||||
|
- **build**:新增 `VERSIONSTYPE`(`r` = RELEASES,`s` = SNAPSHOT)控制版本后缀;
|
||||||
|
补充 Spring / MyBatis-Plus 测试依赖。
|
||||||
|
|
||||||
|
### 修复
|
||||||
|
|
||||||
|
- **spring**:`FastServiceScannerProcessor` 改为按类名探测两个服务基类,
|
||||||
|
仅引入一套 MyBatis-Plus 时只跳过缺失的基类,不再因类字面量加载父类失败抛出
|
||||||
|
`NoClassDefFoundError`。
|
||||||
|
|
||||||
|
### 注意
|
||||||
|
|
||||||
|
- 事件监听注解的 `defaultExecution` 属性仅在 Spring Framework 6.2+ 中提供;
|
||||||
|
在 Spring 5.3 下解析这些组合注解会抛出 `AnnotationConfigurationException`,使用方需按实际
|
||||||
|
Spring 版本选择。
|
||||||
|
|
||||||
|
## [5.7.0] - 2026-11-23
|
||||||
|
|
||||||
|
### 新增
|
||||||
|
|
||||||
|
- **lock**:新增 `RedisLock` Redis 分布式锁工具——基于 Redisson 异步 API 实现协程挂起式加锁,
|
||||||
|
等待期间不占用线程;默认启用看门狗自动续期,支持公平锁、自定义 key 前缀与固定租期;
|
||||||
|
提供 `withLock`(等待获取)与 `tryWithLock`(抢不到立即返回 `null`);
|
||||||
|
新增 `RedisLockTimeoutException`。Redisson 为可选依赖(`compileOnly`),
|
||||||
|
使用方需自行引入(建议 Redisson 3.13+ / 4.x)。
|
||||||
|
|
||||||
|
### 变更
|
||||||
|
|
||||||
|
- **build**:`build.gradle.kts` 与 `settings.gradle.kts` 移除已废弃的 `project.properties`、
|
||||||
|
`settings.extra` 委托写法,改用 `providers.gradleProperty` 与显式访问器;
|
||||||
|
`processResources` 的模板展开改为显式变量表,消除 Gradle 9 的配置期弃用警告。
|
||||||
|
- **build**:`.gitignore` 的 `*lock*` 规则改为 `*.lock`,避免把新增的 `lock` 包整体忽略。
|
||||||
|
|
||||||
|
### 测试
|
||||||
|
|
||||||
|
- 新增 `RedisLockTest`(7 个用例),通过动态代理模拟 Redisson 客户端,
|
||||||
|
覆盖正常加锁释放、等待超时、跳过执行、公平锁、业务异常仍释放、wait/lease 透传。
|
||||||
|
|
||||||
|
## [5.6.0] - 2026-11-23
|
||||||
|
|
||||||
|
### 新增
|
||||||
|
|
||||||
|
- **thread**:新增 `SuspendUtils` 协程工具——`CoroutineContext.withContext`、
|
||||||
|
`CoroutineContext.runBlocking`(按接收者上下文执行)与顶层 `runBlocking`
|
||||||
|
(使用调用线程的事件循环)、`asCompletableDeferred`。
|
||||||
|
- **thread**:`GlobalThreadPool` 新增 `mainDispatcher` / `ioDispatcher` / `cpuDispatcher`、
|
||||||
|
`pools()`、`snapshotAll()`、`isShutdown`,并自动注册 JVM 关闭钩子——
|
||||||
|
进程正常退出时优雅关闭全部池(最多等待 5 秒,超时强制关闭)。
|
||||||
|
- **thread**:`runAsync` / `callAsync` / `computeAsync` / `runAsyncAwait` / `callAsyncAwait`
|
||||||
|
移入 `GlobalThreadPool` 并加 `@JvmStatic`;参数改为 `Runnable` / `Callable`,
|
||||||
|
Kotlin 与 Java 均可直接使用 lambda。
|
||||||
|
- **thread**:新增 `namedThreadFactory`;`ioThreadPool` / `cpuThreadPool` /
|
||||||
|
`scheduledThreadPool` 增加 `daemon` 与 `rejectedHandler` 参数。
|
||||||
|
- **collection**:新增 `newArrayDeque()` 的三个重载。
|
||||||
|
|
||||||
|
### 变更
|
||||||
|
|
||||||
|
- **thread**:重构 `GlobalThreadPool`——main / io / cpu / scheduled 统一守护线程与池配置;
|
||||||
|
`shutdownAll` 覆盖全部池、改用统一截止时间、幂等、超时 `shutdownNow` 并返回是否正常终止;
|
||||||
|
全局池关闭后提交任务抛出 `RejectedExecutionException`;scheduled 开启 `removeOnCancelPolicy`、
|
||||||
|
关闭时丢弃未到期延迟任务;补充池与调度器初始化、拒绝策略、关闭流程及关闭钩子的 Debug 日志。
|
||||||
|
- **thread**:`mainDispatcher` / `ioDispatcher` 复用 kotlinx-coroutines 共享调度器
|
||||||
|
(命名限流视图),`cpuDispatcher` 绑定独立 cpu 池;`ThreadPoolBuilder` 抽出
|
||||||
|
`namedThreadFactory` 供各线程池复用。
|
||||||
|
- **stream**:`SuperStream.toArray` 返回类型补充 jspecify `@NonNull`;
|
||||||
|
`Collection.toArray` 泛型收紧为 `T : Any`。
|
||||||
|
- 移除 `ForEach`;更新依赖与版权年份。
|
||||||
|
|
||||||
|
### 修复
|
||||||
|
|
||||||
|
- **thread**:`CoroutineContext.runBlocking` 未使用接收者上下文,行为与普通 `runBlocking` 相同。
|
||||||
|
- **thread**:全局池关闭后任务被静默丢弃、`submit` 返回永不完成 `Future` 的问题。
|
||||||
|
|
||||||
|
### 测试
|
||||||
|
|
||||||
|
- 新增 `SuspendUtilsTest`;补充 `AsyncTasksTest` 中全局池、调度器与关闭钩子相关用例。
|
||||||
|
|
||||||
|
## [5.5.4] - 2026-11-18
|
||||||
|
|
||||||
|
### 新增
|
||||||
|
|
||||||
|
- **hash**:新增 `HashCodec` 哈希编解码器接口——实现类只需重写 `hash(InputStream)` 一个方法,
|
||||||
|
字节数组/字符串/文件/路径重载、十六进制输出(`hashHex`)与基于 `MessageDigest.isEqual`
|
||||||
|
的常量时间校验(`verifyHash`)均由默认实现提供;新增 `MessageDigestCodec` 流式基类
|
||||||
|
(8KB 缓冲、恒定内存、不关闭调用方流)及 13 种 JDK 标准算法实现
|
||||||
|
(MD2、MD5、SHA-1、SHA-224/256/384/512、SHA-512/224、SHA-512/256、SHA3-224/256/384/512);
|
||||||
|
提供 `HashUtils` 懒加载单例(`MD2`~`SHA512256`)与 `HashType` 枚举;
|
||||||
|
新增 `TestHash` 测试覆盖已知向量、全部算法一致性、流生命周期与文件/路径重载。
|
||||||
|
- **test**:新增非官方 Log4j2 配置 XSD(覆盖 21 种 Appender、13 种 Layout、11 种 Filter、
|
||||||
|
滚动策略与清理条件等,未知插件元素以开放内容模型放行),`log4j2.xml` 接入 Schema 校验。
|
||||||
|
|
||||||
|
### 变更
|
||||||
|
|
||||||
|
- **springboot**:事件监听注解迁移为 Java 实现——新增 `ApplicationReadyEventListener`、
|
||||||
|
`ContextClosedEventListener`;`ApplicationStartedRunner`、`ApplicationDestroyedRunner`
|
||||||
|
标记为废弃;移除 Kotlin 版注解及 `ApplicationListener`、`ApplicationRunnerData`;
|
||||||
|
`Okhttp3AutoConfiguration` 改用 `@ContextClosedEventListener`。
|
||||||
|
- **http**:`MediaType` 枚举项之间补充空行(纯格式化,无内容变更)。
|
||||||
|
|
||||||
|
### 修复
|
||||||
|
|
||||||
|
- **build**:修正 `signing.secretKeyRingFile` 属性名笔误(误插入空格)。
|
||||||
|
|
||||||
|
### 文档
|
||||||
|
|
||||||
|
- hash 包全部接口、类、枚举与懒加载单例补全中文 KDoc;
|
||||||
|
4 个 Spring Boot 事件监听注解补全 Javadoc。
|
||||||
|
|
||||||
|
## [5.5.2] - 2026-11-17
|
||||||
|
|
||||||
|
### 新增
|
||||||
|
|
||||||
|
- **tuple**:实现 `Tuple.compareTo` 字典序比较——同类型可比较元素按自然顺序,
|
||||||
|
其余按字符串形式比较;公共前缀相等时元素个数较少的元组在前。
|
||||||
|
新增 `TestTuple` 测试覆盖 6 种比较场景。
|
||||||
|
|
||||||
## [5.5.1] - 2026-11-17
|
## [5.5.1] - 2026-11-17
|
||||||
|
|
||||||
### 新增
|
### 新增
|
||||||
|
|
||||||
- **json**:新增 `reader` / `witer` / `judgment` 三组抽象,为 Jackson2 与 Jackson3 分别提供
|
- **json**:新增 `reader` / `witer` / `judgment` 三组抽象,为 Jackson2 与 Jackson3 分别提供
|
||||||
`JsonReader`、`JsonArrayReader`、`JsonObjectReader`、`JsonWriter`、`ArrayWriter`、`ObjectWriter`
|
`JsonReader`、`JsonArrayReader`、`JsonObjectReader`、`JsonWriter`、`ArrayWriter`、`ObjectWriter`
|
||||||
与 `ReaderJudgment` 实现(`BaseJsonReader` / `BaseJsonWriter` / `BaseJsonJudgment` 等基类)。
|
与 `ReaderJudgment` 实现(`BaseJsonReader` / `BaseJsonWriter` / `BaseJsonJudgment` 等基类)。
|
||||||
@@ -13,32 +153,38 @@
|
|||||||
`toString()` 输出包含 `zoneId`。
|
`toString()` 输出包含 `zoneId`。
|
||||||
|
|
||||||
### 变更
|
### 变更
|
||||||
|
|
||||||
- **json**:重构转换器体系——移除按类型划分的 `BaseJsonIntConverter`、`BaseJsonStringConverter`
|
- **json**:重构转换器体系——移除按类型划分的 `BaseJsonIntConverter`、`BaseJsonStringConverter`
|
||||||
等 10 个转换器及 `JsonConverter` 接口,统一由 `BaseJsonConverter` 与 `JsonConverterUtils` 处理;
|
等 10 个转换器及 `JsonConverter` 接口,统一由 `BaseJsonConverter` 与 `JsonConverterUtils` 处理;
|
||||||
简化 `DateTimeJsonConverter`、`UUIDJsonConverter`、`NetworkEndpointJsonConverter` 与
|
简化 `DateTimeJsonConverter`、`UUIDJsonConverter`、`NetworkEndpointJsonConverter` 与
|
||||||
Jackson2/Jackson3 序列化/反序列化桥接实现;精简 `JSONA` 与 `JsonApi` 门面。
|
Jackson2/Jackson3 序列化/反序列化桥接实现;精简 `JSONA` 与 `JsonApi` 门面。
|
||||||
- **tuple**:`Tuple` 实现 `Comparable<Tuple>`,迭代器改为基于 `toMutableList()` 的简化实现。
|
- **tuple**:`Tuple` 声明实现 `Comparable<Tuple>`;迭代器改为基于 `toMutableList()` 的简化实现。
|
||||||
- **springboot**:`JsonAutoConfiguration` 与 `JacksonJsonBuilder` / `JacksonJsonBuilderImpl`
|
- **springboot**:`JsonAutoConfiguration` 与 `JacksonJsonBuilder` / `JacksonJsonBuilderImpl`
|
||||||
同步适配新的 JSON 转换器体系。
|
同步适配新的 JSON 转换器体系。
|
||||||
|
|
||||||
### 文档
|
### 文档
|
||||||
|
|
||||||
- 补全 src 下全部 Kotlin 文件的中文 KDoc 与 Java 文件的 Javadoc(约 1.3 万处),
|
- 补全 src 下全部 Kotlin 文件的中文 KDoc 与 Java 文件的 Javadoc(约 1.3 万处),
|
||||||
覆盖 exception、json、springboot、mybatis/mybatisplus、thread/netty/http、
|
覆盖 exception、json、springboot、mybatis/mybatisplus、thread/netty/http、
|
||||||
Tuple1~Tuple100 生成类、MediaType 全部枚举项及测试代码;已有文档保持不变。
|
Tuple1~Tuple100 生成类、MediaType 全部枚举项及测试代码;已有文档保持不变。
|
||||||
|
|
||||||
## [5.4.4] - 2026-11-17
|
## [5.4.4] - 2026-11-17
|
||||||
|
|
||||||
- 构建脚本调整(build.gradle.kts 发布配置完善)。
|
- 构建脚本调整(build.gradle.kts 发布配置完善)。
|
||||||
- SpringBoot 自动配置重构:新增 `JsonAutoConfiguration` 与 `JacksonBuilder`,
|
- SpringBoot 自动配置重构:新增 `JsonAutoConfiguration` 与 `JacksonBuilder`,
|
||||||
精简 Jackson2/Jackson3 JsonApi 自动配置。
|
精简 Jackson2/Jackson3 JsonApi 自动配置。
|
||||||
|
|
||||||
## [5.4.3] - 2026-11-17
|
## [5.4.3] - 2026-11-17
|
||||||
|
|
||||||
- 新增 `JacksonJsonBuilder` / `JacksonJsonBuilderImpl` 构建器。
|
- 新增 `JacksonJsonBuilder` / `JacksonJsonBuilderImpl` 构建器。
|
||||||
- `DateTime`、`UUID` 小幅调整;补充 log4j2 测试配置。
|
- `DateTime`、`UUID` 小幅调整;补充 log4j2 测试配置。
|
||||||
|
|
||||||
## [5.4.2] - 2026-11
|
## [5.4.2] - 2026-11
|
||||||
|
|
||||||
- 修复 `JSONA.jsonApi` 编译错误。
|
- 修复 `JSONA.jsonApi` 编译错误。
|
||||||
- **mybatisplus**:新增 `FastBaseIServiceNew3518`(适配 MyBatis-Plus 3.5.18)。
|
- **mybatisplus**:新增 `FastBaseIServiceNew3518`(适配 MyBatis-Plus 3.5.18)。
|
||||||
|
|
||||||
## [5.4.0] - 2026-11
|
## [5.4.0] - 2026-11
|
||||||
|
|
||||||
- **mybatisplus**:新增 `FastBaseIService`。
|
- **mybatisplus**:新增 `FastBaseIService`。
|
||||||
- 全项目统一 Tab 缩进并补全尾随逗号。
|
- 全项目统一 Tab 缩进并补全尾随逗号。
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
mingli-utils
|
mingli-utils
|
||||||
Copyright 2025 mingliqiye
|
Copyright 2026 mingliqiye
|
||||||
|
|
||||||
This product includes software developed by third parties.
|
This product includes software developed by third parties.
|
||||||
The original copyright notices and licenses are reproduced below.
|
The original copyright notices and licenses are reproduced below.
|
||||||
|
|||||||
+24
-9
@@ -16,13 +16,12 @@
|
|||||||
* ProjectName mingli-utils
|
* ProjectName mingli-utils
|
||||||
* ModuleName mingli-utils
|
* ModuleName mingli-utils
|
||||||
* CurrentFile build.gradle.kts
|
* CurrentFile build.gradle.kts
|
||||||
* LastUpdate 2026-11-17 10:19:02
|
* LastUpdate 2026-11-23 15:17:59
|
||||||
* UpdateUser MingLiPro
|
* UpdateUser MingLiPro
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import java.time.LocalDateTime
|
import java.time.LocalDateTime
|
||||||
import java.time.format.DateTimeFormatter
|
import java.time.format.DateTimeFormatter
|
||||||
import kotlin.math.sign
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Copyright 2026 mingliqiye
|
* Copyright 2026 mingliqiye
|
||||||
@@ -60,11 +59,13 @@ plugins {
|
|||||||
id("org.jetbrains.dokka-javadoc") version "2.1.0"
|
id("org.jetbrains.dokka-javadoc") version "2.1.0"
|
||||||
kotlin("plugin.spring") version "2.1.0"
|
kotlin("plugin.spring") version "2.1.0"
|
||||||
}
|
}
|
||||||
val GROUPSID = project.properties["GROUPSID"] as String
|
val GROUPSID = providers.gradleProperty("GROUPSID").get()
|
||||||
val VERSIONS = project.properties["VERSIONS"] as String
|
val VERSION = providers.gradleProperty("VERSIONS").get()
|
||||||
val ARTIFACTID = project.properties["ARTIFACTID"] as String
|
val ARTIFACTID = providers.gradleProperty("ARTIFACTID").get()
|
||||||
val JDKVERSIONS = (project.properties["JDKVERSIONS"] as String).toInt()
|
val JDKVERSIONS = providers.gradleProperty("JDKVERSIONS").get().toInt()
|
||||||
|
val VERSIONSTYPE = providers.gradleProperty("VERSIONSTYPE").get()
|
||||||
|
val VERSIONS =
|
||||||
|
VERSION + if (VERSIONSTYPE == "s") "-SNAPSHOT" else if (VERSIONSTYPE == "r") "" else error("VERSIONSTYPE is not supported in gradle.properties $VERSIONSTYPE")
|
||||||
|
|
||||||
group = GROUPSID
|
group = GROUPSID
|
||||||
version = VERSIONS
|
version = VERSIONS
|
||||||
@@ -112,8 +113,18 @@ dependencies {
|
|||||||
compileOnly("com.baomidou:mybatis-plus-extension:3.5.15")
|
compileOnly("com.baomidou:mybatis-plus-extension:3.5.15")
|
||||||
compileOnly("com.baomidou:mybatis-plus-jsqlparser:3.5.15")
|
compileOnly("com.baomidou:mybatis-plus-jsqlparser:3.5.15")
|
||||||
compileOnly("com.baomidou:mybatis-plus-spring:3.5.9")
|
compileOnly("com.baomidou:mybatis-plus-spring:3.5.9")
|
||||||
|
compileOnly("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2")
|
||||||
|
compileOnly("org.jetbrains.kotlinx:kotlinx-coroutines-reactor:1.10.2")
|
||||||
|
compileOnly("org.redisson:redisson:4.8.0")
|
||||||
testImplementation("org.junit.jupiter:junit-jupiter:5.7.1")
|
testImplementation("org.junit.jupiter:junit-jupiter:5.7.1")
|
||||||
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
|
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
|
||||||
|
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2")
|
||||||
|
testImplementation(fileTree("libs"))
|
||||||
|
testImplementation("com.baomidou:mybatis-plus-core:3.5.15")
|
||||||
|
testImplementation("com.baomidou:mybatis-plus-extension:3.5.15")
|
||||||
|
testImplementation("com.baomidou:mybatis-plus-spring:3.5.9")
|
||||||
|
testImplementation("org.springframework:spring-context:5.3.39")
|
||||||
|
testImplementation("org.redisson:redisson:4.8.0")
|
||||||
testImplementation("com.mingliqiye.logger:logger-log4j2:1.0.9")
|
testImplementation("com.mingliqiye.logger:logger-log4j2:1.0.9")
|
||||||
testImplementation("com.google.code.gson:gson:2.13.2")
|
testImplementation("com.google.code.gson:gson:2.13.2")
|
||||||
|
|
||||||
@@ -253,12 +264,16 @@ tasks.processResources {
|
|||||||
outputs.upToDateWhen { false }
|
outputs.upToDateWhen { false }
|
||||||
filesMatching(listOf("META-INF/meta-data", "fabric.mod.json")) {
|
filesMatching(listOf("META-INF/meta-data", "fabric.mod.json")) {
|
||||||
expand(
|
expand(
|
||||||
project.properties + mapOf(
|
mapOf(
|
||||||
|
"GROUPSID" to GROUPSID,
|
||||||
|
"ARTIFACTID" to ARTIFACTID,
|
||||||
|
"VERSIONS" to VERSIONS,
|
||||||
|
"JDKVERSIONS" to JDKVERSIONS,
|
||||||
"buildTime" to LocalDateTime.now().format(
|
"buildTime" to LocalDateTime.now().format(
|
||||||
DateTimeFormatter.ofPattern(
|
DateTimeFormatter.ofPattern(
|
||||||
"yyyy-MM-dd HH:mm:ss.SSSSSSS"
|
"yyyy-MM-dd HH:mm:ss.SSSSSSS"
|
||||||
)
|
)
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-2
@@ -16,10 +16,13 @@
|
|||||||
# ProjectName mingli-utils
|
# ProjectName mingli-utils
|
||||||
# ModuleName mingli-utils
|
# ModuleName mingli-utils
|
||||||
# CurrentFile gradle.properties
|
# CurrentFile gradle.properties
|
||||||
# LastUpdate 2026-11-17 09:07:20
|
# LastUpdate 2026-11-23 15:24:00
|
||||||
# UpdateUser MingLiPro
|
# UpdateUser MingLiPro
|
||||||
#
|
#
|
||||||
JDKVERSIONS=17
|
JDKVERSIONS=17
|
||||||
GROUPSID=com.mingliqiye.utils
|
GROUPSID=com.mingliqiye.utils
|
||||||
ARTIFACTID=mingli-utils
|
ARTIFACTID=mingli-utils
|
||||||
VERSIONS=5.5.1
|
# r = RELEASES
|
||||||
|
# s = SNAPSHOT
|
||||||
|
VERSIONSTYPE=r
|
||||||
|
VERSIONS=5.7.2
|
||||||
|
|||||||
+2
-2
@@ -16,7 +16,7 @@
|
|||||||
* ProjectName mingli-utils
|
* ProjectName mingli-utils
|
||||||
* ModuleName mingli-utils
|
* ModuleName mingli-utils
|
||||||
* CurrentFile settings.gradle.kts
|
* CurrentFile settings.gradle.kts
|
||||||
* LastUpdate 2026-02-26 10:52:01
|
* LastUpdate 2026-11-23 10:23:56
|
||||||
* UpdateUser MingLiPro
|
* UpdateUser MingLiPro
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@@ -24,7 +24,7 @@ plugins {
|
|||||||
id("com.gradleup.nmcp.settings").version("1.4.4")
|
id("com.gradleup.nmcp.settings").version("1.4.4")
|
||||||
}
|
}
|
||||||
|
|
||||||
val ARTIFACTID: String by settings.extra
|
val ARTIFACTID = settings.extra["ARTIFACTID"] as String
|
||||||
rootProject.name = ARTIFACTID
|
rootProject.name = ARTIFACTID
|
||||||
|
|
||||||
nmcpSettings {
|
nmcpSettings {
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.main
|
||||||
|
* CurrentFile FastServiceScan.java
|
||||||
|
* LastUpdate 2026-11-23 14:44:48
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.springboot.annotation;
|
||||||
|
|
||||||
|
import com.mingliqiye.utils.springboot.autoconfigure.FastServiceScanRegistrar;
|
||||||
|
import org.springframework.context.annotation.Import;
|
||||||
|
import org.springframework.core.annotation.AliasFor;
|
||||||
|
|
||||||
|
import java.lang.annotation.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 扫描继承自 {@code com.mingliqiye.utils.mybatisplus.FastBaseIService} 或
|
||||||
|
* {@code com.mingliqiye.utils.mybatisplus.FastBaseIServiceNew3518} 的具体类并注册为 Spring Bean。
|
||||||
|
* 两个基类分别对应旧版 {@code mybatis-plus-extension} 与新版 {@code mybatis-plus-spring},
|
||||||
|
* 子类都会被扫描到;行为与 {@code @MapperScan} 类似:只有标注了本注解的启动类/配置类才会触发扫描。
|
||||||
|
*
|
||||||
|
* <p>扫描由 {@link FastServiceScanRegistrar} 注册的
|
||||||
|
* {@code com.mingliqiye.utils.springboot.autoconfigure.FastServiceScannerProcessor} 完成,
|
||||||
|
* 后者是 {@code BeanFactoryPostProcessor},会在所有 {@code BeanDefinitionRegistryPostProcessor}
|
||||||
|
* (包括 {@code @MapperScan} 的 {@code MapperScannerConfigurer})之后执行,
|
||||||
|
* 因此扫描注册时机在 mapper 之后,服务里的 {@code baseMapper} 可以正常注入。</p>
|
||||||
|
*
|
||||||
|
* <p>已经标注 {@code @Component} / {@code @Service} 的类会被跳过,交给普通组件扫描处理,避免重复注册。</p>
|
||||||
|
*
|
||||||
|
* <p>Java 用法:</p>
|
||||||
|
* <pre>{@code
|
||||||
|
* @SpringBootApplication
|
||||||
|
* @MapperScan(basePackages = "com.example.mapper")
|
||||||
|
* @FastServiceScan(basePackages = "com.example.service")
|
||||||
|
* public class ExampleApplication {
|
||||||
|
* }
|
||||||
|
* }</pre>
|
||||||
|
*
|
||||||
|
* <p>Kotlin 用法:</p>
|
||||||
|
* <pre>{@code
|
||||||
|
* @SpringBootApplication
|
||||||
|
* @MapperScan(basePackages = ["com.example.mapper"])
|
||||||
|
* @FastServiceScan(basePackages = ["com.example.service"])
|
||||||
|
* class ExampleApplication
|
||||||
|
* }</pre>
|
||||||
|
*
|
||||||
|
* <p>不指定扫描包时,默认扫描标注类所在包。</p>
|
||||||
|
* <p>{@code Kotlin} 请指定 {@code Service} 为 {@code open}</p>
|
||||||
|
*/
|
||||||
|
@Target(ElementType.TYPE)
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
@Documented
|
||||||
|
@Import(FastServiceScanRegistrar.class)
|
||||||
|
public @interface FastServiceScan {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 要扫描的包,等价于 {@link #basePackages()}。
|
||||||
|
*
|
||||||
|
* @return 要扫描的包
|
||||||
|
*/
|
||||||
|
@AliasFor("basePackages")
|
||||||
|
String[] value() default {};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 要扫描的包。
|
||||||
|
*
|
||||||
|
* @return 要扫描的包
|
||||||
|
*/
|
||||||
|
|
||||||
|
@AliasFor("value")
|
||||||
|
String[] basePackages() default {};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 以这些类所在包作为扫描包。
|
||||||
|
*
|
||||||
|
* @return 用于推导扫描包的类
|
||||||
|
*/
|
||||||
|
Class<?>[] basePackageClasses() default {};
|
||||||
|
}
|
||||||
@@ -13,10 +13,10 @@
|
|||||||
* See the License for the specific language governing permissions and
|
* See the License for the specific language governing permissions and
|
||||||
* limitations under the License.
|
* limitations under the License.
|
||||||
*
|
*
|
||||||
* ProjectName FastBaseMapper.kt
|
* ProjectName mingli-utils
|
||||||
* ModuleName mingli-utils.main
|
* ModuleName mingli-utils.main
|
||||||
* CurrentFile SuperStream.java
|
* CurrentFile SuperStream.java
|
||||||
* LastUpdate 2026-10-26 23:22:18
|
* LastUpdate 2026-11-22 10:10:33
|
||||||
* UpdateUser MingLiPro
|
* UpdateUser MingLiPro
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@@ -26,6 +26,7 @@ import com.mingliqiye.utils.collection.Collections;
|
|||||||
import com.mingliqiye.utils.functions.P1Function;
|
import com.mingliqiye.utils.functions.P1Function;
|
||||||
import com.mingliqiye.utils.functions.P2Function;
|
import com.mingliqiye.utils.functions.P2Function;
|
||||||
import org.jetbrains.annotations.NotNull;
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
import org.jspecify.annotations.NonNull;
|
||||||
|
|
||||||
import java.lang.reflect.Array;
|
import java.lang.reflect.Array;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
@@ -987,7 +988,7 @@ public class SuperStream<T> implements Stream<T> {
|
|||||||
*/
|
*/
|
||||||
@NotNull
|
@NotNull
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
public T[] toArray(Class<T> clazz) {
|
public T @NonNull [] toArray(Class<T> clazz) {
|
||||||
return stream.toArray(i -> (T[]) Array.newInstance(clazz, i));
|
return stream.toArray(i -> (T[]) Array.newInstance(clazz, i));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -997,7 +998,7 @@ public class SuperStream<T> implements Stream<T> {
|
|||||||
* @return 转换后的Object数组
|
* @return 转换后的Object数组
|
||||||
*/
|
*/
|
||||||
@NotNull
|
@NotNull
|
||||||
public Object[] toArray() {
|
public Object @NonNull [] toArray() {
|
||||||
return stream.toArray();
|
return stream.toArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2025 mingliqiye
|
* Copyright 2026 mingliqiye
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@@ -16,7 +16,7 @@
|
|||||||
* ProjectName mingli-utils
|
* ProjectName mingli-utils
|
||||||
* ModuleName mingli-utils.main
|
* ModuleName mingli-utils.main
|
||||||
* CurrentFile Collection.kt
|
* CurrentFile Collection.kt
|
||||||
* LastUpdate 2025-09-21 14:36:57
|
* LastUpdate 2026-11-23 07:33:23
|
||||||
* UpdateUser MingLiPro
|
* UpdateUser MingLiPro
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@@ -745,6 +745,38 @@ fun <T> newStack(elements: Collection<T>): Stack<T> {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建一个新的 ArrayDeque 实例。
|
||||||
|
*
|
||||||
|
* @param T 元素类型
|
||||||
|
* @return 新创建的 ArrayDeque
|
||||||
|
*/
|
||||||
|
fun <T> newArrayDeque(): ArrayDeque<T> {
|
||||||
|
return ArrayDeque()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 使用可变参数创建一个新的 ArrayDeque 实例。
|
||||||
|
*
|
||||||
|
* @param T 元素类型
|
||||||
|
* @param elements 可变参数列表
|
||||||
|
* @return 新创建的 ArrayDeque
|
||||||
|
*/
|
||||||
|
fun <T> newArrayDeque(vararg elements: T): ArrayDeque<T> {
|
||||||
|
return newArrayDeque(elements.toList())
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将集合转换为新的 ArrayDeque 实例。
|
||||||
|
*
|
||||||
|
* @param T 元素类型
|
||||||
|
* @param elements 输入集合
|
||||||
|
* @return 新创建的 ArrayDeque
|
||||||
|
*/
|
||||||
|
fun <T> newArrayDeque(elements: Collection<T>): ArrayDeque<T> {
|
||||||
|
return ArrayDeque(elements)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建一个新的 TreeSet 实例,并指定比较器。
|
* 创建一个新的 TreeSet 实例,并指定比较器。
|
||||||
*
|
*
|
||||||
@@ -980,9 +1012,9 @@ fun toArray(list: List<Char>): CharArray {
|
|||||||
* @param list 输入的 List
|
* @param list 输入的 List
|
||||||
* @return 转换后的数组
|
* @return 转换后的数组
|
||||||
*/
|
*/
|
||||||
inline fun <reified T> toArray(list: List<T>): Array<T> {
|
inline fun <reified T : Any> toArray(list: List<T>): Array<T> {
|
||||||
if (list.isEmpty())
|
if (list.isEmpty())
|
||||||
return arrayOf<T>()
|
return arrayOf()
|
||||||
return SuperStream.of<T>(list)
|
return SuperStream.of<T>(list)
|
||||||
.toArray(T::class.java)
|
.toArray(T::class.java)
|
||||||
}
|
}
|
||||||
@@ -995,7 +1027,7 @@ inline fun <reified T> toArray(list: List<T>): Array<T> {
|
|||||||
* @param clazz 数组元素类型对应的 Class 对象
|
* @param clazz 数组元素类型对应的 Class 对象
|
||||||
* @return 转换后的数组
|
* @return 转换后的数组
|
||||||
*/
|
*/
|
||||||
fun <T> toArray(list: List<T>, clazz: Class<T>): Array<T> {
|
fun <T : Any> toArray(list: List<T>, clazz: Class<T>): Array<T> {
|
||||||
return SuperStream.of<T>(list)
|
return SuperStream.of<T>(list)
|
||||||
.toArray(clazz)
|
.toArray(clazz)
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-15
@@ -15,25 +15,20 @@
|
|||||||
*
|
*
|
||||||
* ProjectName mingli-utils
|
* ProjectName mingli-utils
|
||||||
* ModuleName mingli-utils.main
|
* ModuleName mingli-utils.main
|
||||||
* CurrentFile Listener.kt
|
* CurrentFile RedisLockTimeoutException.kt
|
||||||
* LastUpdate 2026-03-10 09:04:02
|
* LastUpdate 2026-11-23 10:21:41
|
||||||
* UpdateUser MingLiPro
|
* UpdateUser MingLiPro
|
||||||
*/
|
*/
|
||||||
|
|
||||||
package com.mingliqiye.utils.springboot.annotation
|
package com.mingliqiye.utils.exception
|
||||||
|
|
||||||
import org.springframework.core.annotation.AliasFor
|
|
||||||
import org.springframework.stereotype.Component
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 监听器组件注解,组合了 [Component] 的语义。
|
* Redis 分布式锁等待超时异常。
|
||||||
* 被标注的类会被组件扫描注册为 Spring Bean,
|
|
||||||
* [value] 通过 [AliasFor] 别名到 [Component.value],用于指定 Bean 名称。
|
|
||||||
*
|
*
|
||||||
* @property value Bean 名称,默认为空字符串(由 Spring 按类名生成)
|
* @param lockKey 未获取到的完整锁 key(含前缀)
|
||||||
|
* @param waitMillis 等待时长(毫秒)
|
||||||
*/
|
*/
|
||||||
@Component
|
class RedisLockTimeoutException(
|
||||||
annotation class Listener(
|
val lockKey: String,
|
||||||
@get:AliasFor(annotation = Component::class)
|
val waitMillis: Long,
|
||||||
val value: String = "",
|
) : MingLiUtilsBaseException("获取 Redis 分布式锁超时: $lockKey,等待 ${waitMillis}ms")
|
||||||
)
|
|
||||||
@@ -1,707 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2026 mingliqiye
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*
|
|
||||||
* ProjectName mingli-utils
|
|
||||||
* ModuleName mingli-utils.main
|
|
||||||
* CurrentFile ForEach.kt
|
|
||||||
* LastUpdate 2026-02-27 12:45:39
|
|
||||||
* UpdateUser MingLiPro
|
|
||||||
*/
|
|
||||||
@file:JvmName("ForEach")
|
|
||||||
|
|
||||||
package com.mingliqiye.utils.foreach
|
|
||||||
|
|
||||||
import com.mingliqiye.utils.functions.*
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的可迭代对象执行指定的操作,同时处理元素值和索引。
|
|
||||||
* 根据可迭代对象是否实现 RandomAccess 接口选择最优的遍历方式。
|
|
||||||
*
|
|
||||||
* @param iterable 要遍历的可迭代对象
|
|
||||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
|
|
||||||
* @param <T> 可迭代对象中元素的类型
|
|
||||||
*/
|
|
||||||
fun <T> forEach(
|
|
||||||
iterable: Iterable<T>, action: P2Function<in T, in Int>,
|
|
||||||
) {
|
|
||||||
when (iterable) {
|
|
||||||
is RandomAccess if iterable is MutableList<*> -> {
|
|
||||||
// 如果是支持随机访问的可变列表,则使用索引遍历以提高性能
|
|
||||||
val list = iterable as MutableList<T>
|
|
||||||
for (i in list.indices) {
|
|
||||||
action.call(list[i], i)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
is MutableList<*> -> {
|
|
||||||
// 对于普通可变列表,使用迭代器进行遍历,并手动维护索引
|
|
||||||
var index = 0
|
|
||||||
val it = iterable.iterator()
|
|
||||||
while (it.hasNext()) {
|
|
||||||
action.call(it.next(), index)
|
|
||||||
index++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> {
|
|
||||||
// 对于其他类型的可迭代对象,使用增强 for 循环并手动维护索引
|
|
||||||
for ((index, element) in iterable.withIndex()) {
|
|
||||||
action.call(element, index)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的可迭代对象执行指定的操作,仅处理元素值。
|
|
||||||
* 根据可迭代对象是否实现 RandomAccess 接口选择最优的遍历方式。
|
|
||||||
*
|
|
||||||
* @param iterable 要遍历的可迭代对象
|
|
||||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数
|
|
||||||
* @param <T> 可迭代对象中元素的类型
|
|
||||||
*/
|
|
||||||
fun <T> forEach(
|
|
||||||
iterable: Iterable<T>, action: P1Function<in T>,
|
|
||||||
) {
|
|
||||||
if (iterable is RandomAccess) {
|
|
||||||
// 如果是支持随机访问的列表,则使用索引遍历以提高性能
|
|
||||||
val list = iterable as MutableList<T>
|
|
||||||
for (i in list.indices) {
|
|
||||||
action.call(list[i])
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// 否则使用增强 for 循环进行遍历
|
|
||||||
for (element in iterable) {
|
|
||||||
action.call(element)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的可迭代对象执行指定的操作,同时处理元素值和索引。
|
|
||||||
* 如果操作返回 true,则提前终止遍历。
|
|
||||||
* 根据可迭代对象是否实现 RandomAccess 接口选择最优的遍历方式。
|
|
||||||
*
|
|
||||||
* @param iterable 要遍历的可迭代对象
|
|
||||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
|
|
||||||
* @param <T> 可迭代对象中元素的类型
|
|
||||||
*/
|
|
||||||
fun <T> forEachB(
|
|
||||||
iterable: Iterable<T>, action: P2RFunction<in T, in Int, out Boolean>,
|
|
||||||
) {
|
|
||||||
when (iterable) {
|
|
||||||
is RandomAccess if iterable is MutableList<*> -> {
|
|
||||||
// 如果是支持随机访问的可变列表,则使用索引遍历以提高性能
|
|
||||||
val list = iterable as MutableList<T>
|
|
||||||
for (i in list.indices) {
|
|
||||||
if (action.call(list[i], i)) return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
is MutableList<*> -> {
|
|
||||||
// 对于普通可变列表,使用迭代器进行遍历,并手动维护索引
|
|
||||||
var index = 0
|
|
||||||
val it = iterable.iterator()
|
|
||||||
while (it.hasNext()) {
|
|
||||||
if (action.call(it.next(), index)) return
|
|
||||||
index++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> {
|
|
||||||
// 对于其他类型的可迭代对象,使用增强 for 循环并手动维护索引
|
|
||||||
var index = 0
|
|
||||||
for (element in iterable) {
|
|
||||||
if (action.call(element, index)) return
|
|
||||||
index++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的可迭代对象执行指定的操作,仅处理元素值。
|
|
||||||
* 如果操作返回 true,则提前终止遍历。
|
|
||||||
* 根据可迭代对象是否实现 RandomAccess 接口选择最优的遍历方式。
|
|
||||||
*
|
|
||||||
* @param iterable 要遍历的可迭代对象
|
|
||||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
|
|
||||||
* @param <T> 可迭代对象中元素的类型
|
|
||||||
*/
|
|
||||||
fun <T> forEachB(
|
|
||||||
iterable: Iterable<T>, action: P1RFunction<in T, out Boolean>,
|
|
||||||
) {
|
|
||||||
if (iterable is RandomAccess) {
|
|
||||||
// 如果是支持随机访问的列表,则使用索引遍历以提高性能
|
|
||||||
val list = iterable as MutableList<T>
|
|
||||||
for (i in list.indices) {
|
|
||||||
if (action.call(list[i])) return
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// 否则使用增强 for 循环进行遍历
|
|
||||||
for (element in iterable) {
|
|
||||||
if (action.call(element)) return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的数组执行指定的操作,同时处理元素值和索引。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的数组
|
|
||||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
|
|
||||||
* @param <T> 数组中元素的类型
|
|
||||||
*/
|
|
||||||
fun <T> forEach(
|
|
||||||
array: Array<T>, action: P2Function<in T, in Int>,
|
|
||||||
) {
|
|
||||||
forEach(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的数组执行指定的操作,仅处理元素值。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的数组
|
|
||||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数
|
|
||||||
* @param <T> 数组中元素的类型
|
|
||||||
*/
|
|
||||||
fun <T> forEach(
|
|
||||||
array: Array<T>, action: P1Function<in T>,
|
|
||||||
) {
|
|
||||||
forEach(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的数组执行指定的操作,同时处理元素值和索引。
|
|
||||||
* 如果操作返回 true,则提前终止遍历。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的数组
|
|
||||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
|
|
||||||
* @param <T> 数组中元素的类型
|
|
||||||
*/
|
|
||||||
fun <T> forEachB(
|
|
||||||
array: Array<T>, action: P2RFunction<in T, in Int, out Boolean>,
|
|
||||||
) {
|
|
||||||
forEachB(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的数组执行指定的操作,仅处理元素值。
|
|
||||||
* 如果操作返回 true,则提前终止遍历。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的数组
|
|
||||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
|
|
||||||
* @param <T> 数组中元素的类型
|
|
||||||
*/
|
|
||||||
fun <T> forEachB(
|
|
||||||
array: Array<T>, action: P1RFunction<in T, out Boolean>,
|
|
||||||
) {
|
|
||||||
forEachB(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的字节数组执行指定的操作,同时处理元素值和索引。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的字节数组
|
|
||||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
|
|
||||||
*/
|
|
||||||
fun forEach(
|
|
||||||
array: ByteArray, action: P2Function<in Byte, in Int>,
|
|
||||||
) {
|
|
||||||
forEach(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的字节数组执行指定的操作,仅处理元素值。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的字节数组
|
|
||||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数
|
|
||||||
*/
|
|
||||||
fun forEach(
|
|
||||||
array: ByteArray, action: P1Function<in Byte>,
|
|
||||||
) {
|
|
||||||
forEach(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的字节数组执行指定的操作,同时处理元素值和索引。
|
|
||||||
* 如果操作返回 true,则提前终止遍历。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的字节数组
|
|
||||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
|
|
||||||
*/
|
|
||||||
fun forEachB(
|
|
||||||
array: ByteArray, action: P2RFunction<in Byte, in Int, out Boolean>,
|
|
||||||
) {
|
|
||||||
forEachB(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的字节数组执行指定的操作,仅处理元素值。
|
|
||||||
* 如果操作返回 true,则提前终止遍历。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的字节数组
|
|
||||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
|
|
||||||
*/
|
|
||||||
fun forEachB(
|
|
||||||
array: ByteArray, action: P1RFunction<in Byte, out Boolean>,
|
|
||||||
) {
|
|
||||||
forEachB(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的字符数组执行指定的操作,同时处理元素值和索引。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的字符数组
|
|
||||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
|
|
||||||
*/
|
|
||||||
fun forEach(
|
|
||||||
array: CharArray, action: P2Function<in Char, in Int>,
|
|
||||||
) {
|
|
||||||
forEach(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的字符数组执行指定的操作,仅处理元素值。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的字符数组
|
|
||||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数
|
|
||||||
*/
|
|
||||||
fun forEach(
|
|
||||||
array: CharArray, action: P1Function<in Char>,
|
|
||||||
) {
|
|
||||||
forEach(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的字符数组执行指定的操作,同时处理元素值和索引。
|
|
||||||
* 如果操作返回 true,则提前终止遍历。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的字符数组
|
|
||||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
|
|
||||||
*/
|
|
||||||
fun forEachB(
|
|
||||||
array: CharArray, action: P2RFunction<in Char, in Int, out Boolean>,
|
|
||||||
) {
|
|
||||||
forEachB(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的字符数组执行指定的操作,仅处理元素值。
|
|
||||||
* 如果操作返回 true,则提前终止遍历。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的字符数组
|
|
||||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
|
|
||||||
*/
|
|
||||||
fun forEachB(
|
|
||||||
array: CharArray, action: P1RFunction<in Char, out Boolean>,
|
|
||||||
) {
|
|
||||||
forEachB(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的整型数组执行指定的操作,同时处理元素值和索引。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的整型数组
|
|
||||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
|
|
||||||
*/
|
|
||||||
fun forEach(
|
|
||||||
array: IntArray, action: P2Function<in Int, in Int>,
|
|
||||||
) {
|
|
||||||
forEach(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的整型数组执行指定的操作,仅处理元素值。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的整型数组
|
|
||||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数
|
|
||||||
*/
|
|
||||||
fun forEach(
|
|
||||||
array: IntArray, action: P1Function<in Int>,
|
|
||||||
) {
|
|
||||||
forEach(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的整型数组执行指定的操作,同时处理元素值和索引。
|
|
||||||
* 如果操作返回 true,则提前终止遍历。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的整型数组
|
|
||||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
|
|
||||||
*/
|
|
||||||
fun forEachB(
|
|
||||||
array: IntArray, action: P2RFunction<in Int, in Int, out Boolean>,
|
|
||||||
) {
|
|
||||||
forEachB(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的整型数组执行指定的操作,仅处理元素值。
|
|
||||||
* 如果操作返回 true,则提前终止遍历。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的整型数组
|
|
||||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
|
|
||||||
*/
|
|
||||||
fun forEachB(
|
|
||||||
array: IntArray, action: P1RFunction<in Int, out Boolean>,
|
|
||||||
) {
|
|
||||||
forEachB(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的长整型数组执行指定的操作,同时处理元素值和索引。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的长整型数组
|
|
||||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
|
|
||||||
*/
|
|
||||||
fun forEach(
|
|
||||||
array: LongArray, action: P2Function<in Long, in Int>,
|
|
||||||
) {
|
|
||||||
forEach(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的长整型数组执行指定的操作,仅处理元素值。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的长整型数组
|
|
||||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数
|
|
||||||
*/
|
|
||||||
fun forEach(
|
|
||||||
array: LongArray, action: P1Function<in Long>,
|
|
||||||
) {
|
|
||||||
forEach(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的长整型数组执行指定的操作,同时处理元素值和索引。
|
|
||||||
* 如果操作返回 true,则提前终止遍历。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的长整型数组
|
|
||||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
|
|
||||||
*/
|
|
||||||
fun forEachB(
|
|
||||||
array: LongArray, action: P2RFunction<in Long, in Int, out Boolean>,
|
|
||||||
) {
|
|
||||||
forEachB(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的长整型数组执行指定的操作,仅处理元素值。
|
|
||||||
* 如果操作返回 true,则提前终止遍历。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的长整型数组
|
|
||||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
|
|
||||||
*/
|
|
||||||
fun forEachB(
|
|
||||||
array: LongArray, action: P1RFunction<in Long, out Boolean>,
|
|
||||||
) {
|
|
||||||
forEachB(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的短整型数组执行指定的操作,同时处理元素值和索引。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的短整型数组
|
|
||||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
|
|
||||||
*/
|
|
||||||
fun forEach(
|
|
||||||
array: ShortArray, action: P2Function<in Short, in Int>,
|
|
||||||
) {
|
|
||||||
forEach(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的短整型数组执行指定的操作,仅处理元素值。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的短整型数组
|
|
||||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数
|
|
||||||
*/
|
|
||||||
fun forEach(
|
|
||||||
array: ShortArray, action: P1Function<in Short>,
|
|
||||||
) {
|
|
||||||
forEach(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的短整型数组执行指定的操作,同时处理元素值和索引。
|
|
||||||
* 如果操作返回 true,则提前终止遍历。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的短整型数组
|
|
||||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
|
|
||||||
*/
|
|
||||||
fun forEachB(
|
|
||||||
array: ShortArray, action: P2RFunction<in Short, in Int, out Boolean>,
|
|
||||||
) {
|
|
||||||
forEachB(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的短整型数组执行指定的操作,仅处理元素值。
|
|
||||||
* 如果操作返回 true,则提前终止遍历。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的短整型数组
|
|
||||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
|
|
||||||
*/
|
|
||||||
fun forEachB(
|
|
||||||
array: ShortArray, action: P1RFunction<in Short, out Boolean>,
|
|
||||||
) {
|
|
||||||
forEachB(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的浮点数组执行指定的操作,同时处理元素值和索引。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的浮点数组
|
|
||||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
|
|
||||||
*/
|
|
||||||
fun forEach(
|
|
||||||
array: FloatArray, action: P2Function<in Float, in Int>,
|
|
||||||
) {
|
|
||||||
forEach(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的浮点数组执行指定的操作,仅处理元素值。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的浮点数组
|
|
||||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数
|
|
||||||
*/
|
|
||||||
fun forEach(
|
|
||||||
array: FloatArray, action: P1Function<in Float>,
|
|
||||||
) {
|
|
||||||
forEach(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的浮点数组执行指定的操作,同时处理元素值和索引。
|
|
||||||
* 如果操作返回 true,则提前终止遍历。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的浮点数组
|
|
||||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
|
|
||||||
*/
|
|
||||||
fun forEachB(
|
|
||||||
array: FloatArray, action: P2RFunction<in Float, in Int, out Boolean>,
|
|
||||||
) {
|
|
||||||
forEachB(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的浮点数组执行指定的操作,仅处理元素值。
|
|
||||||
* 如果操作返回 true,则提前终止遍历。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的浮点数组
|
|
||||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
|
|
||||||
*/
|
|
||||||
fun forEachB(
|
|
||||||
array: FloatArray, action: P1RFunction<in Float, out Boolean>,
|
|
||||||
) {
|
|
||||||
forEachB(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的双精度浮点数组执行指定的操作,同时处理元素值和索引。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的双精度浮点数组
|
|
||||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
|
|
||||||
*/
|
|
||||||
fun forEach(
|
|
||||||
array: DoubleArray, action: P2Function<in Double, in Int>,
|
|
||||||
) {
|
|
||||||
forEach(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的双精度浮点数组执行指定的操作,仅处理元素值。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的双精度浮点数组
|
|
||||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数
|
|
||||||
*/
|
|
||||||
fun forEach(
|
|
||||||
array: DoubleArray, action: P1Function<in Double>,
|
|
||||||
) {
|
|
||||||
forEach(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的双精度浮点数组执行指定的操作,同时处理元素值和索引。
|
|
||||||
* 如果操作返回 true,则提前终止遍历。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的双精度浮点数组
|
|
||||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
|
|
||||||
*/
|
|
||||||
fun forEachB(
|
|
||||||
array: DoubleArray, action: P2RFunction<in Double, in Int, out Boolean>,
|
|
||||||
) {
|
|
||||||
forEachB(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的双精度浮点数组执行指定的操作,仅处理元素值。
|
|
||||||
* 如果操作返回 true,则提前终止遍历。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的双精度浮点数组
|
|
||||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
|
|
||||||
*/
|
|
||||||
fun forEachB(
|
|
||||||
array: DoubleArray, action: P1RFunction<in Double, out Boolean>,
|
|
||||||
) {
|
|
||||||
forEachB(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的布尔数组执行指定的操作,同时处理元素值和索引。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的布尔数组
|
|
||||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数
|
|
||||||
*/
|
|
||||||
fun forEach(
|
|
||||||
array: BooleanArray, action: P2Function<in Boolean, in Int>,
|
|
||||||
) {
|
|
||||||
forEach(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的布尔数组执行指定的操作,仅处理元素值。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的布尔数组
|
|
||||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数
|
|
||||||
*/
|
|
||||||
fun forEach(
|
|
||||||
array: BooleanArray, action: P1Function<in Boolean>,
|
|
||||||
) {
|
|
||||||
forEach(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的布尔数组执行指定的操作,同时处理元素值和索引。
|
|
||||||
* 如果操作返回 true,则提前终止遍历。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的布尔数组
|
|
||||||
* @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止
|
|
||||||
*/
|
|
||||||
fun forEachB(
|
|
||||||
array: BooleanArray, action: P2RFunction<in Boolean, in Int, out Boolean>,
|
|
||||||
) {
|
|
||||||
forEachB(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的布尔数组执行指定的操作,仅处理元素值。
|
|
||||||
* 如果操作返回 true,则提前终止遍历。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的布尔数组
|
|
||||||
* @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止
|
|
||||||
*/
|
|
||||||
fun forEachB(
|
|
||||||
array: BooleanArray, action: P1RFunction<in Boolean, out Boolean>,
|
|
||||||
) {
|
|
||||||
forEachB(array.toList(), action)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的键值对集合执行指定的操作,同时处理键、值和索引。
|
|
||||||
* 如果操作返回 true,则提前终止遍历。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的键值对集合
|
|
||||||
* @param action 要对每个键值对执行的操作,接收键、值和索引作为参数,返回 Boolean 表示是否提前终止
|
|
||||||
* @param <K> 键的类型
|
|
||||||
* @param <V> 值的类型
|
|
||||||
* @param <A> 集合的具体类型
|
|
||||||
*/
|
|
||||||
fun <K, V, A : Collection<Map.Entry<K, V>>> forEachB(
|
|
||||||
array: A, action: P3RFunction<in K, in V, in Int, out Boolean>,
|
|
||||||
) {
|
|
||||||
forEachB(array, P2RFunction<Map.Entry<K, V>, Int, Boolean> { p1, p2 -> action.call(p1.key, p1.value, p2) })
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的映射执行指定的操作,同时处理键、值和索引。
|
|
||||||
* 如果操作返回 true,则提前终止遍历。
|
|
||||||
*
|
|
||||||
* @param map 要遍历的映射
|
|
||||||
* @param action 要对每个键值对执行的操作,接收键、值和索引作为参数,返回 Boolean 表示是否提前终止
|
|
||||||
* @param <K> 键的类型
|
|
||||||
* @param <V> 值的类型
|
|
||||||
* @param <A> 映射的具体类型
|
|
||||||
*/
|
|
||||||
fun <K, V, A : Map<K, V>> forEachB(
|
|
||||||
map: A, action: P3RFunction<in K, in V, in Int, out Boolean>,
|
|
||||||
) {
|
|
||||||
forEachB(map.entries, P2RFunction<Map.Entry<K, V>, Int, Boolean> { p1, p2 -> action.call(p1.key, p1.value, p2) })
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的键值对集合执行指定的操作,仅处理键和值。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的键值对集合
|
|
||||||
* @param action 要对每个键值对执行的操作,接收键和值作为参数
|
|
||||||
* @param <K> 键的类型
|
|
||||||
* @param <V> 值的类型
|
|
||||||
* @param <A> 集合的具体类型
|
|
||||||
*/
|
|
||||||
fun <K, V, A : Collection<Map.Entry<K, V>>> forEachMap(
|
|
||||||
array: A, action: P2Function<in K, in V>,
|
|
||||||
) {
|
|
||||||
forEach(array, P1Function<Map.Entry<K, V>> { p1 -> action.call(p1.key, p1.value) })
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的映射执行指定的操作,仅处理键和值。
|
|
||||||
*
|
|
||||||
* @param map 要遍历的映射
|
|
||||||
* @param action 要对每个键值对执行的操作,接收键和值作为参数
|
|
||||||
* @param <K> 键的类型
|
|
||||||
* @param <V> 值的类型
|
|
||||||
* @param <A> 映射的具体类型
|
|
||||||
*/
|
|
||||||
fun <K, V, A : Map<K, V>> forEachMap(
|
|
||||||
map: A, action: P2Function<in K, in V>,
|
|
||||||
) {
|
|
||||||
forEach(map.entries, P1Function<Map.Entry<K, V>> { p1 -> action.call(p1.key, p1.value) })
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的键值对集合执行指定的操作,仅处理键和值。
|
|
||||||
* 如果操作返回 true,则提前终止遍历。
|
|
||||||
*
|
|
||||||
* @param array 要遍历的键值对集合
|
|
||||||
* @param action 要对每个键值对执行的操作,接收键和值作为参数,返回 Boolean 表示是否提前终止
|
|
||||||
* @param <K> 键的类型
|
|
||||||
* @param <V> 值的类型
|
|
||||||
* @param <A> 集合的具体类型
|
|
||||||
*/
|
|
||||||
fun <K, V, A : Collection<Map.Entry<K, V>>> forEachMapB(
|
|
||||||
array: A, action: P2RFunction<in K, in V, out Boolean>,
|
|
||||||
) {
|
|
||||||
forEachB(array, P1RFunction<Map.Entry<K, V>, Boolean> { p1 -> action.call(p1.key, p1.value) })
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对给定的映射执行指定的操作,仅处理键和值。
|
|
||||||
* 如果操作返回 true,则提前终止遍历。
|
|
||||||
*
|
|
||||||
* @param map 要遍历的映射
|
|
||||||
* @param action 要对每个键值对执行的操作,接收键和值作为参数,返回 Boolean 表示是否提前终止
|
|
||||||
* @param <K> 键的类型
|
|
||||||
* @param <V> 值的类型
|
|
||||||
* @param <A> 映射的具体类型
|
|
||||||
*/
|
|
||||||
fun <K, V, A : Map<K, V>> forEachMapB(
|
|
||||||
map: A, action: P2RFunction<in K, in V, out Boolean>,
|
|
||||||
) {
|
|
||||||
forEachB(map.entries, P1RFunction<Map.Entry<K, V>, Boolean> { p1 -> action.call(p1.key, p1.value) })
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.main
|
||||||
|
* CurrentFile HashType.kt
|
||||||
|
* LastUpdate 2026-11-18 18:48:01
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.hash
|
||||||
|
|
||||||
|
import com.mingliqiye.utils.hash.code.HashCodec
|
||||||
|
import java.io.InputStream
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 哈希算法类型枚举。
|
||||||
|
*
|
||||||
|
* 每个枚举项持有一个哈希编解码器的工厂函数,枚举本身实现了 [HashCodec],
|
||||||
|
* 可直接作为编解码器使用,哈希操作委托给对应的编解码器实例。
|
||||||
|
*
|
||||||
|
* @param codec 哈希编解码器的工厂函数,每次访问 [code] 时调用以创建实例
|
||||||
|
*/
|
||||||
|
enum class HashType(private val codec: () -> HashCodec) : HashCodec {
|
||||||
|
/** MD2 哈希(输出 128 位,已过时,仅用于兼容遗留系统)。 */
|
||||||
|
MD2(::MD2),
|
||||||
|
/** MD5 哈希(输出 128 位,存在碰撞漏洞,不得用于安全场景)。 */
|
||||||
|
MD5(::MD5),
|
||||||
|
/** SHA-1 哈希(输出 160 位,存在碰撞攻击,不得用于安全场景)。 */
|
||||||
|
SHA1(::SHA1),
|
||||||
|
/** SHA-224 哈希(SHA-2 家族,输出 224 位)。 */
|
||||||
|
SHA224(::SHA224),
|
||||||
|
/** SHA-256 哈希(SHA-2 家族,输出 256 位)。 */
|
||||||
|
SHA256(::SHA256),
|
||||||
|
/** SHA-384 哈希(SHA-2 家族,输出 384 位)。 */
|
||||||
|
SHA384(::SHA384),
|
||||||
|
/** SHA-512 哈希(SHA-2 家族,输出 512 位)。 */
|
||||||
|
SHA512(::SHA512),
|
||||||
|
/** SHA3-224 哈希(SHA-3 家族,输出 224 位)。 */
|
||||||
|
SHA3224(::SHA3224),
|
||||||
|
/** SHA3-256 哈希(SHA-3 家族,输出 256 位)。 */
|
||||||
|
SHA3256(::SHA3256),
|
||||||
|
/** SHA3-384 哈希(SHA-3 家族,输出 384 位)。 */
|
||||||
|
SHA3384(::SHA3384),
|
||||||
|
/** SHA3-512 哈希(SHA-3 家族,输出 512 位)。 */
|
||||||
|
SHA3512(::SHA3512),
|
||||||
|
/** SHA-512/224 哈希(SHA-2 家族,输出 224 位)。 */
|
||||||
|
SHA512224(::SHA512224),
|
||||||
|
/** SHA-512/256 哈希(SHA-2 家族,输出 256 位)。 */
|
||||||
|
SHA512256(::SHA512256);
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取当前类型对应的哈希编解码器实例(每次访问都会通过工厂函数新建)。
|
||||||
|
*/
|
||||||
|
val code get() = codec()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算输入流内容的哈希值,委托给 [code] 对应的编解码器。
|
||||||
|
*
|
||||||
|
* @param input 待计算哈希的输入流
|
||||||
|
* @return 哈希结果字节数组
|
||||||
|
*/
|
||||||
|
override fun hash(input: InputStream): ByteArray {
|
||||||
|
return code.hash(input)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
@@ -16,71 +16,103 @@
|
|||||||
* ProjectName mingli-utils
|
* ProjectName mingli-utils
|
||||||
* ModuleName mingli-utils.main
|
* ModuleName mingli-utils.main
|
||||||
* CurrentFile HashUtils.kt
|
* CurrentFile HashUtils.kt
|
||||||
* LastUpdate 2026-01-11 09:09:52
|
* LastUpdate 2026-11-18 18:53:11
|
||||||
* UpdateUser MingLiPro
|
* UpdateUser MingLiPro
|
||||||
*/
|
*/
|
||||||
@file:JvmName("HashUtils")
|
@file:JvmName("HashUtils")
|
||||||
|
|
||||||
package com.mingliqiye.utils.hash
|
package com.mingliqiye.utils.hash
|
||||||
|
|
||||||
|
import com.mingliqiye.utils.hash.code.*
|
||||||
|
|
||||||
import com.mingliqiye.utils.bcrypt.checkpw
|
|
||||||
import com.mingliqiye.utils.bcrypt.hashpw
|
|
||||||
import com.mingliqiye.utils.bytes.bytesToHex
|
|
||||||
import java.io.File
|
|
||||||
import java.io.FileInputStream
|
|
||||||
import java.io.IOException
|
|
||||||
import java.security.MessageDigest
|
|
||||||
import java.security.NoSuchAlgorithmException
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 计算指定文件的哈希值。
|
* 提供 MD2 哈希器的懒加载实例。
|
||||||
*
|
* 该哈希器输出 128 位摘要,算法已过时,仅用于兼容遗留系统。
|
||||||
* @param file 要计算哈希值的文件对象
|
|
||||||
* @param algorithm 使用的哈希算法名称(如 SHA-256、MD5 等)
|
|
||||||
* @return 文件的十六进制格式哈希值字符串
|
|
||||||
* @throws IOException 当文件不存在或读取过程中发生 I/O 错误时抛出
|
|
||||||
* @throws NoSuchAlgorithmException 当指定的哈希算法不可用时抛出
|
|
||||||
*/
|
*/
|
||||||
@Throws(IOException::class, NoSuchAlgorithmException::class)
|
@get:JvmName("getMd2Codec")
|
||||||
fun calculateFileHash(file: File, algorithm: String): String {
|
val MD2 by lazy(::Md2Codec)
|
||||||
// 检查文件是否存在
|
|
||||||
if (!file.exists()) {
|
|
||||||
throw IOException("File not found: " + file.absolutePath)
|
|
||||||
}
|
|
||||||
|
|
||||||
val digest = MessageDigest.getInstance(algorithm)
|
|
||||||
|
|
||||||
FileInputStream(file).use { fis ->
|
|
||||||
val buffer = ByteArray(8192)
|
|
||||||
var bytesRead: Int
|
|
||||||
|
|
||||||
// 分块读取文件内容并更新摘要
|
|
||||||
while (fis.read(buffer).also { bytesRead = it } != -1) {
|
|
||||||
digest.update(buffer, 0, bytesRead)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return bytesToHex(digest.digest())
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 使用 BCrypt 算法对字符串进行加密。
|
* 提供 MD5 哈希器的懒加载实例。
|
||||||
*
|
* 该哈希器输出 128 位摘要,存在碰撞漏洞,不得用于安全场景,仅建议非安全性校验。
|
||||||
* @param string 需要加密的明文字符串
|
|
||||||
* @return 加密后的 BCrypt 哈希字符串
|
|
||||||
*/
|
*/
|
||||||
fun bcrypt(string: String): String {
|
@get:JvmName("getMd5Codec")
|
||||||
return hashpw(string)
|
val MD5 by lazy(::Md5Codec)
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 验证给定字符串与 BCrypt 哈希是否匹配。
|
* 提供 SHA-1 哈希器的懒加载实例。
|
||||||
*
|
* 该哈希器输出 160 位摘要,存在碰撞攻击,不得用于安全场景,仅建议非安全性校验。
|
||||||
* @param string 明文字符串
|
|
||||||
* @param bcrypted 已经使用 BCrypt 加密的哈希字符串
|
|
||||||
* @return 如果匹配返回 true,否则返回 false
|
|
||||||
*/
|
*/
|
||||||
fun checkBcrypt(string: String, bcrypted: String): Boolean {
|
@get:JvmName("getSha1Codec")
|
||||||
return checkpw(string, bcrypted)
|
val SHA1 by lazy(::Sha1Codec)
|
||||||
}
|
|
||||||
|
/**
|
||||||
|
* 提供 SHA-224 哈希器的懒加载实例。
|
||||||
|
* 该哈希器属于 SHA-2 家族,输出 224 位摘要。
|
||||||
|
*/
|
||||||
|
@get:JvmName("getSha224Codec")
|
||||||
|
val SHA224 by lazy(::Sha224Codec)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提供 SHA-256 哈希器的懒加载实例。
|
||||||
|
* 该哈希器属于 SHA-2 家族,输出 256 位摘要,适用于文件校验、数字签名等场景。
|
||||||
|
*/
|
||||||
|
@get:JvmName("getSha256Codec")
|
||||||
|
val SHA256 by lazy(::Sha256Codec)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提供 SHA-384 哈希器的懒加载实例。
|
||||||
|
* 该哈希器属于 SHA-2 家族,输出 384 位摘要。
|
||||||
|
*/
|
||||||
|
@get:JvmName("getSha384Codec")
|
||||||
|
val SHA384 by lazy(::Sha384Codec)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提供 SHA-512 哈希器的懒加载实例。
|
||||||
|
* 该哈希器属于 SHA-2 家族,输出 512 位摘要,在 64 位平台上通常比 SHA-256 更快。
|
||||||
|
*/
|
||||||
|
@get:JvmName("getSha512Codec")
|
||||||
|
val SHA512 by lazy(::Sha512Codec)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提供 SHA3-224 哈希器的懒加载实例。
|
||||||
|
* 该哈希器属于 SHA-3 家族(Keccak 结构),输出 224 位摘要。
|
||||||
|
*/
|
||||||
|
@get:JvmName("getSha3224Codec")
|
||||||
|
val SHA3224 by lazy(::Sha3224Codec)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提供 SHA3-256 哈希器的懒加载实例。
|
||||||
|
* 该哈希器属于 SHA-3 家族(Keccak 结构),输出 256 位摘要。
|
||||||
|
*/
|
||||||
|
@get:JvmName("getSha3256Codec")
|
||||||
|
val SHA3256 by lazy(::Sha3256Codec)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提供 SHA3-384 哈希器的懒加载实例。
|
||||||
|
* 该哈希器属于 SHA-3 家族(Keccak 结构),输出 384 位摘要。
|
||||||
|
*/
|
||||||
|
@get:JvmName("getSha3384Codec")
|
||||||
|
val SHA3384 by lazy(::Sha3384Codec)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提供 SHA3-512 哈希器的懒加载实例。
|
||||||
|
* 该哈希器属于 SHA-3 家族(Keccak 结构),输出 512 位摘要。
|
||||||
|
*/
|
||||||
|
@get:JvmName("getSha3512Codec")
|
||||||
|
val SHA3512 by lazy(::Sha3512Codec)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提供 SHA-512/224 哈希器的懒加载实例。
|
||||||
|
* 该哈希器以 SHA-512 的运算结构截断输出至 224 位,在 64 位平台上性能优于 SHA-224。
|
||||||
|
*/
|
||||||
|
@get:JvmName("getSha512224Codec")
|
||||||
|
val SHA512224 by lazy(::Sha512224Codec)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提供 SHA-512/256 哈希器的懒加载实例。
|
||||||
|
* 该哈希器以 SHA-512 的运算结构截断输出至 256 位,在 64 位平台上性能优于 SHA-256。
|
||||||
|
*/
|
||||||
|
@get:JvmName("getSha512256Codec")
|
||||||
|
val SHA512256 by lazy(::Sha512256Codec)
|
||||||
|
|||||||
@@ -0,0 +1,176 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.main
|
||||||
|
* CurrentFile HashCodec.kt
|
||||||
|
* LastUpdate 2026-11-18 18:36:00
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.hash.code
|
||||||
|
|
||||||
|
import com.mingliqiye.utils.base.BaseType
|
||||||
|
import java.io.File
|
||||||
|
import java.io.InputStream
|
||||||
|
import java.nio.charset.Charset
|
||||||
|
import java.nio.file.Files
|
||||||
|
import java.nio.file.Path
|
||||||
|
import java.security.MessageDigest
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 哈希编解码器接口。
|
||||||
|
*
|
||||||
|
* 实现类只需重写 [hash](InputStream 版本)一个方法,
|
||||||
|
* 其余字节数组、字符串、文件、路径的重载以及十六进制输出、
|
||||||
|
* 哈希校验均由接口提供默认实现。
|
||||||
|
*
|
||||||
|
* 使用示例(以 SHA-256 为例):
|
||||||
|
* ```
|
||||||
|
* val sha256 = Sha256Codec()
|
||||||
|
* val hex = sha256.hashHex("hello")
|
||||||
|
* val ok = sha256.verifyHash("hello", hex)
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
interface HashCodec {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算输入流内容的哈希值(唯一需要实现的方法)。
|
||||||
|
*
|
||||||
|
* 实现不需要关闭输入流,由调用方负责流的生命周期。
|
||||||
|
*
|
||||||
|
* @param input 待计算哈希的输入流
|
||||||
|
* @return 哈希结果字节数组
|
||||||
|
*/
|
||||||
|
fun hash(input: InputStream): ByteArray
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算字节数组的哈希值。
|
||||||
|
*
|
||||||
|
* @param bytes 待计算哈希的字节数组
|
||||||
|
* @return 哈希结果字节数组
|
||||||
|
*/
|
||||||
|
fun hash(bytes: ByteArray): ByteArray = hash(bytes.inputStream())
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算字符串的哈希值。
|
||||||
|
*
|
||||||
|
* @param string 待计算哈希的字符串
|
||||||
|
* @param charset 字符串编码字符集,默认 UTF-8
|
||||||
|
* @return 哈希结果字节数组
|
||||||
|
*/
|
||||||
|
fun hash(string: String, charset: Charset = Charsets.UTF_8): ByteArray = hash(string.toByteArray(charset))
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算文件内容的哈希值。
|
||||||
|
*
|
||||||
|
* @param file 待计算哈希的文件
|
||||||
|
* @return 哈希结果字节数组
|
||||||
|
*/
|
||||||
|
fun hash(file: File): ByteArray = file.inputStream().use { hash(it) }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算路径指向文件内容的哈希值。
|
||||||
|
*
|
||||||
|
* @param path 待计算哈希的文件路径
|
||||||
|
* @return 哈希结果字节数组
|
||||||
|
*/
|
||||||
|
fun hash(path: Path): ByteArray = Files.newInputStream(path).use { hash(it) }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算输入流内容的哈希值并以小写十六进制字符串返回。
|
||||||
|
*
|
||||||
|
* @param input 待计算哈希的输入流
|
||||||
|
* @return 十六进制格式的哈希字符串
|
||||||
|
*/
|
||||||
|
fun hashHex(input: InputStream): String = BaseType.BASE16.encode(hash(input))
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算字节数组的哈希值并以小写十六进制字符串返回。
|
||||||
|
*
|
||||||
|
* @param bytes 待计算哈希的字节数组
|
||||||
|
* @return 十六进制格式的哈希字符串
|
||||||
|
*/
|
||||||
|
fun hashHex(bytes: ByteArray): String = BaseType.BASE16.encode(hash(bytes))
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算字符串的哈希值并以小写十六进制字符串返回。
|
||||||
|
*
|
||||||
|
* @param string 待计算哈希的字符串
|
||||||
|
* @param charset 字符串编码字符集,默认 UTF-8
|
||||||
|
* @return 十六进制格式的哈希字符串
|
||||||
|
*/
|
||||||
|
fun hashHex(string: String, charset: Charset = Charsets.UTF_8): String =
|
||||||
|
BaseType.BASE16.encode(hash(string, charset))
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算文件内容的哈希值并以小写十六进制字符串返回。
|
||||||
|
*
|
||||||
|
* @param file 待计算哈希的文件
|
||||||
|
* @return 十六进制格式的哈希字符串
|
||||||
|
*/
|
||||||
|
fun hashHex(file: File): String = BaseType.BASE16.encode(hash(file))
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算路径指向文件内容的哈希值并以小写十六进制字符串返回。
|
||||||
|
*
|
||||||
|
* @param path 待计算哈希的文件路径
|
||||||
|
* @return 十六进制格式的哈希字符串
|
||||||
|
*/
|
||||||
|
fun hashHex(path: Path): String = BaseType.BASE16.encode(hash(path))
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 校验输入流内容的哈希值是否与期望值一致。
|
||||||
|
*
|
||||||
|
* 使用 [java.security.MessageDigest.isEqual] 进行常量时间比较,避免时序攻击。
|
||||||
|
*
|
||||||
|
* @param input 待校验的输入流
|
||||||
|
* @param hashed 期望的哈希值字节数组
|
||||||
|
* @return 一致返回 true,否则返回 false
|
||||||
|
*/
|
||||||
|
fun verifyHash(input: InputStream, hashed: ByteArray): Boolean = MessageDigest.isEqual(hash(input), hashed)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 校验字节数组的哈希值是否与期望值一致。
|
||||||
|
*
|
||||||
|
* @param bytes 待校验的字节数组
|
||||||
|
* @param hashed 期望的哈希值字节数组
|
||||||
|
* @return 一致返回 true,否则返回 false
|
||||||
|
*/
|
||||||
|
fun verifyHash(bytes: ByteArray, hashed: ByteArray): Boolean = MessageDigest.isEqual(hash(bytes), hashed)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 校验字符串的哈希值是否与期望值一致。
|
||||||
|
*
|
||||||
|
* @param string 待校验的字符串
|
||||||
|
* @param hashed 期望的哈希值字节数组
|
||||||
|
* @param charset 字符串编码字符集,默认 UTF-8
|
||||||
|
* @return 一致返回 true,否则返回 false
|
||||||
|
*/
|
||||||
|
fun verifyHash(string: String, hashed: ByteArray, charset: Charset = Charsets.UTF_8): Boolean =
|
||||||
|
MessageDigest.isEqual(hash(string, charset), hashed)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 校验字符串的哈希值是否与期望的十六进制字符串一致(忽略大小写)。
|
||||||
|
*
|
||||||
|
* @param string 待校验的字符串
|
||||||
|
* @param hashedHex 期望的十六进制哈希字符串
|
||||||
|
* @param charset 字符串编码字符集,默认 UTF-8
|
||||||
|
* @return 一致返回 true,否则返回 false
|
||||||
|
*/
|
||||||
|
fun verifyHash(string: String, hashedHex: String, charset: Charset = Charsets.UTF_8): Boolean =
|
||||||
|
MessageDigest.isEqual(hash(string, charset), BaseType.BASE16.decode(hashedHex.lowercase()))
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.main
|
||||||
|
* CurrentFile Md2Codec.kt
|
||||||
|
* LastUpdate 2026-11-18 11:18:32
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.hash.code
|
||||||
|
|
||||||
|
/**
|
||||||
|
* MD2 哈希编解码器(输出 128 位 / 16 字节)。
|
||||||
|
*
|
||||||
|
* MD2 已过时且存在安全缺陷,仅用于兼容遗留系统,不建议在任何新场景使用。
|
||||||
|
*/
|
||||||
|
class Md2Codec : MessageDigestCodec("MD2")
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.main
|
||||||
|
* CurrentFile Md5Codec.kt
|
||||||
|
* LastUpdate 2026-11-18 11:18:32
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.hash.code
|
||||||
|
|
||||||
|
/**
|
||||||
|
* MD5 哈希编解码器(输出 128 位 / 16 字节)。
|
||||||
|
*
|
||||||
|
* MD5 已被证实存在碰撞漏洞,不得用于数字签名、密码存储等安全场景,
|
||||||
|
* 仅建议用于兼容遗留系统或非安全性校验(如文件完整性粗检)。
|
||||||
|
*/
|
||||||
|
class Md5Codec : MessageDigestCodec("MD5")
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.main
|
||||||
|
* CurrentFile MessageDigestCodec.kt
|
||||||
|
* LastUpdate 2026-11-18 11:18:32
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.hash.code
|
||||||
|
|
||||||
|
import java.io.InputStream
|
||||||
|
import java.security.MessageDigest
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 基于 JDK [MessageDigest] 的哈希编解码器抽象基类。
|
||||||
|
*
|
||||||
|
* 以固定 8KB 缓冲区流式读取输入,内存占用恒定,适用于任意大小的文件与数据流。
|
||||||
|
* 每次调用 [hash] 都会新建 [MessageDigest] 实例(其本身非线程安全),
|
||||||
|
* 因此本类实例无状态、可安全地在多线程间共享。
|
||||||
|
*
|
||||||
|
* 遵循 [HashCodec] 契约:不关闭输入流,由调用方负责流的生命周期。
|
||||||
|
*
|
||||||
|
* 子类只需指定算法名称,也可借此扩展 JDK 默认提供者之外的算法
|
||||||
|
* (如 BouncyCastle 提供的 SM3),前提是相应 [java.security.Provider] 已注册。
|
||||||
|
*
|
||||||
|
* @param algorithm [MessageDigest.getInstance] 所用的算法名称
|
||||||
|
*/
|
||||||
|
abstract class MessageDigestCodec(private val algorithm: String) : HashCodec {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 以 8KB 缓冲区流式计算输入流内容的哈希值。
|
||||||
|
*
|
||||||
|
* 不关闭输入流;每次调用新建 [MessageDigest] 实例,线程安全。
|
||||||
|
*
|
||||||
|
* @param input 待计算哈希的输入流
|
||||||
|
* @return 哈希结果字节数组
|
||||||
|
* @throws java.security.NoSuchAlgorithmException 当前环境无指定算法的提供者时抛出
|
||||||
|
*/
|
||||||
|
override fun hash(input: InputStream): ByteArray {
|
||||||
|
val digest = MessageDigest.getInstance(algorithm)
|
||||||
|
val buffer = ByteArray(8192)
|
||||||
|
while (true) {
|
||||||
|
val n = input.read(buffer)
|
||||||
|
if (n == -1) break
|
||||||
|
digest.update(buffer, 0, n)
|
||||||
|
}
|
||||||
|
return digest.digest()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.main
|
||||||
|
* CurrentFile Sha1Codec.kt
|
||||||
|
* LastUpdate 2026-11-18 11:18:32
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.hash.code
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SHA-1 哈希编解码器(输出 160 位 / 20 字节)。
|
||||||
|
*
|
||||||
|
* SHA-1 已被证实存在碰撞攻击(SHAttered),不得用于安全场景,
|
||||||
|
* 仅建议用于兼容遗留系统或非安全性校验。
|
||||||
|
*/
|
||||||
|
class Sha1Codec : MessageDigestCodec("SHA-1")
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.main
|
||||||
|
* CurrentFile Sha224Codec.kt
|
||||||
|
* LastUpdate 2026-11-18 11:18:32
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.hash.code
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SHA-224 哈希编解码器(SHA-2 家族,输出 224 位 / 28 字节)。
|
||||||
|
*/
|
||||||
|
class Sha224Codec : MessageDigestCodec("SHA-224")
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.main
|
||||||
|
* CurrentFile Sha256Codec.kt
|
||||||
|
* LastUpdate 2026-11-18 11:18:32
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.hash.code
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SHA-256 哈希编解码器(SHA-2 家族,输出 256 位 / 32 字节)。
|
||||||
|
*
|
||||||
|
* 目前广泛使用的安全哈希算法,适用于文件校验、数字签名、消息摘要等场景。
|
||||||
|
*
|
||||||
|
* 使用示例:
|
||||||
|
* ```
|
||||||
|
* val sha256 = Sha256Codec()
|
||||||
|
* val hex = sha256.hashHex("hello")
|
||||||
|
* val ok = sha256.verifyHash("hello", hex)
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
class Sha256Codec : MessageDigestCodec("SHA-256")
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.main
|
||||||
|
* CurrentFile Sha3224Codec.kt
|
||||||
|
* LastUpdate 2026-11-18 11:18:32
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.hash.code
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SHA3-224 哈希编解码器(SHA-3 家族,Keccak 结构,输出 224 位 / 28 字节)。
|
||||||
|
*/
|
||||||
|
class Sha3224Codec : MessageDigestCodec("SHA3-224")
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.main
|
||||||
|
* CurrentFile Sha3256Codec.kt
|
||||||
|
* LastUpdate 2026-11-18 11:18:32
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.hash.code
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SHA3-256 哈希编解码器(SHA-3 家族,Keccak 结构,输出 256 位 / 32 字节)。
|
||||||
|
*/
|
||||||
|
class Sha3256Codec : MessageDigestCodec("SHA3-256")
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.main
|
||||||
|
* CurrentFile Sha3384Codec.kt
|
||||||
|
* LastUpdate 2026-11-18 11:18:32
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.hash.code
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SHA3-384 哈希编解码器(SHA-3 家族,Keccak 结构,输出 384 位 / 48 字节)。
|
||||||
|
*/
|
||||||
|
class Sha3384Codec : MessageDigestCodec("SHA3-384")
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.main
|
||||||
|
* CurrentFile Sha3512Codec.kt
|
||||||
|
* LastUpdate 2026-11-18 11:18:52
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.hash.code
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SHA3-512 哈希编解码器(SHA-3 家族,Keccak 结构,输出 512 位 / 64 字节)。
|
||||||
|
*/
|
||||||
|
class Sha3512Codec : MessageDigestCodec("SHA3-512")
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.main
|
||||||
|
* CurrentFile Sha384Codec.kt
|
||||||
|
* LastUpdate 2026-11-18 11:18:32
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.hash.code
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SHA-384 哈希编解码器(SHA-2 家族,输出 384 位 / 48 字节)。
|
||||||
|
*/
|
||||||
|
class Sha384Codec : MessageDigestCodec("SHA-384")
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.main
|
||||||
|
* CurrentFile Sha512224Codec.kt
|
||||||
|
* LastUpdate 2026-11-18 11:18:32
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.hash.code
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SHA-512/224 哈希编解码器(SHA-2 家族,输出 224 位 / 28 字节)。
|
||||||
|
*
|
||||||
|
* 以 SHA-512 的运算结构截断输出至 224 位,在 64 位平台上性能优于 SHA-224。
|
||||||
|
*/
|
||||||
|
class Sha512224Codec : MessageDigestCodec("SHA-512/224")
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.main
|
||||||
|
* CurrentFile Sha512256Codec.kt
|
||||||
|
* LastUpdate 2026-11-18 11:18:32
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.hash.code
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SHA-512/256 哈希编解码器(SHA-2 家族,输出 256 位 / 32 字节)。
|
||||||
|
*
|
||||||
|
* 以 SHA-512 的运算结构截断输出至 256 位,在 64 位平台上性能优于 SHA-256。
|
||||||
|
*/
|
||||||
|
class Sha512256Codec : MessageDigestCodec("SHA-512/256")
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.main
|
||||||
|
* CurrentFile Sha512Codec.kt
|
||||||
|
* LastUpdate 2026-11-18 11:18:32
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.hash.code
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SHA-512 哈希编解码器(SHA-2 家族,输出 512 位 / 64 字节)。
|
||||||
|
*
|
||||||
|
* 在 64 位平台上通常比 SHA-256 更快,适用于大文件校验与高安全需求场景。
|
||||||
|
*/
|
||||||
|
class Sha512Codec : MessageDigestCodec("SHA-512")
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -16,14 +16,14 @@
|
|||||||
* ProjectName mingli-utils
|
* ProjectName mingli-utils
|
||||||
* ModuleName mingli-utils.main
|
* ModuleName mingli-utils.main
|
||||||
* CurrentFile DateTimeJsonConverter.kt
|
* CurrentFile DateTimeJsonConverter.kt
|
||||||
* LastUpdate 2026-11-17 20:17:32
|
* LastUpdate 2026-11-18 00:03:07
|
||||||
* UpdateUser MingLiPro
|
* UpdateUser MingLiPro
|
||||||
*/
|
*/
|
||||||
|
|
||||||
package com.mingliqiye.utils.json.converters
|
package com.mingliqiye.utils.json.converters
|
||||||
|
|
||||||
import com.google.gson.JsonParseException
|
|
||||||
import com.mingliqiye.utils.annotation.DateTimeJsonFormat
|
import com.mingliqiye.utils.annotation.DateTimeJsonFormat
|
||||||
|
import com.mingliqiye.utils.exception.JsonParserException
|
||||||
import com.mingliqiye.utils.json.api.type.JsonTypeReference
|
import com.mingliqiye.utils.json.api.type.JsonTypeReference
|
||||||
import com.mingliqiye.utils.json.converters.base.AnnotationGetter
|
import com.mingliqiye.utils.json.converters.base.AnnotationGetter
|
||||||
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
|
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
|
||||||
@@ -68,12 +68,12 @@ class DateTimeJsonConverter : BaseJsonConverter<DateTime> {
|
|||||||
/**
|
/**
|
||||||
* 按 [DateTimeJsonFormat] 注解指定的格式从 JSON 字符串解析日期时间
|
* 按 [DateTimeJsonFormat] 注解指定的格式从 JSON 字符串解析日期时间
|
||||||
*
|
*
|
||||||
* @throws JsonParseException 当节点不是字符串类型时抛出
|
* @throws JsonParserException 当节点不是字符串类型时抛出
|
||||||
*/
|
*/
|
||||||
override fun deConvert(jsonReader: BaseJsonReader, annotationGetter: AnnotationGetter): DateTime? {
|
override fun deConvert(jsonReader: BaseJsonReader, annotationGetter: AnnotationGetter): DateTime? {
|
||||||
val dateTimeJsonFormat: DateTimeJsonFormat? = annotationGetter.getAnnotation<DateTimeJsonFormat>()
|
val dateTimeJsonFormat: DateTimeJsonFormat? = annotationGetter.getAnnotation<DateTimeJsonFormat>()
|
||||||
if (jsonReader.isNull) return null
|
if (jsonReader.isNull) return null
|
||||||
if (!jsonReader.isString) throw JsonParseException("type item not string")
|
if (!jsonReader.isString) throw JsonParserException("type item not string")
|
||||||
val obj = jsonReader.getString()
|
val obj = jsonReader.getString()
|
||||||
return if (Formatter.NONE != dateTimeJsonFormat?.value && dateTimeJsonFormat != null) {
|
return if (Formatter.NONE != dateTimeJsonFormat?.value && dateTimeJsonFormat != null) {
|
||||||
DateTime.parse(obj, dateTimeJsonFormat.value, dateTimeJsonFormat.repcZero)
|
DateTime.parse(obj, dateTimeJsonFormat.value, dateTimeJsonFormat.repcZero)
|
||||||
|
|||||||
+4
-4
@@ -16,13 +16,13 @@
|
|||||||
* ProjectName mingli-utils
|
* ProjectName mingli-utils
|
||||||
* ModuleName mingli-utils.main
|
* ModuleName mingli-utils.main
|
||||||
* CurrentFile NetworkEndpointJsonConverter.kt
|
* CurrentFile NetworkEndpointJsonConverter.kt
|
||||||
* LastUpdate 2026-11-17 20:01:08
|
* LastUpdate 2026-11-18 00:03:17
|
||||||
* UpdateUser MingLiPro
|
* UpdateUser MingLiPro
|
||||||
*/
|
*/
|
||||||
|
|
||||||
package com.mingliqiye.utils.json.converters
|
package com.mingliqiye.utils.json.converters
|
||||||
|
|
||||||
import com.google.gson.JsonParseException
|
import com.mingliqiye.utils.exception.JsonParserException
|
||||||
import com.mingliqiye.utils.json.api.type.JsonTypeReference
|
import com.mingliqiye.utils.json.api.type.JsonTypeReference
|
||||||
import com.mingliqiye.utils.json.converters.base.AnnotationGetter
|
import com.mingliqiye.utils.json.converters.base.AnnotationGetter
|
||||||
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
|
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
|
||||||
@@ -58,14 +58,14 @@ class NetworkEndpointJsonConverter : BaseJsonConverter<NetworkEndpoint> {
|
|||||||
/**
|
/**
|
||||||
* 从 `host:port` 形式的 JSON 字符串还原网络端点
|
* 从 `host:port` 形式的 JSON 字符串还原网络端点
|
||||||
*
|
*
|
||||||
* @throws JsonParseException 当节点不是字符串类型时抛出
|
* @throws JsonParserException 当节点不是字符串类型时抛出
|
||||||
*/
|
*/
|
||||||
override fun deConvert(
|
override fun deConvert(
|
||||||
jsonReader: BaseJsonReader,
|
jsonReader: BaseJsonReader,
|
||||||
annotationGetter: AnnotationGetter,
|
annotationGetter: AnnotationGetter,
|
||||||
): NetworkEndpoint? {
|
): NetworkEndpoint? {
|
||||||
return if (jsonReader.isNotNull) {
|
return if (jsonReader.isNotNull) {
|
||||||
if (!jsonReader.isString) throw JsonParseException("type item not string")
|
if (!jsonReader.isString) throw JsonParserException("type item not string")
|
||||||
NetworkEndpoint.of(jsonReader.getString())
|
NetworkEndpoint.of(jsonReader.getString())
|
||||||
} else null
|
} else null
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,15 +16,15 @@
|
|||||||
* ProjectName mingli-utils
|
* ProjectName mingli-utils
|
||||||
* ModuleName mingli-utils.main
|
* ModuleName mingli-utils.main
|
||||||
* CurrentFile UUIDJsonConverter.kt
|
* CurrentFile UUIDJsonConverter.kt
|
||||||
* LastUpdate 2026-11-17 20:01:08
|
* LastUpdate 2026-11-18 00:03:17
|
||||||
* UpdateUser MingLiPro
|
* UpdateUser MingLiPro
|
||||||
*/
|
*/
|
||||||
|
|
||||||
package com.mingliqiye.utils.json.converters
|
package com.mingliqiye.utils.json.converters
|
||||||
|
|
||||||
import com.google.gson.JsonParseException
|
|
||||||
import com.mingliqiye.utils.annotation.UUIDJsonFormat
|
import com.mingliqiye.utils.annotation.UUIDJsonFormat
|
||||||
import com.mingliqiye.utils.base.BaseType
|
import com.mingliqiye.utils.base.BaseType
|
||||||
|
import com.mingliqiye.utils.exception.JsonParserException
|
||||||
import com.mingliqiye.utils.json.api.type.JsonTypeReference
|
import com.mingliqiye.utils.json.api.type.JsonTypeReference
|
||||||
import com.mingliqiye.utils.json.converters.base.AnnotationGetter
|
import com.mingliqiye.utils.json.converters.base.AnnotationGetter
|
||||||
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
|
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
|
||||||
@@ -72,14 +72,14 @@ class UUIDJsonConverter : BaseJsonConverter<UUID> {
|
|||||||
/**
|
/**
|
||||||
* 按 [UUIDJsonFormat] 注解指定的进制从 JSON 字符串解析 UUID
|
* 按 [UUIDJsonFormat] 注解指定的进制从 JSON 字符串解析 UUID
|
||||||
*
|
*
|
||||||
* @throws JsonParseException 当节点不是字符串类型时抛出
|
* @throws JsonParserException 当节点不是字符串类型时抛出
|
||||||
*/
|
*/
|
||||||
override fun deConvert(
|
override fun deConvert(
|
||||||
jsonReader: BaseJsonReader,
|
jsonReader: BaseJsonReader,
|
||||||
annotationGetter: AnnotationGetter,
|
annotationGetter: AnnotationGetter,
|
||||||
): UUID? {
|
): UUID? {
|
||||||
if (jsonReader.isNull) return null
|
if (jsonReader.isNull) return null
|
||||||
if (!jsonReader.isString) throw JsonParseException("type item not string")
|
if (!jsonReader.isString) throw JsonParserException("type item not string")
|
||||||
|
|
||||||
val obj = jsonReader.getString()
|
val obj = jsonReader.getString()
|
||||||
|
|
||||||
|
|||||||
@@ -16,13 +16,13 @@
|
|||||||
* ProjectName mingli-utils
|
* ProjectName mingli-utils
|
||||||
* ModuleName mingli-utils.main
|
* ModuleName mingli-utils.main
|
||||||
* CurrentFile BaseJsonWriter.kt
|
* CurrentFile BaseJsonWriter.kt
|
||||||
* LastUpdate 2026-11-17 19:32:34
|
* LastUpdate 2026-11-17 21:10:29
|
||||||
* UpdateUser MingLiPro
|
* UpdateUser MingLiPro
|
||||||
*/
|
*/
|
||||||
|
|
||||||
package com.mingliqiye.utils.json.witer.base
|
package com.mingliqiye.utils.json.witer.base
|
||||||
|
|
||||||
import com.mingliqiye.utils.json.judgment.BaseJsonJudgment
|
import com.mingliqiye.utils.json.judgment.base.BaseJsonJudgment
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -35,30 +35,35 @@ interface BaseJsonWriter : BaseJsonJudgment {
|
|||||||
* @param objCall 对象写入回调,接收对象写入器并返回它
|
* @param objCall 对象写入回调,接收对象写入器并返回它
|
||||||
*/
|
*/
|
||||||
fun setObject(objCall: (BaseJsonObjectWriter) -> BaseJsonObjectWriter)
|
fun setObject(objCall: (BaseJsonObjectWriter) -> BaseJsonObjectWriter)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 写入一个 JSON 数组,通过回调填充数组元素
|
* 写入一个 JSON 数组,通过回调填充数组元素
|
||||||
*
|
*
|
||||||
* @param arrayCall 数组写入回调,接收数组写入器并返回它
|
* @param arrayCall 数组写入回调,接收数组写入器并返回它
|
||||||
*/
|
*/
|
||||||
fun setArray(arrayCall: (BaseJsonArrayWriter) -> BaseJsonArrayWriter)
|
fun setArray(arrayCall: (BaseJsonArrayWriter) -> BaseJsonArrayWriter)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 写入字符串值
|
* 写入字符串值
|
||||||
*
|
*
|
||||||
* @param string 待写入的字符串
|
* @param string 待写入的字符串
|
||||||
*/
|
*/
|
||||||
fun setString(string: String)
|
fun setString(string: String)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 写入数值
|
* 写入数值
|
||||||
*
|
*
|
||||||
* @param number 待写入的数值
|
* @param number 待写入的数值
|
||||||
*/
|
*/
|
||||||
fun setNumber(number: Number)
|
fun setNumber(number: Number)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 写入布尔值
|
* 写入布尔值
|
||||||
*
|
*
|
||||||
* @param boolean 待写入的布尔值
|
* @param boolean 待写入的布尔值
|
||||||
*/
|
*/
|
||||||
fun setBoolean(boolean: Boolean)
|
fun setBoolean(boolean: Boolean)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 写入 null 值
|
* 写入 null 值
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -0,0 +1,226 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.main
|
||||||
|
* CurrentFile RedisLock.kt
|
||||||
|
* LastUpdate 2026-11-23 10:26:28
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.lock
|
||||||
|
|
||||||
|
import com.mingliqiye.utils.exception.RedisLockTimeoutException
|
||||||
|
import com.mingliqiye.utils.logger.MingLiLoggerFactory
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.NonCancellable
|
||||||
|
import kotlinx.coroutines.future.await
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import kotlinx.coroutines.withTimeoutOrNull
|
||||||
|
import org.redisson.api.RLock
|
||||||
|
import org.redisson.api.RedissonClient
|
||||||
|
import java.util.concurrent.CompletionStage
|
||||||
|
import java.util.concurrent.ThreadLocalRandom
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
import java.util.concurrent.atomic.AtomicLong
|
||||||
|
import kotlin.time.Duration.Companion.milliseconds
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 基于 Redisson 的 Redis 分布式锁工具,提供「协程挂起等待」的加锁 API。
|
||||||
|
*
|
||||||
|
* 与 `RLock.lock()` 的线程阻塞不同,加锁/解锁都走 Redisson 异步 API,
|
||||||
|
* 等待期间只挂起协程、不占用业务线程,适合十秒级左右的操作:
|
||||||
|
*
|
||||||
|
* ```kotlin
|
||||||
|
* val lock = RedisLock(redisson)
|
||||||
|
* lock.withLock("settle:2026-11") {
|
||||||
|
* // 同一时刻只有一个节点会执行到这里
|
||||||
|
* doSettle()
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* 特性:
|
||||||
|
* - 默认启用 Redisson 看门狗(`leaseMillis = -1`),业务执行超时也会自动续期
|
||||||
|
* - 支持公平锁、自定义 key 前缀、固定租期
|
||||||
|
* - `tryWithLock` 抢不到锁立即返回 `null`,不等待
|
||||||
|
*
|
||||||
|
* 使用前提:调用方需自行引入 Redisson(本库对 Redisson 仅有 `compileOnly` 依赖),
|
||||||
|
* 建议 Redisson 3.13+ / 4.x。
|
||||||
|
*
|
||||||
|
* 注意:
|
||||||
|
* - **不可重入**:每次加锁都会分配独立的 owner id,同一协程嵌套调用同一个 key 会等待超时
|
||||||
|
* - Redis 锁可能因主从切换、网络分区而丢失,业务仍需幂等/唯一约束兜底
|
||||||
|
* - [leaseMillis] 为正数时为固定租期、不会自动续期,[withLock] 的业务必须在该时间内完成
|
||||||
|
* - 等待超时会抛出 [RedisLockTimeoutException]
|
||||||
|
*
|
||||||
|
* @param redisson Redisson 客户端
|
||||||
|
* @param keyPrefix 锁 key 前缀,默认 `mingli:lock:`
|
||||||
|
* @param fair 是否使用公平锁(`getFairLock`),默认非公平
|
||||||
|
* @param defaultWaitMillis 默认最长等待时间(毫秒),默认 15 秒
|
||||||
|
* @param leaseMillis 租约时间:默认 `-1` 使用看门狗自动续期;正数为固定租期
|
||||||
|
*/
|
||||||
|
class RedisLock @JvmOverloads constructor(
|
||||||
|
private val redisson: RedissonClient,
|
||||||
|
private val keyPrefix: String = DEFAULT_KEY_PREFIX,
|
||||||
|
private val fair: Boolean = false,
|
||||||
|
private val defaultWaitMillis: Long = DEFAULT_WAIT_MILLIS,
|
||||||
|
private val leaseMillis: Long = WATCHDOG_LEASE,
|
||||||
|
) {
|
||||||
|
|
||||||
|
private val log = MingLiLoggerFactory.getLogger<RedisLock>()
|
||||||
|
|
||||||
|
init {
|
||||||
|
require(defaultWaitMillis >= 0) { "defaultWaitMillis 不能为负数: $defaultWaitMillis" }
|
||||||
|
require(leaseMillis == WATCHDOG_LEASE || leaseMillis > 0) {
|
||||||
|
"leaseMillis 必须是 -1(看门狗自动续期)或正数: $leaseMillis"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取锁并在持有期间执行 [block],锁被占用时挂起等待,最长等待 [waitMillis]。
|
||||||
|
*
|
||||||
|
* 正常返回或 [block] 抛异常都会释放锁;等待期间协程被取消也会尽力释放。
|
||||||
|
*
|
||||||
|
* @param key 业务锁 key,实际 Redis key 为 `keyPrefix + key`
|
||||||
|
* @param waitMillis 最长等待时间(毫秒),默认取构造参数
|
||||||
|
* @param block 持锁执行的业务逻辑
|
||||||
|
* @return [block] 的返回值
|
||||||
|
* @throws RedisLockTimeoutException 等待超过 [waitMillis] 仍未获取到锁
|
||||||
|
*/
|
||||||
|
suspend fun <T> withLock(
|
||||||
|
key: String,
|
||||||
|
waitMillis: Long = defaultWaitMillis,
|
||||||
|
block: suspend () -> T,
|
||||||
|
): T {
|
||||||
|
require(key.isNotBlank()) { "锁 key 不能为空" }
|
||||||
|
require(waitMillis >= 0) { "waitMillis 不能为负数: $waitMillis" }
|
||||||
|
val lock = lockOf(key)
|
||||||
|
val ownerId = nextOwnerId()
|
||||||
|
var acquired = false
|
||||||
|
var cancelled = false
|
||||||
|
try {
|
||||||
|
acquired = awaitAcquire(lock, waitMillis, ownerId)
|
||||||
|
if (!acquired) {
|
||||||
|
log.debug("获取 Redis 分布式锁超时: key={}, wait={}ms", lock.name, waitMillis)
|
||||||
|
throw RedisLockTimeoutException(lock.name, waitMillis)
|
||||||
|
}
|
||||||
|
log.debug("已获取 Redis 分布式锁: key={}, owner={}", lock.name, ownerId)
|
||||||
|
return block()
|
||||||
|
} catch (e: CancellationException) {
|
||||||
|
cancelled = true
|
||||||
|
throw e
|
||||||
|
} finally {
|
||||||
|
// 等待中被取消时,锁可能刚好已经拿到,这里统一尝试释放
|
||||||
|
if (acquired || cancelled) {
|
||||||
|
release(lock, ownerId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 尝试获取锁:抢不到立即返回 `null`,不等待;抢到则执行 [block] 并返回其结果。
|
||||||
|
*
|
||||||
|
* 注意:如果 [block] 允许返回 `null`,调用方无法区分「锁被占用」和「业务返回 null」。
|
||||||
|
*
|
||||||
|
* @param key 业务锁 key,实际 Redis key 为 `keyPrefix + key`
|
||||||
|
* @param block 持锁执行的业务逻辑
|
||||||
|
* @return [block] 的返回值;锁被占用时返回 `null`
|
||||||
|
*/
|
||||||
|
suspend fun <T> tryWithLock(
|
||||||
|
key: String,
|
||||||
|
block: suspend () -> T,
|
||||||
|
): T? {
|
||||||
|
require(key.isNotBlank()) { "锁 key 不能为空" }
|
||||||
|
val lock = lockOf(key)
|
||||||
|
val ownerId = nextOwnerId()
|
||||||
|
var acquired = false
|
||||||
|
var cancelled = false
|
||||||
|
try {
|
||||||
|
acquired = awaitAcquire(lock, 0, ownerId)
|
||||||
|
if (!acquired) {
|
||||||
|
log.debug("Redis 分布式锁被占用,跳过执行: key={}", lock.name)
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
log.debug("已获取 Redis 分布式锁: key={}, owner={}", lock.name, ownerId)
|
||||||
|
return block()
|
||||||
|
} catch (e: CancellationException) {
|
||||||
|
cancelled = true
|
||||||
|
throw e
|
||||||
|
} finally {
|
||||||
|
if (acquired || cancelled) {
|
||||||
|
release(lock, ownerId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算某个业务 key 对应的完整 Redis 锁 key(`keyPrefix + key`)。
|
||||||
|
*/
|
||||||
|
fun lockName(key: String): String = keyPrefix + key
|
||||||
|
|
||||||
|
private suspend fun awaitAcquire(lock: RLock, waitMillis: Long, ownerId: Long): Boolean {
|
||||||
|
val future = lock.tryLockAsync(waitMillis, leaseMillis, TimeUnit.MILLISECONDS, ownerId)
|
||||||
|
// RFuture 同时实现了 Future 和 CompletionStage,显式转成 CompletionStage 以匹配 await 扩展
|
||||||
|
return (future as CompletionStage<Boolean>).await()
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun release(lock: RLock, ownerId: Long) {
|
||||||
|
withContext(NonCancellable) {
|
||||||
|
try {
|
||||||
|
val released = withTimeoutOrNull(RELEASE_TIMEOUT_MILLIS.milliseconds) {
|
||||||
|
(lock.unlockAsync(ownerId) as CompletionStage<Void>).await()
|
||||||
|
true
|
||||||
|
}
|
||||||
|
if (released == true) {
|
||||||
|
log.debug("已释放 Redis 分布式锁: key={}, owner={}", lock.name, ownerId)
|
||||||
|
} else {
|
||||||
|
log.warn("释放 Redis 分布式锁超时: key={}, owner={}", lock.name, ownerId)
|
||||||
|
}
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
// 锁可能已因租约到期/主从切换丢失,unlock 会抛 IllegalMonitorStateException
|
||||||
|
log.debug("释放 Redis 分布式锁失败: key={}, owner={}", lock.name, ownerId, t)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun lockOf(key: String): RLock =
|
||||||
|
if (fair) redisson.getFairLock(keyPrefix + key) else redisson.getLock(keyPrefix + key)
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
|
||||||
|
/** 默认锁 key 前缀 */
|
||||||
|
const val DEFAULT_KEY_PREFIX: String = "mingli:lock:"
|
||||||
|
|
||||||
|
/** 默认等待时间:15 秒 */
|
||||||
|
const val DEFAULT_WAIT_MILLIS: Long = 15_000L
|
||||||
|
|
||||||
|
/** 使用 Redisson 看门狗自动续期租约 */
|
||||||
|
const val WATCHDOG_LEASE: Long = -1L
|
||||||
|
|
||||||
|
/** 释放锁的等待上限,避免 Redis 故障时卡住调用方 */
|
||||||
|
private const val RELEASE_TIMEOUT_MILLIS: Long = 2_000L
|
||||||
|
|
||||||
|
/**
|
||||||
|
* owner id 生成器。
|
||||||
|
*
|
||||||
|
* Redisson 用 `clientUuid:threadId` 区分持有者;这里不绑定真实线程,
|
||||||
|
* 而是给每次加锁生成一个唯一的 id,从而支持跨线程的协程解锁。
|
||||||
|
* 随机起始值是为了避开真实线程 id,避免和同一客户端里其它锁语义冲突。
|
||||||
|
*/
|
||||||
|
private val OWNER_IDS = AtomicLong(ThreadLocalRandom.current().nextLong())
|
||||||
|
|
||||||
|
private fun nextOwnerId(): Long = OWNER_IDS.incrementAndGet()
|
||||||
|
}
|
||||||
|
}
|
||||||
+59
-8
@@ -16,21 +16,72 @@
|
|||||||
* ProjectName mingli-utils
|
* ProjectName mingli-utils
|
||||||
* ModuleName mingli-utils.main
|
* ModuleName mingli-utils.main
|
||||||
* CurrentFile ApplicationDestroyedRunner.kt
|
* CurrentFile ApplicationDestroyedRunner.kt
|
||||||
* LastUpdate 2026-03-10 09:04:02
|
* LastUpdate 2026-11-23 15:07:06
|
||||||
* UpdateUser MingLiPro
|
* UpdateUser MingLiPro
|
||||||
*/
|
*/
|
||||||
|
|
||||||
package com.mingliqiye.utils.springboot.annotation
|
package com.mingliqiye.utils.springboot.annotation
|
||||||
|
|
||||||
|
import org.springframework.context.event.ContextClosedEvent
|
||||||
|
import org.springframework.context.event.EventListener
|
||||||
|
import org.springframework.core.Ordered
|
||||||
|
import org.springframework.core.annotation.AliasFor
|
||||||
|
import org.springframework.core.annotation.Order
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 标记在 Spring 上下文关闭时执行的方法。
|
* 应用销毁(上下文关闭)事件监听注解。
|
||||||
* 被标注的方法会在 ContextClosedEvent 触发时由
|
|
||||||
* [com.mingliqiye.utils.springboot.listener.ApplicationListener] 反射调用,
|
|
||||||
* 多个方法按 [order] 升序执行。
|
|
||||||
*
|
*
|
||||||
* @property order 执行顺序,值越小越先执行,默认为 [Int.MIN_VALUE]
|
* 标注在 Spring Bean 的方法上,当 Spring 应用上下文关闭
|
||||||
|
* ([ContextClosedEvent] 发布)时自动调用该方法。
|
||||||
|
*
|
||||||
|
* 已弃用,请改用 [ContextClosedEventListener](监听相同事件,命名更规范)。
|
||||||
|
*
|
||||||
|
* @see ContextClosedEventListener
|
||||||
|
* @see EventListener
|
||||||
|
* @see ContextClosedEvent
|
||||||
*/
|
*/
|
||||||
@Target(AnnotationTarget.FUNCTION)
|
@Deprecated(
|
||||||
|
message = "已弃用,请改用 ContextClosedEventListener(监听相同事件,命名更规范)",
|
||||||
|
replaceWith = ReplaceWith(
|
||||||
|
expression = "ContextClosedEventListener",
|
||||||
|
imports = ["com.mingliqiye.utils.springboot.annotation.ContextClosedEventListener"],
|
||||||
|
),
|
||||||
|
)
|
||||||
|
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.ANNOTATION_CLASS)
|
||||||
|
@Retention(AnnotationRetention.RUNTIME)
|
||||||
|
@MustBeDocumented
|
||||||
|
@EventListener(ContextClosedEvent::class)
|
||||||
|
@Order
|
||||||
annotation class ApplicationDestroyedRunner(
|
annotation class ApplicationDestroyedRunner(
|
||||||
val order: Int = Int.MIN_VALUE,
|
/**
|
||||||
|
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
|
||||||
|
*
|
||||||
|
* 默认为空字符串,表示无条件执行。
|
||||||
|
*/
|
||||||
|
@get:AliasFor(annotation = EventListener::class, attribute = "condition")
|
||||||
|
val condition: String = "",
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 当事件不是 [ContextClosedEvent] 类型时是否仍默认执行监听方法。
|
||||||
|
*
|
||||||
|
* 默认为 `true`。
|
||||||
|
*/
|
||||||
|
@get:AliasFor(annotation = EventListener::class, attribute = "defaultExecution")
|
||||||
|
val defaultExecution: Boolean = true,
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 监听器的唯一标识,用于注册可指定 id 的监听器。
|
||||||
|
*
|
||||||
|
* 默认为空字符串,表示自动生成。
|
||||||
|
*/
|
||||||
|
@get:AliasFor(annotation = EventListener::class, attribute = "id")
|
||||||
|
val id: String = "",
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 监听器的执行顺序,值越小优先级越高。
|
||||||
|
*
|
||||||
|
* 默认为 [Ordered.LOWEST_PRECEDENCE]。
|
||||||
|
*/
|
||||||
|
@get:AliasFor(annotation = Order::class, attribute = "value")
|
||||||
|
val order: Int = Ordered.LOWEST_PRECEDENCE,
|
||||||
)
|
)
|
||||||
|
|||||||
+88
@@ -0,0 +1,88 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.main
|
||||||
|
* CurrentFile ApplicationReadyEventListener.kt
|
||||||
|
* LastUpdate 2026-11-23 15:07:06
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.springboot.annotation
|
||||||
|
|
||||||
|
import org.springframework.boot.context.event.ApplicationReadyEvent
|
||||||
|
import org.springframework.context.event.EventListener
|
||||||
|
import org.springframework.core.Ordered
|
||||||
|
import org.springframework.core.annotation.AliasFor
|
||||||
|
import org.springframework.core.annotation.Order
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 应用就绪事件监听注解。
|
||||||
|
*
|
||||||
|
* 标注在 Spring Bean 的方法上,当 Spring Boot 应用完成启动并就绪
|
||||||
|
* ([ApplicationReadyEvent] 发布)时自动调用该方法,
|
||||||
|
* 等价于 `@EventListener(ApplicationReadyEvent::class)` 的组合简化写法。
|
||||||
|
*
|
||||||
|
* ```kotlin
|
||||||
|
* @Component
|
||||||
|
* class InitTask {
|
||||||
|
* @ApplicationReadyEventListener(order = 0)
|
||||||
|
* fun onReady() {
|
||||||
|
* // 应用就绪后执行的初始化逻辑
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @see EventListener
|
||||||
|
* @see ApplicationReadyEvent
|
||||||
|
*/
|
||||||
|
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.ANNOTATION_CLASS)
|
||||||
|
@Retention(AnnotationRetention.RUNTIME)
|
||||||
|
@MustBeDocumented
|
||||||
|
@EventListener(ApplicationReadyEvent::class)
|
||||||
|
@Order
|
||||||
|
annotation class ApplicationReadyEventListener(
|
||||||
|
/**
|
||||||
|
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
|
||||||
|
*
|
||||||
|
* 默认为空字符串,表示无条件执行。
|
||||||
|
*/
|
||||||
|
@get:AliasFor(annotation = EventListener::class, attribute = "condition")
|
||||||
|
val condition: String = "",
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 当事件不是 [ApplicationReadyEvent] 类型时是否仍默认执行监听方法。
|
||||||
|
*
|
||||||
|
* 默认为 `true`。
|
||||||
|
*/
|
||||||
|
@get:AliasFor(annotation = EventListener::class, attribute = "defaultExecution")
|
||||||
|
val defaultExecution: Boolean = true,
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 监听器的唯一标识,用于注册可指定 id 的监听器。
|
||||||
|
*
|
||||||
|
* 默认为空字符串,表示自动生成。
|
||||||
|
*/
|
||||||
|
@get:AliasFor(annotation = EventListener::class, attribute = "id")
|
||||||
|
val id: String = "",
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 监听器的执行顺序,值越小优先级越高。
|
||||||
|
*
|
||||||
|
* 默认为 [Ordered.LOWEST_PRECEDENCE]。
|
||||||
|
*/
|
||||||
|
@get:AliasFor(annotation = Order::class, attribute = "value")
|
||||||
|
val order: Int = Ordered.LOWEST_PRECEDENCE,
|
||||||
|
)
|
||||||
+59
-8
@@ -16,21 +16,72 @@
|
|||||||
* ProjectName mingli-utils
|
* ProjectName mingli-utils
|
||||||
* ModuleName mingli-utils.main
|
* ModuleName mingli-utils.main
|
||||||
* CurrentFile ApplicationStartedRunner.kt
|
* CurrentFile ApplicationStartedRunner.kt
|
||||||
* LastUpdate 2026-03-11 08:46:40
|
* LastUpdate 2026-11-23 15:07:06
|
||||||
* UpdateUser MingLiPro
|
* UpdateUser MingLiPro
|
||||||
*/
|
*/
|
||||||
|
|
||||||
package com.mingliqiye.utils.springboot.annotation
|
package com.mingliqiye.utils.springboot.annotation
|
||||||
|
|
||||||
|
import org.springframework.boot.context.event.ApplicationReadyEvent
|
||||||
|
import org.springframework.context.event.EventListener
|
||||||
|
import org.springframework.core.Ordered
|
||||||
|
import org.springframework.core.annotation.AliasFor
|
||||||
|
import org.springframework.core.annotation.Order
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 标记在 Spring Boot 应用启动完成后执行的方法。
|
* 应用启动完成事件监听注解。
|
||||||
* 被标注的方法会在 ApplicationStartedEvent 触发时由
|
|
||||||
* [com.mingliqiye.utils.springboot.listener.ApplicationListener] 反射调用,
|
|
||||||
* 多个方法按 [order] 升序执行。
|
|
||||||
*
|
*
|
||||||
* @property order 执行顺序,值越小越先执行,默认为 [Int.MIN_VALUE]
|
* 标注在 Spring Bean 的方法上,当 Spring Boot 应用完成启动并就绪
|
||||||
|
* ([ApplicationReadyEvent] 发布)时自动调用该方法。
|
||||||
|
*
|
||||||
|
* 已弃用,请改用 [ApplicationReadyEventListener](功能完全一致,命名更规范)。
|
||||||
|
*
|
||||||
|
* @see ApplicationReadyEventListener
|
||||||
|
* @see EventListener
|
||||||
|
* @see ApplicationReadyEvent
|
||||||
*/
|
*/
|
||||||
@Target(AnnotationTarget.FUNCTION)
|
@Deprecated(
|
||||||
|
message = "已弃用,请改用 ApplicationReadyEventListener(功能完全一致,命名更规范)",
|
||||||
|
replaceWith = ReplaceWith(
|
||||||
|
expression = "ApplicationReadyEventListener",
|
||||||
|
imports = ["com.mingliqiye.utils.springboot.annotation.ApplicationReadyEventListener"],
|
||||||
|
),
|
||||||
|
)
|
||||||
|
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.ANNOTATION_CLASS)
|
||||||
|
@Retention(AnnotationRetention.RUNTIME)
|
||||||
|
@MustBeDocumented
|
||||||
|
@EventListener(ApplicationReadyEvent::class)
|
||||||
|
@Order
|
||||||
annotation class ApplicationStartedRunner(
|
annotation class ApplicationStartedRunner(
|
||||||
val order: Int = Int.MIN_VALUE,
|
/**
|
||||||
|
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
|
||||||
|
*
|
||||||
|
* 默认为空字符串,表示无条件执行。
|
||||||
|
*/
|
||||||
|
@get:AliasFor(annotation = EventListener::class, attribute = "condition")
|
||||||
|
val condition: String = "",
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 当事件不是 [ApplicationReadyEvent] 类型时是否仍默认执行监听方法。
|
||||||
|
*
|
||||||
|
* 默认为 `true`。
|
||||||
|
*/
|
||||||
|
@get:AliasFor(annotation = EventListener::class, attribute = "defaultExecution")
|
||||||
|
val defaultExecution: Boolean = true,
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 监听器的唯一标识,用于注册可指定 id 的监听器。
|
||||||
|
*
|
||||||
|
* 默认为空字符串,表示自动生成。
|
||||||
|
*/
|
||||||
|
@get:AliasFor(annotation = EventListener::class, attribute = "id")
|
||||||
|
val id: String = "",
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 监听器的执行顺序,值越小优先级越高。
|
||||||
|
*
|
||||||
|
* 默认为 [Ordered.LOWEST_PRECEDENCE]。
|
||||||
|
*/
|
||||||
|
@get:AliasFor(annotation = Order::class, attribute = "value")
|
||||||
|
val order: Int = Ordered.LOWEST_PRECEDENCE,
|
||||||
)
|
)
|
||||||
|
|||||||
+89
@@ -0,0 +1,89 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.main
|
||||||
|
* CurrentFile ContextClosedEventListener.kt
|
||||||
|
* LastUpdate 2026-11-23 15:07:06
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.springboot.annotation
|
||||||
|
|
||||||
|
import org.springframework.context.event.ContextClosedEvent
|
||||||
|
import org.springframework.context.event.EventListener
|
||||||
|
import org.springframework.core.Ordered
|
||||||
|
import org.springframework.core.annotation.AliasFor
|
||||||
|
import org.springframework.core.annotation.Order
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 应用上下文关闭事件监听注解。
|
||||||
|
*
|
||||||
|
* 标注在 Spring Bean 的方法上,当 Spring 应用上下文关闭
|
||||||
|
* ([ContextClosedEvent] 发布)时自动调用该方法,
|
||||||
|
* 等价于 `@EventListener(ContextClosedEvent::class)` 的组合简化写法,
|
||||||
|
* 适用于应用停机前的资源清理、状态保存等场景。
|
||||||
|
*
|
||||||
|
* ```kotlin
|
||||||
|
* @Component
|
||||||
|
* class CleanupTask {
|
||||||
|
* @ContextClosedEventListener
|
||||||
|
* fun onClosed() {
|
||||||
|
* // 上下文关闭前执行的清理逻辑
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @see EventListener
|
||||||
|
* @see ContextClosedEvent
|
||||||
|
*/
|
||||||
|
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.ANNOTATION_CLASS)
|
||||||
|
@Retention(AnnotationRetention.RUNTIME)
|
||||||
|
@MustBeDocumented
|
||||||
|
@EventListener(ContextClosedEvent::class)
|
||||||
|
@Order
|
||||||
|
annotation class ContextClosedEventListener(
|
||||||
|
/**
|
||||||
|
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
|
||||||
|
*
|
||||||
|
* 默认为空字符串,表示无条件执行。
|
||||||
|
*/
|
||||||
|
@get:AliasFor(annotation = EventListener::class, attribute = "condition")
|
||||||
|
val condition: String = "",
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 当事件不是 [ContextClosedEvent] 类型时是否仍默认执行监听方法。
|
||||||
|
*
|
||||||
|
* 默认为 `true`。
|
||||||
|
*/
|
||||||
|
@get:AliasFor(annotation = EventListener::class, attribute = "defaultExecution")
|
||||||
|
val defaultExecution: Boolean = true,
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 监听器的唯一标识,用于注册可指定 id 的监听器。
|
||||||
|
*
|
||||||
|
* 默认为空字符串,表示自动生成。
|
||||||
|
*/
|
||||||
|
@get:AliasFor(annotation = EventListener::class, attribute = "id")
|
||||||
|
val id: String = "",
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 监听器的执行顺序,值越小优先级越高。
|
||||||
|
*
|
||||||
|
* 默认为 [Ordered.LOWEST_PRECEDENCE]。
|
||||||
|
*/
|
||||||
|
@get:AliasFor(annotation = Order::class, attribute = "value")
|
||||||
|
val order: Int = Ordered.LOWEST_PRECEDENCE,
|
||||||
|
)
|
||||||
+94
@@ -0,0 +1,94 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.main
|
||||||
|
* CurrentFile FastServiceScanRegistrar.kt
|
||||||
|
* LastUpdate 2026-11-23 14:21:18
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.springboot.autoconfigure
|
||||||
|
|
||||||
|
import com.mingliqiye.utils.springboot.annotation.FastServiceScan
|
||||||
|
import org.springframework.beans.factory.config.BeanDefinition
|
||||||
|
import org.springframework.beans.factory.support.BeanDefinitionRegistry
|
||||||
|
import org.springframework.beans.factory.support.RootBeanDefinition
|
||||||
|
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar
|
||||||
|
import org.springframework.core.type.AnnotationMetadata
|
||||||
|
import org.springframework.util.ClassUtils
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [FastServiceScan] 的注册器:解析注解上的扫描包,并把 [FastServiceScannerProcessor] 注册成 Bean。
|
||||||
|
*
|
||||||
|
* 通过 Spring 的 `MergedAnnotation.synthesize()` 读取注解,这样 `value` 与 `basePackages`
|
||||||
|
* 之间的 `@AliasFor` 会像 `@MapperScan` 一样被正确合并(两者同时指定不同值时也会按 Spring
|
||||||
|
* 的规则报错,而不是被静默合并)。
|
||||||
|
*
|
||||||
|
* 这里不直接扫描,而是注册一个 `BeanFactoryPostProcessor`,由 Spring 在所有
|
||||||
|
* `BeanDefinitionRegistryPostProcessor`(如 `@MapperScan` 的 `MapperScannerConfigurer`)之后执行,
|
||||||
|
* 从而保证扫描注册时机在 mapper 之后。
|
||||||
|
*/
|
||||||
|
class FastServiceScanRegistrar : ImportBeanDefinitionRegistrar {
|
||||||
|
|
||||||
|
override fun registerBeanDefinitions(
|
||||||
|
importingClassMetadata: AnnotationMetadata,
|
||||||
|
registry: BeanDefinitionRegistry,
|
||||||
|
) {
|
||||||
|
val mergedAnnotation = importingClassMetadata.annotations.get(FastServiceScan::class.java)
|
||||||
|
if (!mergedAnnotation.isPresent) return
|
||||||
|
// synthesize 会应用 @AliasFor,value/basePackages 指向同一个值
|
||||||
|
val annotation = mergedAnnotation.synthesize()
|
||||||
|
val packages = resolvePackages(annotation, importingClassMetadata)
|
||||||
|
if (packages.isEmpty()) return
|
||||||
|
|
||||||
|
if (registry.containsBeanDefinition(PROCESSOR_BEAN_NAME)) return
|
||||||
|
|
||||||
|
val definition = RootBeanDefinition(FastServiceScannerProcessor::class.java)
|
||||||
|
definition.constructorArgumentValues.addIndexedArgumentValue(0, packages.toTypedArray())
|
||||||
|
definition.role = BeanDefinition.ROLE_INFRASTRUCTURE
|
||||||
|
registry.registerBeanDefinition(PROCESSOR_BEAN_NAME, definition)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析注解上的扫描包;未指定时取标注类所在包。
|
||||||
|
*/
|
||||||
|
private fun resolvePackages(
|
||||||
|
annotation: FastServiceScan,
|
||||||
|
importingClassMetadata: AnnotationMetadata,
|
||||||
|
): Set<String> {
|
||||||
|
val packages = LinkedHashSet<String>()
|
||||||
|
|
||||||
|
// value 与 basePackages 互为 @AliasFor,这里各读一遍只是防御;重复值会被 Set 去重
|
||||||
|
for (packageName in annotation.value) {
|
||||||
|
if (packageName.isNotBlank()) packages += packageName.trim()
|
||||||
|
}
|
||||||
|
for (packageName in annotation.basePackages) {
|
||||||
|
if (packageName.isNotBlank()) packages += packageName.trim()
|
||||||
|
}
|
||||||
|
for (baseClass in annotation.basePackageClasses) {
|
||||||
|
packages += ClassUtils.getPackageName(baseClass.java)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (packages.isEmpty()) {
|
||||||
|
packages += ClassUtils.getPackageName(importingClassMetadata.className)
|
||||||
|
}
|
||||||
|
return packages
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val PROCESSOR_BEAN_NAME = "fastServiceScannerProcessor"
|
||||||
|
}
|
||||||
|
}
|
||||||
+137
@@ -0,0 +1,137 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.main
|
||||||
|
* CurrentFile FastServiceScannerProcessor.kt
|
||||||
|
* LastUpdate 2026-11-23 14:05:00
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.springboot.autoconfigure
|
||||||
|
|
||||||
|
import com.mingliqiye.utils.logger.MingLiLoggerFactory
|
||||||
|
import org.springframework.beans.factory.config.BeanFactoryPostProcessor
|
||||||
|
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory
|
||||||
|
import org.springframework.beans.factory.support.BeanDefinitionRegistry
|
||||||
|
import org.springframework.context.annotation.AnnotationBeanNameGenerator
|
||||||
|
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider
|
||||||
|
import org.springframework.core.Ordered
|
||||||
|
import org.springframework.core.type.filter.AnnotationTypeFilter
|
||||||
|
import org.springframework.core.type.filter.AssignableTypeFilter
|
||||||
|
import org.springframework.stereotype.Component
|
||||||
|
import org.springframework.util.ClassUtils
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 扫描继承自 `com.mingliqiye.utils.mybatisplus.FastBaseIService` 或
|
||||||
|
* `com.mingliqiye.utils.mybatisplus.FastBaseIServiceNew3518` 的具体类并注册为 Spring Bean。
|
||||||
|
*
|
||||||
|
* 两个基类分别适配旧版 `mybatis-plus-extension` 与新版 `mybatis-plus-spring`,哪个子类都能扫到。
|
||||||
|
* 基类按类名在运行期探测:缺少对应 MyBatis-Plus 依赖时只跳过该基类,
|
||||||
|
* 不会因为类字面量加载父类失败而抛 `NoClassDefFoundError` 导致启动中断。
|
||||||
|
*
|
||||||
|
* 这是一个 [BeanFactoryPostProcessor],Spring 保证它在所有
|
||||||
|
* `BeanDefinitionRegistryPostProcessor`(包括 `@MapperScan` 的 `MapperScannerConfigurer`)之后执行,
|
||||||
|
* 因此 mapper 的 BeanDefinition 已经注册完毕,服务里的 `baseMapper` 注入不会因为时机问题失败。
|
||||||
|
*
|
||||||
|
* 已经标注 `@Component` / `@Service` 的类会交给普通组件扫描,这里跳过以避免重复注册。
|
||||||
|
*
|
||||||
|
* @param basePackages 要扫描的包
|
||||||
|
*/
|
||||||
|
class FastServiceScannerProcessor(
|
||||||
|
private val basePackages: Array<String>,
|
||||||
|
) : BeanFactoryPostProcessor, Ordered {
|
||||||
|
|
||||||
|
private val log = MingLiLoggerFactory.getLogger<FastServiceScannerProcessor>()
|
||||||
|
|
||||||
|
override fun postProcessBeanFactory(beanFactory: ConfigurableListableBeanFactory) {
|
||||||
|
val registry = beanFactory as? BeanDefinitionRegistry ?: return
|
||||||
|
if (basePackages.isEmpty()) return
|
||||||
|
|
||||||
|
val classLoader = beanFactory.beanClassLoader ?: FastServiceScannerProcessor::class.java.classLoader
|
||||||
|
|
||||||
|
val scanner = ClassPathScanningCandidateComponentProvider(false).apply {
|
||||||
|
// 已有 @Component/@Service 的由组件扫描负责,避免重复注册
|
||||||
|
addExcludeFilter(AnnotationTypeFilter(Component::class.java))
|
||||||
|
}
|
||||||
|
|
||||||
|
var includeFilterCount = 0
|
||||||
|
for (baseClassName in BASE_SERVICE_CLASS_NAMES) {
|
||||||
|
// isPresent 内部 catch Throwable,父类缺失导致的 NoClassDefFoundError 也会返回 false
|
||||||
|
if (!ClassUtils.isPresent(baseClassName, classLoader)) {
|
||||||
|
log.debug("跳过未加载的服务基类: {}", baseClassName)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
val baseClass = try {
|
||||||
|
ClassUtils.forName(baseClassName, classLoader)
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
log.debug("加载服务基类失败,已跳过: {}", baseClassName, t)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// 多个 include filter 之间是 OR 关系
|
||||||
|
scanner.addIncludeFilter(AssignableTypeFilter(baseClass))
|
||||||
|
includeFilterCount++
|
||||||
|
}
|
||||||
|
if (includeFilterCount == 0) {
|
||||||
|
log.debug("没有可用的服务基类,跳过 FastBaseIService 扫描: packages={}", basePackages.toList())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val nameGenerator = AnnotationBeanNameGenerator()
|
||||||
|
var registered = 0
|
||||||
|
|
||||||
|
for (basePackage in basePackages) {
|
||||||
|
for (candidate in scanner.findCandidateComponents(basePackage)) {
|
||||||
|
val className = candidate.beanClassName ?: continue
|
||||||
|
val beanName = nameGenerator.generateBeanName(candidate, registry)
|
||||||
|
val existing = if (registry.containsBeanDefinition(beanName)) {
|
||||||
|
registry.getBeanDefinition(beanName)
|
||||||
|
} else null
|
||||||
|
|
||||||
|
when {
|
||||||
|
existing == null -> {
|
||||||
|
registry.registerBeanDefinition(beanName, candidate)
|
||||||
|
registered++
|
||||||
|
}
|
||||||
|
|
||||||
|
existing.beanClassName == className -> Unit
|
||||||
|
|
||||||
|
else -> {
|
||||||
|
// 不同包下简单类名相同,用全限定名避免覆盖
|
||||||
|
registry.registerBeanDefinition(className, candidate)
|
||||||
|
registered++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.debug(
|
||||||
|
"FastBaseIService/FastBaseIServiceNew3518 扫描完成: packages={}, registered={}",
|
||||||
|
basePackages.toList(),
|
||||||
|
registered,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun getOrder(): Int = Ordered.LOWEST_PRECEDENCE
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
/**
|
||||||
|
* 服务基类全限定名。用字符串而不是类字面量,避免运行期缺少对应 MyBatis-Plus 依赖时加载失败。
|
||||||
|
*/
|
||||||
|
private val BASE_SERVICE_CLASS_NAMES = listOf(
|
||||||
|
"com.mingliqiye.utils.mybatisplus.FastBaseIService",
|
||||||
|
"com.mingliqiye.utils.mybatisplus.FastBaseIServiceNew3518",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-1
@@ -16,7 +16,7 @@
|
|||||||
* ProjectName mingli-utils
|
* ProjectName mingli-utils
|
||||||
* ModuleName mingli-utils.main
|
* ModuleName mingli-utils.main
|
||||||
* CurrentFile Okhttp3AutoConfiguration.kt
|
* CurrentFile Okhttp3AutoConfiguration.kt
|
||||||
* LastUpdate 2026-11-16 11:29:35
|
* LastUpdate 2026-11-18 08:22:35
|
||||||
* UpdateUser MingLiPro
|
* UpdateUser MingLiPro
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@@ -118,6 +118,7 @@ open class Okhttp3AutoConfiguration {
|
|||||||
* 仅当 [okhttp] 字段非空(即客户端由本配置创建)时执行;
|
* 仅当 [okhttp] 字段非空(即客户端由本配置创建)时执行;
|
||||||
* 调用方自行声明的客户端不会被清理。
|
* 调用方自行声明的客户端不会被清理。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@EventListener(ContextClosedEvent::class)
|
@EventListener(ContextClosedEvent::class)
|
||||||
open fun handleContextClosed() {
|
open fun handleContextClosed() {
|
||||||
okhttp?.let {
|
okhttp?.let {
|
||||||
|
|||||||
@@ -1,132 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2026 mingliqiye
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*
|
|
||||||
* ProjectName mingli-utils
|
|
||||||
* ModuleName mingli-utils.main
|
|
||||||
* CurrentFile ApplicationListener.kt
|
|
||||||
* LastUpdate 2026-03-11 08:20:37
|
|
||||||
* UpdateUser MingLiPro
|
|
||||||
*/
|
|
||||||
|
|
||||||
package com.mingliqiye.utils.springboot.listener
|
|
||||||
|
|
||||||
|
|
||||||
import com.mingliqiye.utils.logger.MingLiLoggerFactory
|
|
||||||
import com.mingliqiye.utils.springboot.annotation.ApplicationDestroyedRunner
|
|
||||||
import com.mingliqiye.utils.springboot.annotation.ApplicationStartedRunner
|
|
||||||
import com.mingliqiye.utils.springboot.annotation.Listener
|
|
||||||
import org.springframework.beans.factory.ListableBeanFactory
|
|
||||||
import org.springframework.boot.context.event.ApplicationStartedEvent
|
|
||||||
import org.springframework.context.event.ContextClosedEvent
|
|
||||||
import org.springframework.context.event.EventListener
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 应用生命周期监听器。
|
|
||||||
* 在应用启动完成时扫描容器中所有 Bean 的方法,收集标注了
|
|
||||||
* [ApplicationStartedRunner] / [ApplicationDestroyedRunner] 的方法并按 order 排序,
|
|
||||||
* 分别在 ApplicationStartedEvent 和 ContextClosedEvent 触发时依次反射执行。
|
|
||||||
*/
|
|
||||||
@Listener
|
|
||||||
class ApplicationListener {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 已扫描到的待执行方法集合,键为注解类全名,值为按 order 升序排列的执行数据列表。
|
|
||||||
*/
|
|
||||||
val runningMap = HashMap<String, MutableList<ApplicationRunnerData>>()
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 伴生对象,持有本监听器的日志记录器。
|
|
||||||
*/
|
|
||||||
companion object {
|
|
||||||
private val log = MingLiLoggerFactory.getLogger<ApplicationListener>()
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 扫描容器中的 Bean 方法,收集生命周期回调并按 order 排序。
|
|
||||||
*
|
|
||||||
* 跳过 `org.springframework` 包下的 Bean;每次调用会先清空 [runningMap] 再重新扫描。
|
|
||||||
*
|
|
||||||
* @param applicationContext 用于遍历 Bean 定义与获取 Bean 实例的容器
|
|
||||||
*/
|
|
||||||
fun init(applicationContext: ListableBeanFactory) {
|
|
||||||
runningMap.clear()
|
|
||||||
for (beanName in applicationContext.beanDefinitionNames) {
|
|
||||||
val bean: Any = applicationContext.getBean(beanName)
|
|
||||||
val beanClass: Class<*> = bean.javaClass
|
|
||||||
if (beanClass.getName().startsWith("org.springframework")) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
for (method in beanClass.getDeclaredMethods()) {
|
|
||||||
val annotation: Any =
|
|
||||||
method.getAnnotation(ApplicationStartedRunner::class.java) ?: method.getAnnotation(
|
|
||||||
ApplicationDestroyedRunner::class.java
|
|
||||||
) ?: continue
|
|
||||||
var order: Int
|
|
||||||
var key: Class<out Annotation>
|
|
||||||
when (annotation) {
|
|
||||||
is ApplicationStartedRunner -> {
|
|
||||||
order = annotation.order
|
|
||||||
key = ApplicationStartedRunner::class.java
|
|
||||||
}
|
|
||||||
|
|
||||||
is ApplicationDestroyedRunner -> {
|
|
||||||
order = annotation.order
|
|
||||||
key = ApplicationDestroyedRunner::class.java
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> continue
|
|
||||||
}
|
|
||||||
log.debug("ApplicationListener Scaned [{} - {}] order: {} ", bean.javaClass.name, method, order)
|
|
||||||
val d = runningMap.getOrPut(key.name) {
|
|
||||||
ArrayList()
|
|
||||||
}
|
|
||||||
d.add(
|
|
||||||
ApplicationRunnerData(
|
|
||||||
beanName = beanName, order = order, bean = bean, method = method
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
runningMap.forEach { (string, data) ->
|
|
||||||
data.sortWith(compareBy(ApplicationRunnerData::order))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 应用启动完成事件回调:先执行 [init] 扫描,再按 order 升序执行所有 [ApplicationStartedRunner] 方法。
|
|
||||||
*
|
|
||||||
* @param event 应用启动完成事件
|
|
||||||
*/
|
|
||||||
@EventListener(ApplicationStartedEvent::class)
|
|
||||||
fun applicationStarted(event: ApplicationStartedEvent) {
|
|
||||||
init(event.applicationContext)
|
|
||||||
runningMap[ApplicationStartedRunner::class.java.name]?.forEach {
|
|
||||||
log.debug("Started Event Running {} {} {} - {}", it.beanName, it.bean, it.method, it.order)
|
|
||||||
it.run()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 上下文关闭事件回调:按 order 升序执行所有 [ApplicationDestroyedRunner] 方法。
|
|
||||||
*/
|
|
||||||
@EventListener(ContextClosedEvent::class)
|
|
||||||
fun applicationClosed() {
|
|
||||||
runningMap[ApplicationDestroyedRunner::class.java.name]?.forEach {
|
|
||||||
log.debug("Closed Event Running {} {} {} - {}", it.beanName, it.bean, it.method, it.order)
|
|
||||||
it.run()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright 2026 mingliqiye
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*
|
|
||||||
* ProjectName mingli-utils
|
|
||||||
* ModuleName mingli-utils.main
|
|
||||||
* CurrentFile ApplicationRunnerData.kt
|
|
||||||
* LastUpdate 2026-03-10 09:10:50
|
|
||||||
* UpdateUser MingLiPro
|
|
||||||
*/
|
|
||||||
|
|
||||||
package com.mingliqiye.utils.springboot.listener
|
|
||||||
|
|
||||||
import java.lang.reflect.Method
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 生命周期回调的执行数据,记录一个待反射执行的方法及其宿主 Bean 与执行顺序。
|
|
||||||
*
|
|
||||||
* @property beanName Bean 在容器中的名称
|
|
||||||
* @property order 执行顺序,值越小越先执行
|
|
||||||
* @property bean 方法所属的 Bean 实例
|
|
||||||
* @property method 待执行的回调方法
|
|
||||||
*/
|
|
||||||
data class ApplicationRunnerData(
|
|
||||||
val beanName: String, val order: Int, val bean: Any, val method: Method,
|
|
||||||
) {
|
|
||||||
/**
|
|
||||||
* 反射调用 [method],以 [bean] 为宿主实例执行回调。
|
|
||||||
*/
|
|
||||||
fun run() {
|
|
||||||
method.invoke(bean)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -16,7 +16,7 @@
|
|||||||
* ProjectName mingli-utils
|
* ProjectName mingli-utils
|
||||||
* ModuleName mingli-utils.main
|
* ModuleName mingli-utils.main
|
||||||
* CurrentFile SystemUtil.kt
|
* CurrentFile SystemUtil.kt
|
||||||
* LastUpdate 2026-10-28 22:43:54
|
* LastUpdate 2026-11-23 07:50:35
|
||||||
* UpdateUser MingLiPro
|
* UpdateUser MingLiPro
|
||||||
*/
|
*/
|
||||||
@file:JvmName("SystemUtils")
|
@file:JvmName("SystemUtils")
|
||||||
@@ -264,7 +264,7 @@ val isNotJswarMode: Boolean get() = protocol != "jswar"
|
|||||||
/**
|
/**
|
||||||
* 当前操作系统的行分隔符
|
* 当前操作系统的行分隔符
|
||||||
*/
|
*/
|
||||||
val lineSeparator
|
val lineSeparator: String
|
||||||
get() = System.lineSeparator()
|
get() = System.lineSeparator()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -16,57 +16,204 @@
|
|||||||
* ProjectName mingli-utils
|
* ProjectName mingli-utils
|
||||||
* ModuleName mingli-utils.main
|
* ModuleName mingli-utils.main
|
||||||
* CurrentFile GlobalThreadPool.kt
|
* CurrentFile GlobalThreadPool.kt
|
||||||
* LastUpdate 2026-10-19 20:51:35
|
* LastUpdate 2026-11-23 09:48:34
|
||||||
* UpdateUser MingLiPro
|
* UpdateUser MingLiPro
|
||||||
*/
|
*/
|
||||||
|
|
||||||
package com.mingliqiye.utils.thread
|
package com.mingliqiye.utils.thread
|
||||||
|
|
||||||
import com.mingliqiye.utils.netty.NamedThreadFactory
|
import com.mingliqiye.utils.logger.MingLiLoggerFactory
|
||||||
import com.mingliqiye.utils.system.availableProcessors
|
import com.mingliqiye.utils.system.availableProcessors
|
||||||
import java.util.concurrent.Callable
|
import com.mingliqiye.utils.thread.GlobalThreadPool.SHUTDOWN_HOOK_TIMEOUT_SECONDS
|
||||||
import java.util.concurrent.Future
|
import com.mingliqiye.utils.thread.GlobalThreadPool.cpu
|
||||||
import java.util.concurrent.ScheduledThreadPoolExecutor
|
import com.mingliqiye.utils.thread.GlobalThreadPool.cpuDispatcher
|
||||||
import java.util.concurrent.ThreadPoolExecutor
|
import com.mingliqiye.utils.thread.GlobalThreadPool.io
|
||||||
|
import com.mingliqiye.utils.thread.GlobalThreadPool.ioDispatcher
|
||||||
|
import com.mingliqiye.utils.thread.GlobalThreadPool.main
|
||||||
|
import com.mingliqiye.utils.thread.GlobalThreadPool.mainDispatcher
|
||||||
|
import com.mingliqiye.utils.thread.GlobalThreadPool.pools
|
||||||
|
import com.mingliqiye.utils.thread.GlobalThreadPool.scheduled
|
||||||
|
import com.mingliqiye.utils.thread.GlobalThreadPool.shutdownAll
|
||||||
|
import com.mingliqiye.utils.thread.GlobalThreadPool.submit
|
||||||
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.asCoroutineDispatcher
|
||||||
|
import java.util.concurrent.*
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 全局线程池,按任务类型提供三类共享池,通过 `by lazy` 懒加载。
|
* 全局共享线程池,按负载类型划分,并额外提供协程调度器的统一入口。
|
||||||
|
*
|
||||||
|
* | 池 | 线程数 | 队列 | 适用场景 |
|
||||||
|
* | :--- | :--- | :--- | :--- |
|
||||||
|
* | [main] | 核数 / 2 ~ 核数 | 128 有界 | 通用异步任务 |
|
||||||
|
* | [io] | 核数 x2 ~ 核数 x4 | 1024 有界 | 网络、磁盘等阻塞任务 |
|
||||||
|
* | [cpu] | 核数 | 无界 | 纯计算任务 |
|
||||||
|
* | [scheduled] | 核数 / 2(至少 1) | 延迟队列 | 延迟与周期任务 |
|
||||||
|
*
|
||||||
|
* 所有池的线程均为守护线程,不会阻止 JVM 退出;需要主动释放时调用 [shutdownAll],
|
||||||
|
* 进程正常退出时也会通过注册的关闭钩子自动调用一次(最多等 5 秒,超时强制关闭)。
|
||||||
|
* 各池都是懒加载的,首次访问时才创建。
|
||||||
|
*
|
||||||
|
* 协程调度器([mainDispatcher]、[ioDispatcher]、[cpuDispatcher])与池的对应关系并不统一:
|
||||||
|
* [mainDispatcher] 和 [ioDispatcher] 直接复用 kotlinx-coroutines 的共享调度器
|
||||||
|
* (`asCoroutineDispatcher()` 会把每个续体变成一次线程池入队,高频调度下比
|
||||||
|
* [Dispatchers.Default] 慢数倍);只有 [cpuDispatcher] 绑定 [cpu] 池——计算任务粒度大、
|
||||||
|
* 续体切换少,入队开销可以忽略,换来独立的计算线程与可辨识的线程名。
|
||||||
|
* 线程池也仍然直接面向 ExecutorService / Future / 阻塞任务等场景。
|
||||||
*
|
*
|
||||||
* ```kotlin
|
* ```kotlin
|
||||||
* GlobalThreadPool.io.execute { download() }
|
* GlobalThreadPool.io.execute { download() }
|
||||||
* val result = GlobalThreadPool.cpu.submit { compute() }.get()
|
* val result = GlobalThreadPool.cpu.submit { compute() }.get()
|
||||||
* runAsync { log("done") }
|
* GlobalThreadPool.runAsync { log("done") }
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
object GlobalThreadPool {
|
object GlobalThreadPool {
|
||||||
|
|
||||||
/** IO 密集型全局池:线程多、队列有界,适合网络/磁盘等阻塞任务 */
|
private val log = MingLiLoggerFactory.getLogger<GlobalThreadPool>()
|
||||||
val io: ThreadPoolExecutor by lazy {
|
|
||||||
threadPool("MingLiGlobalIO") {
|
init {
|
||||||
corePoolSize = availableProcessors * 2
|
registerShutdownHook()
|
||||||
maximumPoolSize = availableProcessors * 4
|
}
|
||||||
boundedQueue(1024)
|
|
||||||
|
/** JVM 关闭时为在途任务保留的收尾时长(秒) */
|
||||||
|
private const val SHUTDOWN_HOOK_TIMEOUT_SECONDS = 5L
|
||||||
|
|
||||||
|
/** 可用处理器数,所有池的线程规模都由它推算 */
|
||||||
|
private val cores: Int = availableProcessors
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 全局池拒绝策略:队列满时由提交线程执行,形成背压;
|
||||||
|
* 池已关闭时抛出 [RejectedExecutionException] 而不是静默丢弃,
|
||||||
|
* 避免 [submit] 返回一个永远不会完成的 [Future]。
|
||||||
|
*/
|
||||||
|
private val globalRejectedHandler = RejectedExecutionHandler { runnable, executor ->
|
||||||
|
if (executor.isShutdown) {
|
||||||
|
log.debug("全局池已关闭,拒绝任务提交")
|
||||||
|
throw RejectedExecutionException("global thread pool is shutdown")
|
||||||
|
}
|
||||||
|
log.debug("全局池队列已满,任务改由提交线程 [{}] 执行", Thread.currentThread().name)
|
||||||
|
runnable.run()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 通用全局池:适合短小的异步任务。
|
||||||
|
*
|
||||||
|
* 队列满时由提交线程直接执行,形成天然背压、不丢任务;
|
||||||
|
* 池关闭后提交会抛出 [RejectedExecutionException]。
|
||||||
|
*/
|
||||||
|
@JvmStatic
|
||||||
|
@get:JvmName("main")
|
||||||
|
val main: ThreadPoolExecutor by lazy {
|
||||||
|
val corePoolSize = (cores / 2).coerceAtLeast(1)
|
||||||
|
log.debug("初始化全局池 [main]: core={}, max={}, queue=128, daemon=true", corePoolSize, cores)
|
||||||
|
threadPool("MingLiGlobalMain") {
|
||||||
|
this.corePoolSize = corePoolSize
|
||||||
|
maximumPoolSize = cores
|
||||||
|
boundedQueue(128)
|
||||||
allowCoreThreadTimeout = true
|
allowCoreThreadTimeout = true
|
||||||
daemon = true
|
daemon = true
|
||||||
|
rejectedHandler = globalRejectedHandler
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** CPU 密集型全局池:线程数等于核数,适合纯计算任务 */
|
/**
|
||||||
|
* IO 密集型全局池:线程较多、队列有界,适合网络、磁盘等阻塞任务。
|
||||||
|
*
|
||||||
|
* 核心线程允许空闲超时回收,空闲一段时间后会释放线程资源。
|
||||||
|
*/
|
||||||
|
@JvmStatic
|
||||||
|
@get:JvmName("io")
|
||||||
|
val io: ThreadPoolExecutor by lazy {
|
||||||
|
val corePoolSize = cores * 2
|
||||||
|
log.debug("初始化全局池 [io]: core={}, max={}, queue=1024, daemon=true", corePoolSize, cores * 4)
|
||||||
|
ioThreadPool("MingLiGlobalIO", daemon = true, rejectedHandler = globalRejectedHandler)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CPU 密集型全局池:线程数等于核数,适合纯计算任务。
|
||||||
|
*
|
||||||
|
* 队列无界,突发任务不会被拒绝,但提交速度长期超过消费速度时会持续积压。
|
||||||
|
*/
|
||||||
|
@JvmStatic
|
||||||
|
@get:JvmName("cpu")
|
||||||
val cpu: ThreadPoolExecutor by lazy {
|
val cpu: ThreadPoolExecutor by lazy {
|
||||||
threadPool("MingLiGlobalCPU") {
|
log.debug("初始化全局池 [cpu]: core={}, max={}, queue=unbounded, daemon=true", cores, cores)
|
||||||
corePoolSize = availableProcessors
|
cpuThreadPool("MingLiGlobalCPU", daemon = true, rejectedHandler = globalRejectedHandler)
|
||||||
maximumPoolSize = availableProcessors
|
}
|
||||||
daemon = true
|
|
||||||
|
/**
|
||||||
|
* 全局定时池:承载 [delayRun]、[scheduleWithFixedDelay]、[scheduleAtFixedRate] 等定时任务。
|
||||||
|
*
|
||||||
|
* 已取消的任务会立即移出队列([ScheduledThreadPoolExecutor.getRemoveOnCancelPolicy]),
|
||||||
|
* 关闭时丢弃尚未到期的延迟任务,避免 [shutdownAll] 被长延时任务拖住。
|
||||||
|
*/
|
||||||
|
@JvmStatic
|
||||||
|
@get:JvmName("scheduled")
|
||||||
|
val scheduled: ScheduledThreadPoolExecutor by lazy {
|
||||||
|
val coreSize = (cores / 2).coerceAtLeast(1)
|
||||||
|
log.debug("初始化全局池 [scheduled]: core={}, daemon=true, removeOnCancelPolicy=true", coreSize)
|
||||||
|
scheduledThreadPool(
|
||||||
|
coreSize = coreSize,
|
||||||
|
name = "MingLiGlobalScheduled",
|
||||||
|
daemon = true,
|
||||||
|
).apply {
|
||||||
|
removeOnCancelPolicy = true
|
||||||
|
executeExistingDelayedTasksAfterShutdownPolicy = false
|
||||||
|
continueExistingPeriodicTasksAfterShutdownPolicy = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 全局定时任务池 */
|
// ---- 协程调度器 ----
|
||||||
val scheduled: ScheduledThreadPoolExecutor by lazy {
|
|
||||||
// 包装一层将定时线程设为守护线程,避免阻塞 JVM 退出
|
/**
|
||||||
val base = NamedThreadFactory.of("MingLiGlobalScheduled")
|
* 通用协程调度器:[Dispatchers.Default] 的命名视图。
|
||||||
ScheduledThreadPoolExecutor(
|
*
|
||||||
(availableProcessors / 2).coerceAtLeast(1),
|
* 它不包装 [main] 线程池,而是直接使用 kotlinx-coroutines 的共享调度器
|
||||||
) { runnable -> base.newThread(runnable).apply { isDaemon = true } }
|
* (每个 worker 本地队列 + work-stealing),避免"每个续体一次线程池入队"的开销。
|
||||||
|
* 并行度取 `max(4, CPU 核数)`;等于或大于 Default 核心池时只是命名视图,不做额外限流。
|
||||||
|
*
|
||||||
|
* 共享实例,不要 `close()`;它不归 [shutdownAll] 管。
|
||||||
|
*/
|
||||||
|
@JvmStatic
|
||||||
|
@get:JvmName("mainDispatcher")
|
||||||
|
val mainDispatcher: CoroutineDispatcher by lazy {
|
||||||
|
val parallelism = cores.coerceAtLeast(4)
|
||||||
|
log.debug("初始化协程调度器 [mainDispatcher]: Dispatchers.Default, parallelism={}", parallelism)
|
||||||
|
Dispatchers.Default.limitedParallelism(parallelism, "MingLiGlobalMainDispatcher")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* IO 密集型协程调度器:[Dispatchers.IO] 的命名限流视图,最大并发取 `max(128, CPU 核数)`。
|
||||||
|
*
|
||||||
|
* 底层仍是 IO 的弹性调度器;套一层 `limitedParallelism` 是为了给并发线程数一个
|
||||||
|
* 明确上限,代价是每次分发多一层原子计数。
|
||||||
|
*
|
||||||
|
* 共享实例,不要 `close()`;它不归 [shutdownAll] 管。
|
||||||
|
*/
|
||||||
|
@JvmStatic
|
||||||
|
@get:JvmName("ioDispatcher")
|
||||||
|
val ioDispatcher: CoroutineDispatcher by lazy {
|
||||||
|
val parallelism = 128.coerceAtLeast(cores)
|
||||||
|
log.debug("初始化协程调度器 [ioDispatcher]: Dispatchers.IO, parallelism={}", parallelism)
|
||||||
|
Dispatchers.IO.limitedParallelism(parallelism, "MingLiGlobalIODispatcher")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算专用的协程调度器:绑定独立的 [cpu] 池,线程数等于 CPU 核数,
|
||||||
|
* 线程名为 `MingLiGlobalCPU-*`。
|
||||||
|
*
|
||||||
|
* 这里刻意不复用 [Dispatchers.Default]:计算任务粒度大、续体切换少,每次入队的那点
|
||||||
|
* 开销可以忽略,换来的是与全局 Default 调度器隔离的独立计算线程,以及随
|
||||||
|
* [shutdownAll] 一起关闭(关闭后投递的协程会被取消并转到 IO 清理)。
|
||||||
|
*
|
||||||
|
* 只用于 CPU 密集型计算,不要在里面做阻塞调用。
|
||||||
|
*/
|
||||||
|
@JvmStatic
|
||||||
|
@get:JvmName("cpuDispatcher")
|
||||||
|
val cpuDispatcher: CoroutineDispatcher by lazy {
|
||||||
|
log.debug("初始化协程调度器 [cpuDispatcher]: 绑定全局池 [cpu]")
|
||||||
|
cpu.asCoroutineDispatcher()
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- 便捷提交 ----
|
// ---- 便捷提交 ----
|
||||||
@@ -110,40 +257,191 @@ object GlobalThreadPool {
|
|||||||
@JvmStatic
|
@JvmStatic
|
||||||
fun <T> submit(runnable: Runnable, result: T): Future<T> = io.submit(runnable, result)
|
fun <T> submit(runnable: Runnable, result: T): Future<T> = io.submit(runnable, result)
|
||||||
|
|
||||||
|
// ---- 便捷任务 ----
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 优雅关闭全部线程池(先正常关闭,超时后强制关闭)
|
* 向全局 IO 池提交无返回值任务
|
||||||
|
*
|
||||||
|
* Kotlin 可直接用 lambda,Java 也可直接传 `Runnable`。
|
||||||
|
*
|
||||||
|
* @param block 要执行的任务
|
||||||
|
* @return 任务句柄,可用于等待完成或取消
|
||||||
*/
|
*/
|
||||||
@JvmStatic
|
@JvmStatic
|
||||||
fun shutdownAll() {
|
fun runAsync(block: Runnable): Future<*> = io.submit(block)
|
||||||
io.shutdownGracefully()
|
|
||||||
cpu.shutdownGracefully()
|
|
||||||
scheduled.shutdownGracefully()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 向全局 IO 池提交无返回值任务
|
|
||||||
*/
|
|
||||||
fun runAsync(block: () -> Unit): Future<*> = GlobalThreadPool.io.submit(block)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 向全局 IO 池提交带返回值任务
|
* 向全局 IO 池提交带返回值任务
|
||||||
|
*
|
||||||
|
* Kotlin 可直接用 lambda,Java 也可直接传 `Callable`。
|
||||||
|
*
|
||||||
|
* @param T 任务返回值类型
|
||||||
|
* @param block 要执行的任务
|
||||||
|
* @return 任务句柄,可通过 [Future.get] 获取结果
|
||||||
*/
|
*/
|
||||||
fun <T> callAsync(block: () -> T): Future<T> = GlobalThreadPool.io.submit(Callable(block))
|
@JvmStatic
|
||||||
|
fun <T> callAsync(block: Callable<T>): Future<T> = io.submit(block)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 向全局 CPU 池提交计算任务
|
* 向全局 CPU 池提交计算任务
|
||||||
|
*
|
||||||
|
* Kotlin 可直接用 lambda,Java 也可直接传 `Callable`。
|
||||||
|
*
|
||||||
|
* @param T 任务返回值类型
|
||||||
|
* @param block 要执行的计算任务
|
||||||
|
* @return 任务句柄,可通过 [Future.get] 获取结果
|
||||||
*/
|
*/
|
||||||
fun <T> computeAsync(block: () -> T): Future<T> = GlobalThreadPool.cpu.submit(Callable(block))
|
@JvmStatic
|
||||||
|
fun <T> computeAsync(block: Callable<T>): Future<T> = cpu.submit(block)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 在全局 IO 池执行任务并阻塞等待完成
|
* 在全局 IO 池执行任务并阻塞等待完成
|
||||||
|
*
|
||||||
|
* @param block 要执行的任务
|
||||||
*/
|
*/
|
||||||
fun runAsyncAwait(block: () -> Unit) {
|
@JvmStatic
|
||||||
GlobalThreadPool.io.submit(block).get()
|
fun runAsyncAwait(block: Runnable) {
|
||||||
}
|
io.submit(block).get()
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 在全局 IO 池执行任务并阻塞等待结果
|
* 在全局 IO 池执行任务并阻塞等待结果
|
||||||
|
*
|
||||||
|
* @param T 任务返回值类型
|
||||||
|
* @param block 要执行的任务
|
||||||
|
* @return 任务执行结果
|
||||||
*/
|
*/
|
||||||
fun <T> callAsyncAwait(block: () -> T): T = GlobalThreadPool.io.submit(Callable(block)).get()
|
@JvmStatic
|
||||||
|
fun <T> callAsyncAwait(block: Callable<T>): T = io.submit(block).get()
|
||||||
|
|
||||||
|
// ---- 监控 ----
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 全部全局池,按名称索引,便于统一监控、上报或统计。
|
||||||
|
*
|
||||||
|
* 键依次为 `main`、`io`、`cpu`、`scheduled`,值复用同一批单例。
|
||||||
|
* 每次调用返回新的只读视图;访问会初始化尚未创建的全局池。
|
||||||
|
*/
|
||||||
|
@JvmStatic
|
||||||
|
fun pools(): Map<String, ExecutorService> = executorPools()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 采集全部全局池的运行快照,键与 [pools] 一致。
|
||||||
|
*
|
||||||
|
* 适合周期性上报指标,例如:
|
||||||
|
*
|
||||||
|
* ```kotlin
|
||||||
|
* GlobalThreadPool.snapshotAll().forEach { (name, snapshot) ->
|
||||||
|
* log.info("pool {}: {}", name, snapshot)
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @return 池名称到 [ThreadPoolSnapshot] 的映射
|
||||||
|
*/
|
||||||
|
@JvmStatic
|
||||||
|
fun snapshotAll(): Map<String, ThreadPoolSnapshot> =
|
||||||
|
executorPools().mapValues { (_, pool) -> pool.snapshot() }
|
||||||
|
|
||||||
|
// ---- 生命周期 ----
|
||||||
|
|
||||||
|
private val shutdownState = AtomicBoolean(false)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 是否已经调用过 [shutdownAll]
|
||||||
|
*/
|
||||||
|
@JvmStatic
|
||||||
|
val isShutdown: Boolean get() = shutdownState.get()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 优雅关闭全部全局池。
|
||||||
|
*
|
||||||
|
* 先停止接收新任务,再在统一的截止时间内等待线程池终止;
|
||||||
|
* 到期仍未结束的池会被 [ExecutorService.shutdownNow] 强制关闭。
|
||||||
|
* 全局池关闭后不可复用,重复调用直接返回 `true`;
|
||||||
|
* 之后再提交任务会抛出 [RejectedExecutionException]。
|
||||||
|
*
|
||||||
|
* @param timeout 整体等待时长,从开始关闭时计时,所有池共享
|
||||||
|
* @param unit 时间单位
|
||||||
|
* @return 是否所有池都在截止时间内正常终止
|
||||||
|
*/
|
||||||
|
@JvmStatic
|
||||||
|
@JvmOverloads
|
||||||
|
fun shutdownAll(timeout: Long = 30, unit: TimeUnit = TimeUnit.SECONDS): Boolean {
|
||||||
|
if (!shutdownState.compareAndSet(false, true)) {
|
||||||
|
log.debug("全局线程池已关闭,忽略重复的 shutdownAll 调用")
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
val startNanos = System.nanoTime()
|
||||||
|
val pools = executorPools()
|
||||||
|
log.debug("正在关闭全局线程池: {},等待上限 {} {}", pools.keys, timeout, unit)
|
||||||
|
val deadline = startNanos + unit.toNanos(timeout)
|
||||||
|
pools.values.forEach { it.shutdown() }
|
||||||
|
var terminated = true
|
||||||
|
try {
|
||||||
|
for ((name, pool) in pools) {
|
||||||
|
val remaining = deadline - System.nanoTime()
|
||||||
|
val done = remaining > 0 && pool.awaitTermination(remaining, TimeUnit.NANOSECONDS)
|
||||||
|
if (done) {
|
||||||
|
log.debug("线程池 [{}] 已关闭,完成任务数={}", name, pool.completedTaskCount)
|
||||||
|
} else {
|
||||||
|
terminated = false
|
||||||
|
log.warn("线程池 [{}] 未在期限内终止,执行 shutdownNow()", name)
|
||||||
|
pool.shutdownNow()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (_: InterruptedException) {
|
||||||
|
// 保留中断状态,并强制关闭剩余池
|
||||||
|
Thread.currentThread().interrupt()
|
||||||
|
log.warn("等待全局线程池关闭时线程被中断,强制关闭剩余线程池")
|
||||||
|
pools.values.forEach { it.shutdownNow() }
|
||||||
|
terminated = false
|
||||||
|
}
|
||||||
|
val elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos)
|
||||||
|
if (terminated) {
|
||||||
|
log.debug("全局线程池关闭完成,耗时 {} ms", elapsedMillis)
|
||||||
|
} else {
|
||||||
|
log.warn("全局线程池关闭完成,但存在未正常终止的池,耗时 {} ms", elapsedMillis)
|
||||||
|
}
|
||||||
|
return terminated
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册 JVM 关闭钩子:进程退出前调用 [shutdownAll],给在途任务一段收尾时间。
|
||||||
|
*
|
||||||
|
* 池线程都是守护线程,不注册钩子 JVM 也能正常退出;钩子的意义是把"直接中断"
|
||||||
|
* 变成"最多等 [SHUTDOWN_HOOK_TIMEOUT_SECONDS] 秒再强制关闭"。
|
||||||
|
* JVM 已在关闭中(例如本对象是在别的 shutdown hook 里第一次被访问)或安全管理器
|
||||||
|
* 拒绝注册时静默跳过,不影响全局池继续使用。
|
||||||
|
*/
|
||||||
|
private fun registerShutdownHook() {
|
||||||
|
val hook = Thread({
|
||||||
|
try {
|
||||||
|
log.debug("JVM 关闭钩子触发,开始关闭全局线程池")
|
||||||
|
shutdownAll(SHUTDOWN_HOOK_TIMEOUT_SECONDS, TimeUnit.SECONDS)
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
// 日志框架可能已先于本钩子关闭,这里也不能让异常阻塞 JVM 退出
|
||||||
|
runCatching { log.warn("JVM 关闭钩子中关闭全局线程池失败", t) }
|
||||||
|
}
|
||||||
|
}, "MingLiGlobalPool-Shutdown")
|
||||||
|
try {
|
||||||
|
Runtime.getRuntime().addShutdownHook(hook)
|
||||||
|
log.debug("已注册 JVM 关闭钩子: {}", hook.name)
|
||||||
|
} catch (_: IllegalStateException) {
|
||||||
|
// JVM 已在关闭中,无法再注册钩子
|
||||||
|
log.debug("JVM 已在关闭中,跳过注册关闭钩子")
|
||||||
|
} catch (_: SecurityException) {
|
||||||
|
// 安全管理器拒绝注册钩子
|
||||||
|
log.debug("安全管理器拒绝注册关闭钩子,跳过")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 全部全局池的有序视图,键为池名称
|
||||||
|
*/
|
||||||
|
private fun executorPools(): Map<String, ThreadPoolExecutor> = linkedMapOf(
|
||||||
|
"main" to main,
|
||||||
|
"io" to io,
|
||||||
|
"cpu" to cpu,
|
||||||
|
"scheduled" to scheduled,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.main
|
||||||
|
* CurrentFile SuspendUtils.kt
|
||||||
|
* LastUpdate 2026-11-23 09:14:46
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.suspend
|
||||||
|
|
||||||
|
import kotlinx.coroutines.CompletableDeferred
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import kotlin.contracts.ExperimentalContracts
|
||||||
|
import kotlin.contracts.InvocationKind
|
||||||
|
import kotlin.contracts.contract
|
||||||
|
import kotlin.coroutines.CoroutineContext
|
||||||
|
|
||||||
|
|
||||||
|
@OptIn(ExperimentalContracts::class)
|
||||||
|
suspend inline fun <T> CoroutineContext.withContext(noinline block: suspend CoroutineScope.() -> T): T {
|
||||||
|
contract {
|
||||||
|
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
|
||||||
|
}
|
||||||
|
return withContext(this) {
|
||||||
|
block(this)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun <T> T.asCompletableDeferred() = CompletableDeferred(this)
|
||||||
|
|
||||||
|
|
||||||
|
@OptIn(ExperimentalContracts::class)
|
||||||
|
fun <T> CoroutineContext.runBlocking(block: suspend CoroutineScope.() -> T): T {
|
||||||
|
contract {
|
||||||
|
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
|
||||||
|
}
|
||||||
|
return kotlinx.coroutines.runBlocking(this) {
|
||||||
|
block()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 在当前线程上阻塞运行协程,等价于 [kotlinx.coroutines.runBlocking]。
|
||||||
|
*
|
||||||
|
* 使用调用线程自己的事件循环,不占用 [com.mingliqiye.utils.thread.GlobalThreadPool] 的池线程,
|
||||||
|
* 因此不会被池的并发度限制或关闭影响;需要在本线程之外执行时用 [CoroutineContext.runBlocking]。
|
||||||
|
*/
|
||||||
|
@OptIn(ExperimentalContracts::class)
|
||||||
|
fun <T> runBlocking(block: suspend CoroutineScope.() -> T): T {
|
||||||
|
contract {
|
||||||
|
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
|
||||||
|
}
|
||||||
|
return kotlinx.coroutines.runBlocking {
|
||||||
|
block()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -16,7 +16,7 @@
|
|||||||
* ProjectName mingli-utils
|
* ProjectName mingli-utils
|
||||||
* ModuleName mingli-utils.main
|
* ModuleName mingli-utils.main
|
||||||
* CurrentFile ThreadExt.kt
|
* CurrentFile ThreadExt.kt
|
||||||
* LastUpdate 2026-10-19 20:51:35
|
* LastUpdate 2026-11-23 07:50:35
|
||||||
* UpdateUser MingLiPro
|
* UpdateUser MingLiPro
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@@ -69,7 +69,7 @@ fun Runnable.asThread(
|
|||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
fun Thread.onUncaught(action: (Thread, Throwable) -> Unit): Thread = apply {
|
fun Thread.onUncaught(action: (Thread, Throwable) -> Unit): Thread = apply {
|
||||||
setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler { t, e -> action(t, e) })
|
setUncaughtExceptionHandler { t, e -> action(t, e) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -16,7 +16,7 @@
|
|||||||
* ProjectName mingli-utils
|
* ProjectName mingli-utils
|
||||||
* ModuleName mingli-utils.main
|
* ModuleName mingli-utils.main
|
||||||
* CurrentFile ThreadPoolBuilder.kt
|
* CurrentFile ThreadPoolBuilder.kt
|
||||||
* LastUpdate 2026-10-19 20:51:35
|
* LastUpdate 2026-11-23 09:31:23
|
||||||
* UpdateUser MingLiPro
|
* UpdateUser MingLiPro
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@@ -114,21 +114,9 @@ class ThreadPoolBuilder internal constructor() {
|
|||||||
* @return 配置完成的 [ThreadPoolExecutor]
|
* @return 配置完成的 [ThreadPoolExecutor]
|
||||||
*/
|
*/
|
||||||
fun build(): ThreadPoolExecutor {
|
fun build(): ThreadPoolExecutor {
|
||||||
val baseFactory = threadFactory ?: NamedThreadFactory.of(name)
|
val factory = threadFactory
|
||||||
// 提取局部变量,避免 apply 块内与 Thread 自身属性混淆
|
?.let { decorateThreadFactory(it, daemon, priority, uncaughtHandler) }
|
||||||
val daemonThread = daemon
|
?: namedThreadFactory(name, daemon, priority, uncaughtHandler)
|
||||||
val threadPriority = priority
|
|
||||||
val exceptionHandler = uncaughtHandler
|
|
||||||
// 需要定制 daemon/priority/异常处理时包装一层,否则直接复用
|
|
||||||
val factory = if (daemonThread || threadPriority != Thread.NORM_PRIORITY || exceptionHandler != null) {
|
|
||||||
ThreadFactory { runnable ->
|
|
||||||
baseFactory.newThread(runnable).apply {
|
|
||||||
isDaemon = daemonThread
|
|
||||||
this.priority = threadPriority
|
|
||||||
exceptionHandler?.let { setUncaughtExceptionHandler(it) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else baseFactory
|
|
||||||
return ThreadPoolExecutor(
|
return ThreadPoolExecutor(
|
||||||
corePoolSize,
|
corePoolSize,
|
||||||
maximumPoolSize,
|
maximumPoolSize,
|
||||||
@@ -143,6 +131,51 @@ class ThreadPoolBuilder internal constructor() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建带名称的线程工厂,可选配置守护线程、优先级与未捕获异常处理器。
|
||||||
|
*
|
||||||
|
* 适合与 JDK 原生线程池(如 [ScheduledThreadPoolExecutor])搭配使用:
|
||||||
|
*
|
||||||
|
* ```kotlin
|
||||||
|
* val scheduler = ScheduledThreadPoolExecutor(1, namedThreadFactory("scheduler", daemon = true))
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @param name 线程名称前缀,实际线程名为 `name-1`、`name-2` ...
|
||||||
|
* @param daemon 是否创建守护线程
|
||||||
|
* @param priority 线程优先级
|
||||||
|
* @param uncaughtHandler 未捕获异常处理器,为 null 时使用线程默认处理器
|
||||||
|
*/
|
||||||
|
@JvmOverloads
|
||||||
|
fun namedThreadFactory(
|
||||||
|
name: String = "MingLiPool",
|
||||||
|
daemon: Boolean = false,
|
||||||
|
priority: Int = Thread.NORM_PRIORITY,
|
||||||
|
uncaughtHandler: Thread.UncaughtExceptionHandler? = null,
|
||||||
|
): ThreadFactory = decorateThreadFactory(
|
||||||
|
NamedThreadFactory.of(name),
|
||||||
|
daemon,
|
||||||
|
priority,
|
||||||
|
uncaughtHandler,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按需装饰线程工厂:需要定制守护线程、优先级或异常处理器时包一层,否则原样返回。
|
||||||
|
*/
|
||||||
|
private fun decorateThreadFactory(
|
||||||
|
base: ThreadFactory,
|
||||||
|
daemon: Boolean,
|
||||||
|
priority: Int,
|
||||||
|
uncaughtHandler: Thread.UncaughtExceptionHandler?,
|
||||||
|
): ThreadFactory = if (daemon || priority != Thread.NORM_PRIORITY || uncaughtHandler != null) {
|
||||||
|
ThreadFactory { runnable ->
|
||||||
|
base.newThread(runnable).apply {
|
||||||
|
isDaemon = daemon
|
||||||
|
this.priority = priority
|
||||||
|
uncaughtHandler?.let { setUncaughtExceptionHandler(it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else base
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 以 DSL 方式构建线程池
|
* 以 DSL 方式构建线程池
|
||||||
*
|
*
|
||||||
@@ -195,22 +228,45 @@ fun cachedThreadPool(name: String = "MingLiCachedPool"): ThreadPoolExecutor =
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建 IO 密集型线程池:更多线程 + 有界队列
|
* 创建 IO 密集型线程池:更多线程 + 有界队列
|
||||||
|
*
|
||||||
|
* @param name 线程池名称
|
||||||
|
* @param daemon 线程是否为守护线程
|
||||||
|
* @param rejectedHandler 任务拒绝策略,默认为由提交线程执行
|
||||||
*/
|
*/
|
||||||
fun ioThreadPool(name: String = "MingLiIoPool"): ThreadPoolExecutor =
|
@JvmOverloads
|
||||||
|
fun ioThreadPool(
|
||||||
|
name: String = "MingLiIoPool",
|
||||||
|
daemon: Boolean = false,
|
||||||
|
rejectedHandler: RejectedExecutionHandler = ThreadPoolExecutor.CallerRunsPolicy(),
|
||||||
|
corePoolSize: Int = availableProcessors * 2,
|
||||||
|
): ThreadPoolExecutor =
|
||||||
threadPool(name) {
|
threadPool(name) {
|
||||||
corePoolSize = availableProcessors * 2
|
this.corePoolSize = corePoolSize
|
||||||
maximumPoolSize = availableProcessors * 4
|
maximumPoolSize = availableProcessors * 4
|
||||||
boundedQueue(1024)
|
boundedQueue(1024)
|
||||||
allowCoreThreadTimeout = true
|
allowCoreThreadTimeout = true
|
||||||
|
this.daemon = daemon
|
||||||
|
this.rejectedHandler = rejectedHandler
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建 CPU 密集型线程池:线程数等于核数,避免上下文切换开销
|
* 创建 CPU 密集型线程池:线程数等于核数,避免上下文切换开销
|
||||||
|
*
|
||||||
|
* @param name 线程池名称
|
||||||
|
* @param daemon 线程是否为守护线程
|
||||||
|
* @param rejectedHandler 任务拒绝策略,默认为由提交线程执行
|
||||||
*/
|
*/
|
||||||
fun cpuThreadPool(name: String = "MingLiCpuPool"): ThreadPoolExecutor =
|
@JvmOverloads
|
||||||
|
fun cpuThreadPool(
|
||||||
|
name: String = "MingLiCpuPool",
|
||||||
|
daemon: Boolean = false,
|
||||||
|
rejectedHandler: RejectedExecutionHandler = ThreadPoolExecutor.CallerRunsPolicy(),
|
||||||
|
): ThreadPoolExecutor =
|
||||||
threadPool(name) {
|
threadPool(name) {
|
||||||
corePoolSize = availableProcessors
|
corePoolSize = availableProcessors
|
||||||
maximumPoolSize = availableProcessors
|
maximumPoolSize = availableProcessors
|
||||||
|
this.daemon = daemon
|
||||||
|
this.rejectedHandler = rejectedHandler
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -218,9 +274,12 @@ fun cpuThreadPool(name: String = "MingLiCpuPool"): ThreadPoolExecutor =
|
|||||||
*
|
*
|
||||||
* @param coreSize 核心线程数,默认 CPU 核数 / 2(至少 1)
|
* @param coreSize 核心线程数,默认 CPU 核数 / 2(至少 1)
|
||||||
* @param name 线程池名称
|
* @param name 线程池名称
|
||||||
|
* @param daemon 线程是否为守护线程
|
||||||
*/
|
*/
|
||||||
|
@JvmOverloads
|
||||||
fun scheduledThreadPool(
|
fun scheduledThreadPool(
|
||||||
coreSize: Int = (availableProcessors / 2).coerceAtLeast(1),
|
coreSize: Int = (availableProcessors / 2).coerceAtLeast(1),
|
||||||
name: String = "MingLiScheduledPool",
|
name: String = "MingLiScheduledPool",
|
||||||
|
daemon: Boolean = false,
|
||||||
): ScheduledThreadPoolExecutor =
|
): ScheduledThreadPoolExecutor =
|
||||||
ScheduledThreadPoolExecutor(coreSize, NamedThreadFactory.of(name))
|
ScheduledThreadPoolExecutor(coreSize, namedThreadFactory(name, daemon = daemon))
|
||||||
|
|||||||
@@ -16,7 +16,7 @@
|
|||||||
* ProjectName mingli-utils
|
* ProjectName mingli-utils
|
||||||
* ModuleName mingli-utils.main
|
* ModuleName mingli-utils.main
|
||||||
* CurrentFile ThreadUtils.kt
|
* CurrentFile ThreadUtils.kt
|
||||||
* LastUpdate 2026-02-09 20:14:22
|
* LastUpdate 2026-11-22 10:03:03
|
||||||
* UpdateUser MingLiPro
|
* UpdateUser MingLiPro
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@@ -134,4 +134,5 @@ object ThreadUtils {
|
|||||||
append("\n\n")
|
append("\n\n")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,7 +16,7 @@
|
|||||||
* ProjectName mingli-utils
|
* ProjectName mingli-utils
|
||||||
* ModuleName mingli-utils.main
|
* ModuleName mingli-utils.main
|
||||||
* CurrentFile Tuples.kt
|
* CurrentFile Tuples.kt
|
||||||
* LastUpdate 2026-11-17 20:29:54
|
* LastUpdate 2026-11-17 21:11:31
|
||||||
* UpdateUser MingLiPro
|
* UpdateUser MingLiPro
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@@ -34,6 +34,32 @@ import java.io.Serializable
|
|||||||
*/
|
*/
|
||||||
abstract class Tuple(val size: Int = 1) : Serializable, Iterable<Any>, Comparable<Tuple> {
|
abstract class Tuple(val size: Int = 1) : Serializable, Iterable<Any>, Comparable<Tuple> {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按字典序比较当前元组与另一个元组。
|
||||||
|
*
|
||||||
|
* 从第 1 个元素开始逐位比较:两个元素类型相同且都实现 [Comparable] 时按自然顺序比较,
|
||||||
|
* 否则按元素的字符串形式([toString])比较。
|
||||||
|
* 公共位置元素全部相等时,元素个数较少的元组视为较小。
|
||||||
|
*
|
||||||
|
* @param other 要比较的目标元组
|
||||||
|
* @return 负数、零或正数,分别表示当前元组小于、等于或大于 [other]
|
||||||
|
*/
|
||||||
|
override fun compareTo(other: Tuple): Int {
|
||||||
|
val minSize = minOf(size, other.size)
|
||||||
|
for (i in 0..<minSize) {
|
||||||
|
val a = get(i)
|
||||||
|
val b = other.get(i)
|
||||||
|
val result = if (a is Comparable<*> && b is Comparable<*> && a.javaClass == b.javaClass) {
|
||||||
|
@Suppress("UNCHECKED_CAST")
|
||||||
|
(a as Comparable<Any>).compareTo(b)
|
||||||
|
} else {
|
||||||
|
a.toString().compareTo(b.toString())
|
||||||
|
}
|
||||||
|
if (result != 0) return result
|
||||||
|
}
|
||||||
|
return size.compareTo(other.size)
|
||||||
|
}
|
||||||
|
|
||||||
override fun iterator(): Iterator<Any> {
|
override fun iterator(): Iterator<Any> {
|
||||||
return toMutableList().iterator()
|
return toMutableList().iterator()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,142 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.test
|
||||||
|
* CurrentFile TestHash.kt
|
||||||
|
* LastUpdate 2026-11-18 11:17:46
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils
|
||||||
|
|
||||||
|
import com.mingliqiye.utils.base.BaseType
|
||||||
|
import com.mingliqiye.utils.hash.code.Md2Codec
|
||||||
|
import com.mingliqiye.utils.hash.code.Md5Codec
|
||||||
|
import com.mingliqiye.utils.hash.code.MessageDigestCodec
|
||||||
|
import com.mingliqiye.utils.hash.code.Sha1Codec
|
||||||
|
import com.mingliqiye.utils.hash.code.Sha224Codec
|
||||||
|
import com.mingliqiye.utils.hash.code.Sha256Codec
|
||||||
|
import com.mingliqiye.utils.hash.code.Sha3224Codec
|
||||||
|
import com.mingliqiye.utils.hash.code.Sha3256Codec
|
||||||
|
import com.mingliqiye.utils.hash.code.Sha3384Codec
|
||||||
|
import com.mingliqiye.utils.hash.code.Sha3512Codec
|
||||||
|
import com.mingliqiye.utils.hash.code.Sha384Codec
|
||||||
|
import com.mingliqiye.utils.hash.code.Sha512224Codec
|
||||||
|
import com.mingliqiye.utils.hash.code.Sha512256Codec
|
||||||
|
import com.mingliqiye.utils.hash.code.Sha512Codec
|
||||||
|
import com.mingliqiye.utils.hash.code.HashCodec
|
||||||
|
import org.junit.jupiter.api.Assertions.*
|
||||||
|
import org.junit.jupiter.api.Test
|
||||||
|
import java.io.FilterInputStream
|
||||||
|
import java.nio.file.Files
|
||||||
|
import java.security.MessageDigest
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [HashCodec] 及其全部内置算法实现的测试。
|
||||||
|
*/
|
||||||
|
class TestHash {
|
||||||
|
|
||||||
|
private val codecs: List<Pair<HashCodec, String>> = listOf(
|
||||||
|
Md2Codec() to "MD2",
|
||||||
|
Md5Codec() to "MD5",
|
||||||
|
Sha1Codec() to "SHA-1",
|
||||||
|
Sha224Codec() to "SHA-224",
|
||||||
|
Sha256Codec() to "SHA-256",
|
||||||
|
Sha384Codec() to "SHA-384",
|
||||||
|
Sha512Codec() to "SHA-512",
|
||||||
|
Sha512224Codec() to "SHA-512/224",
|
||||||
|
Sha512256Codec() to "SHA-512/256",
|
||||||
|
Sha3224Codec() to "SHA3-224",
|
||||||
|
Sha3256Codec() to "SHA3-256",
|
||||||
|
Sha3384Codec() to "SHA3-384",
|
||||||
|
Sha3512Codec() to "SHA3-512",
|
||||||
|
)
|
||||||
|
|
||||||
|
/** 测试常见算法对 "hello" 的已知哈希向量 */
|
||||||
|
@Test
|
||||||
|
fun knownVectors() {
|
||||||
|
assertEquals("5d41402abc4b2a76b9719d911017c592", Md5Codec().hashHex("hello"))
|
||||||
|
assertEquals("aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d", Sha1Codec().hashHex("hello"))
|
||||||
|
assertEquals(
|
||||||
|
"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824",
|
||||||
|
Sha256Codec().hashHex("hello")
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试全部算法的流式结果与 MessageDigest 直接计算一致,且校验方法正确 */
|
||||||
|
@Test
|
||||||
|
fun allAlgorithmsMatchMessageDigest() {
|
||||||
|
val data = ByteArray(100_000) { (it % 251).toByte() }
|
||||||
|
for ((codec, algorithm) in codecs) {
|
||||||
|
val expected = MessageDigest.getInstance(algorithm).digest(data)
|
||||||
|
assertArrayEquals(expected, codec.hash(data), algorithm)
|
||||||
|
assertArrayEquals(expected, codec.hash(data.inputStream()), algorithm)
|
||||||
|
assertEquals(BaseType.BASE16.encode(expected), codec.hashHex(data), algorithm)
|
||||||
|
assertTrue(codec.verifyHash(data, expected), algorithm)
|
||||||
|
val tampered = expected.copyOf().also { it[0] = (it[0].toInt() xor 1).toByte() }
|
||||||
|
assertFalse(codec.verifyHash(data, tampered), algorithm)
|
||||||
|
assertTrue(codec.verifyHash("hello", codec.hashHex("hello")), algorithm)
|
||||||
|
assertFalse(codec.verifyHash("hello", codec.hashHex("world")), algorithm)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试实现不关闭调用方传入的输入流 */
|
||||||
|
@Test
|
||||||
|
fun doesNotCloseCallerStream() {
|
||||||
|
var closed = false
|
||||||
|
val stream = object : FilterInputStream("hello".byteInputStream()) {
|
||||||
|
override fun close() {
|
||||||
|
closed = true
|
||||||
|
super.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Sha256Codec().hash(stream)
|
||||||
|
assertFalse(closed)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试文件与路径重载结果和字节数组一致 */
|
||||||
|
@Test
|
||||||
|
fun fileAndPathOverloads() {
|
||||||
|
val data = ByteArray(20_000) { (it % 256).toByte() }
|
||||||
|
val path = Files.createTempFile("mingli-hash-test", ".bin")
|
||||||
|
try {
|
||||||
|
Files.write(path, data)
|
||||||
|
val codec = Sha256Codec()
|
||||||
|
assertArrayEquals(codec.hash(data), codec.hash(path))
|
||||||
|
assertArrayEquals(codec.hash(data), codec.hash(path.toFile()))
|
||||||
|
assertEquals(codec.hashHex(data), codec.hashHex(path))
|
||||||
|
assertEquals(codec.hashHex(data), codec.hashHex(path.toFile()))
|
||||||
|
} finally {
|
||||||
|
Files.deleteIfExists(path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试自定义算法名称的扩展基类用法 */
|
||||||
|
@Test
|
||||||
|
fun customAlgorithmViaBaseClass() {
|
||||||
|
val codec = object : MessageDigestCodec("SHA-256") {}
|
||||||
|
assertArrayEquals(Sha256Codec().hash("hello"), codec.hash("hello"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试空输入可正常计算哈希 */
|
||||||
|
@Test
|
||||||
|
fun emptyInput() {
|
||||||
|
val empty = ByteArray(0)
|
||||||
|
for ((codec, algorithm) in codecs) {
|
||||||
|
assertArrayEquals(MessageDigest.getInstance(algorithm).digest(empty), codec.hash(empty), algorithm)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.test
|
||||||
|
* CurrentFile TestTuple.kt
|
||||||
|
* LastUpdate 2026-11-17 21:20:00
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils
|
||||||
|
|
||||||
|
import com.mingliqiye.utils.tuple.Tuple
|
||||||
|
import org.junit.jupiter.api.Assertions.assertEquals
|
||||||
|
import org.junit.jupiter.api.Assertions.assertTrue
|
||||||
|
import org.junit.jupiter.api.Test
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [Tuple] 字典序比较(compareTo)测试。
|
||||||
|
*/
|
||||||
|
class TestTuple {
|
||||||
|
|
||||||
|
/** 测试首元素不同时按首元素自然顺序比较 */
|
||||||
|
@Test
|
||||||
|
fun compareByFirstElement() {
|
||||||
|
assertTrue(Tuple.of(2, "a") > Tuple.of(1, "z"))
|
||||||
|
assertTrue(Tuple.of(1, "z") < Tuple.of(2, "a"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试首元素相同时按后续元素逐位比较 */
|
||||||
|
@Test
|
||||||
|
fun compareByLaterElement() {
|
||||||
|
assertTrue(Tuple.of(1, "b") > Tuple.of(1, "a"))
|
||||||
|
assertTrue(Tuple.of(1, 2, 3) < Tuple.of(1, 2, 4))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试公共前缀相等时元素个数少的元组较小 */
|
||||||
|
@Test
|
||||||
|
fun compareBySizeWhenPrefixEqual() {
|
||||||
|
assertTrue(Tuple.of(1) < Tuple.of(1, 0))
|
||||||
|
assertTrue(Tuple.of(1, 0, 0) > Tuple.of(1, 0))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试元素完全相同的元组比较结果为 0 */
|
||||||
|
@Test
|
||||||
|
fun compareEqualTuples() {
|
||||||
|
assertEquals(0, Tuple.of(1, "a").compareTo(Tuple.of(1, "a")))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试非 Comparable 元素按字符串形式比较且不抛异常 */
|
||||||
|
@Test
|
||||||
|
fun compareNonComparableElements() {
|
||||||
|
val a = Any()
|
||||||
|
val b = Any()
|
||||||
|
assertEquals(a.toString().compareTo(b.toString()), Tuple.of(a).compareTo(Tuple.of(b)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试元组可直接使用 sorted 排序 */
|
||||||
|
@Test
|
||||||
|
fun sortedTuples() {
|
||||||
|
val sorted = listOf(Tuple.of(2, "a"), Tuple.of(1, "z"), Tuple.of(1, "a")).sorted()
|
||||||
|
assertEquals(listOf(listOf(1, "a"), listOf(1, "z"), listOf(2, "a")), sorted.map { it.toList() })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,236 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.test
|
||||||
|
* CurrentFile RedisLockTest.kt
|
||||||
|
* LastUpdate 2026-11-23 10:21:41
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.lock
|
||||||
|
|
||||||
|
import com.mingliqiye.utils.exception.RedisLockTimeoutException
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import org.junit.jupiter.api.Assertions.assertEquals
|
||||||
|
import org.junit.jupiter.api.Assertions.assertFalse
|
||||||
|
import org.junit.jupiter.api.Assertions.assertNull
|
||||||
|
import org.junit.jupiter.api.Assertions.assertThrows
|
||||||
|
import org.junit.jupiter.api.Assertions.assertTrue
|
||||||
|
import org.junit.jupiter.api.Test
|
||||||
|
import org.redisson.api.RFuture
|
||||||
|
import org.redisson.api.RLock
|
||||||
|
import org.redisson.api.RedissonClient
|
||||||
|
import java.lang.reflect.Proxy
|
||||||
|
import java.util.concurrent.CompletableFuture
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RedisLock 的单元测试,通过动态代理模拟 Redisson 客户端,不依赖真实 Redis。
|
||||||
|
*/
|
||||||
|
class RedisLockTest {
|
||||||
|
|
||||||
|
/** 测试正常加锁、执行业务并释放锁,等待时间/租约/owner 传递正确 */
|
||||||
|
@Test
|
||||||
|
fun testWithLockAcquiresAndReleases() = runBlocking {
|
||||||
|
val fake = FakeRedisson(acquireResult = true)
|
||||||
|
val lock = RedisLock(fake.client, keyPrefix = "test:", defaultWaitMillis = 1234)
|
||||||
|
|
||||||
|
var executed = false
|
||||||
|
lock.withLock("order:1") { executed = true }
|
||||||
|
|
||||||
|
assertTrue(executed)
|
||||||
|
assertEquals(listOf("test:order:1"), fake.lockNames)
|
||||||
|
assertEquals("test:order:1", lock.lockName("order:1"))
|
||||||
|
assertEquals(1, fake.acquireCalls.get())
|
||||||
|
assertEquals(1, fake.unlockCalls.get())
|
||||||
|
assertEquals(fake.acquireOwnerId, fake.unlockOwnerId)
|
||||||
|
assertEquals(1234L, fake.lastWaitMillis)
|
||||||
|
assertEquals(RedisLock.WATCHDOG_LEASE, fake.lastLeaseMillis)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试等待超时:抛 RedisLockTimeoutException,业务不执行、不释放锁 */
|
||||||
|
@Test
|
||||||
|
fun testWithLockTimeout() {
|
||||||
|
val fake = FakeRedisson(acquireResult = false)
|
||||||
|
val lock = RedisLock(fake.client)
|
||||||
|
|
||||||
|
var executed = false
|
||||||
|
assertThrows(RedisLockTimeoutException::class.java) {
|
||||||
|
runBlocking {
|
||||||
|
lock.withLock("k", waitMillis = 50) { executed = true }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assertFalse(executed)
|
||||||
|
assertEquals(0, fake.unlockCalls.get())
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试 tryWithLock 抢不到锁时立即返回 null,不等待、不执行 */
|
||||||
|
@Test
|
||||||
|
fun testTryWithLockBusy() = runBlocking {
|
||||||
|
val fake = FakeRedisson(acquireResult = false)
|
||||||
|
val lock = RedisLock(fake.client)
|
||||||
|
|
||||||
|
val result = lock.tryWithLock("k") { "should not run" }
|
||||||
|
|
||||||
|
assertNull(result)
|
||||||
|
assertEquals(0L, fake.lastWaitMillis)
|
||||||
|
assertEquals(0, fake.unlockCalls.get())
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试 tryWithLock 抢到锁时执行并返回结果,随后释放 */
|
||||||
|
@Test
|
||||||
|
fun testTryWithLockSuccess() = runBlocking {
|
||||||
|
val fake = FakeRedisson(acquireResult = true)
|
||||||
|
val lock = RedisLock(fake.client)
|
||||||
|
|
||||||
|
assertEquals("ok", lock.tryWithLock("k") { "ok" })
|
||||||
|
assertEquals(1, fake.unlockCalls.get())
|
||||||
|
assertEquals(fake.acquireOwnerId, fake.unlockOwnerId)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试公平锁配置使用 getFairLock */
|
||||||
|
@Test
|
||||||
|
fun testFairLock() = runBlocking {
|
||||||
|
val fake = FakeRedisson(acquireResult = true)
|
||||||
|
val lock = RedisLock(fake.client, fair = true)
|
||||||
|
|
||||||
|
lock.withLock("k") { }
|
||||||
|
|
||||||
|
assertTrue(fake.fairUsed)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试业务抛异常时依然释放锁 */
|
||||||
|
@Test
|
||||||
|
fun testReleaseOnBlockFailure() {
|
||||||
|
val fake = FakeRedisson(acquireResult = true)
|
||||||
|
val lock = RedisLock(fake.client)
|
||||||
|
|
||||||
|
assertThrows(IllegalStateException::class.java) {
|
||||||
|
runBlocking {
|
||||||
|
lock.withLock("k") { error("boom") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(1, fake.unlockCalls.get())
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试自定义等待时间与固定租期会透传给 Redisson */
|
||||||
|
@Test
|
||||||
|
fun testCustomWaitAndLease() = runBlocking {
|
||||||
|
val fake = FakeRedisson(acquireResult = true)
|
||||||
|
val lock = RedisLock(fake.client, defaultWaitMillis = 100, leaseMillis = 5_000)
|
||||||
|
|
||||||
|
lock.withLock("k", waitMillis = 200) { }
|
||||||
|
|
||||||
|
assertEquals(200L, fake.lastWaitMillis)
|
||||||
|
assertEquals(5_000L, fake.lastLeaseMillis)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 使用动态代理模拟 RedissonClient / RLock。
|
||||||
|
*/
|
||||||
|
private class FakeRedisson(private val acquireResult: Boolean) {
|
||||||
|
|
||||||
|
val lockNames = mutableListOf<String>()
|
||||||
|
val acquireCalls = AtomicInteger()
|
||||||
|
val unlockCalls = AtomicInteger()
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
var acquireOwnerId: Long = -1
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
var unlockOwnerId: Long = -1
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
var lastWaitMillis: Long = -1
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
var lastLeaseMillis: Long = -1
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
var fairUsed: Boolean = false
|
||||||
|
|
||||||
|
private val lock: RLock = Proxy.newProxyInstance(
|
||||||
|
RLock::class.java.classLoader,
|
||||||
|
arrayOf(RLock::class.java),
|
||||||
|
) { proxy, method, args ->
|
||||||
|
when (method.name) {
|
||||||
|
"tryLockAsync" -> {
|
||||||
|
acquireCalls.incrementAndGet()
|
||||||
|
lastWaitMillis = args[0] as Long
|
||||||
|
lastLeaseMillis = args[1] as Long
|
||||||
|
acquireOwnerId = args[3] as Long
|
||||||
|
completedFuture(acquireResult)
|
||||||
|
}
|
||||||
|
|
||||||
|
"unlockAsync" -> {
|
||||||
|
unlockCalls.incrementAndGet()
|
||||||
|
unlockOwnerId = args[0] as Long
|
||||||
|
completedFuture<Void>(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
"getName" -> "fake-lock"
|
||||||
|
"toString" -> "FakeRLock"
|
||||||
|
"hashCode" -> System.identityHashCode(proxy)
|
||||||
|
"equals" -> proxy === args[0]
|
||||||
|
else -> defaultValue(method.returnType)
|
||||||
|
}
|
||||||
|
} as RLock
|
||||||
|
|
||||||
|
val client: RedissonClient = Proxy.newProxyInstance(
|
||||||
|
RedissonClient::class.java.classLoader,
|
||||||
|
arrayOf(RedissonClient::class.java),
|
||||||
|
) { proxy, method, args ->
|
||||||
|
when (method.name) {
|
||||||
|
"getLock" -> {
|
||||||
|
lockNames += args[0] as String
|
||||||
|
fairUsed = false
|
||||||
|
lock
|
||||||
|
}
|
||||||
|
|
||||||
|
"getFairLock" -> {
|
||||||
|
lockNames += args[0] as String
|
||||||
|
fairUsed = true
|
||||||
|
lock
|
||||||
|
}
|
||||||
|
|
||||||
|
"toString" -> "FakeRedisson"
|
||||||
|
"hashCode" -> System.identityHashCode(proxy)
|
||||||
|
"equals" -> proxy === args[0]
|
||||||
|
else -> defaultValue(method.returnType)
|
||||||
|
}
|
||||||
|
} as RedissonClient
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun <V> completedFuture(value: V?): RFuture<V> = object : CompletableFuture<V>(), RFuture<V> {
|
||||||
|
init {
|
||||||
|
complete(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun defaultValue(type: Class<*>): Any? = when (type) {
|
||||||
|
java.lang.Boolean.TYPE -> false
|
||||||
|
java.lang.Byte.TYPE -> 0.toByte()
|
||||||
|
java.lang.Short.TYPE -> 0.toShort()
|
||||||
|
java.lang.Integer.TYPE -> 0
|
||||||
|
java.lang.Long.TYPE -> 0L
|
||||||
|
java.lang.Float.TYPE -> 0f
|
||||||
|
java.lang.Double.TYPE -> 0.0
|
||||||
|
java.lang.Character.TYPE -> '\u0000'
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
+115
@@ -0,0 +1,115 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.test
|
||||||
|
* CurrentFile FastServiceScanRegistrarTest.kt
|
||||||
|
* LastUpdate 2026-11-23 14:21:18
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.springboot.autoconfigure
|
||||||
|
|
||||||
|
import com.mingliqiye.utils.springboot.annotation.FastServiceScan
|
||||||
|
import org.junit.jupiter.api.Assertions.assertArrayEquals
|
||||||
|
import org.junit.jupiter.api.Assertions.assertEquals
|
||||||
|
import org.junit.jupiter.api.Assertions.assertTrue
|
||||||
|
import org.junit.jupiter.api.Test
|
||||||
|
import org.springframework.beans.factory.support.DefaultListableBeanFactory
|
||||||
|
import org.springframework.core.type.AnnotationMetadata
|
||||||
|
|
||||||
|
/**
|
||||||
|
* FastServiceScanRegistrar 的单元测试,不启动 Spring 容器,只验证注解解析与注册行为。
|
||||||
|
*/
|
||||||
|
class FastServiceScanRegistrarTest {
|
||||||
|
|
||||||
|
@FastServiceScan(basePackages = ["com.example.service"])
|
||||||
|
private class ExplicitPackagesConfig
|
||||||
|
|
||||||
|
@FastServiceScan("com.example.value")
|
||||||
|
private class ValueAliasConfig
|
||||||
|
|
||||||
|
@FastServiceScan(basePackageClasses = [FastServiceScanRegistrarTest::class])
|
||||||
|
private class ClassPackagesConfig
|
||||||
|
|
||||||
|
@FastServiceScan
|
||||||
|
private class DefaultPackageConfig
|
||||||
|
|
||||||
|
/** 测试显式 basePackages 会注册扫描器并使用配置的包 */
|
||||||
|
@Test
|
||||||
|
fun testExplicitPackages() {
|
||||||
|
val registry = DefaultListableBeanFactory()
|
||||||
|
val metadata = AnnotationMetadata.introspect(ExplicitPackagesConfig::class.java)
|
||||||
|
|
||||||
|
FastServiceScanRegistrar().registerBeanDefinitions(metadata, registry)
|
||||||
|
|
||||||
|
assertTrue(registry.containsBeanDefinition("fastServiceScannerProcessor"))
|
||||||
|
val beanDefinition = registry.getBeanDefinition("fastServiceScannerProcessor")
|
||||||
|
val packages = beanDefinition.constructorArgumentValues.getIndexedArgumentValue(0, Array<String>::class.java)?.value
|
||||||
|
assertArrayEquals(arrayOf("com.example.service"), packages as Array<*>)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试 value 与 basePackages 的 @AliasFor 生效 */
|
||||||
|
@Test
|
||||||
|
fun testValueAlias() {
|
||||||
|
val registry = DefaultListableBeanFactory()
|
||||||
|
val metadata = AnnotationMetadata.introspect(ValueAliasConfig::class.java)
|
||||||
|
|
||||||
|
FastServiceScanRegistrar().registerBeanDefinitions(metadata, registry)
|
||||||
|
|
||||||
|
val beanDefinition = registry.getBeanDefinition("fastServiceScannerProcessor")
|
||||||
|
val packages = beanDefinition.constructorArgumentValues.getIndexedArgumentValue(0, Array<String>::class.java)?.value
|
||||||
|
assertArrayEquals(arrayOf("com.example.value"), packages as Array<*>)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试 basePackageClasses 会转换为其所在包 */
|
||||||
|
@Test
|
||||||
|
fun testBasePackageClasses() {
|
||||||
|
val registry = DefaultListableBeanFactory()
|
||||||
|
val metadata = AnnotationMetadata.introspect(ClassPackagesConfig::class.java)
|
||||||
|
|
||||||
|
FastServiceScanRegistrar().registerBeanDefinitions(metadata, registry)
|
||||||
|
|
||||||
|
val beanDefinition = registry.getBeanDefinition("fastServiceScannerProcessor")
|
||||||
|
val packages = beanDefinition.constructorArgumentValues.getIndexedArgumentValue(0, Array<String>::class.java)?.value
|
||||||
|
assertArrayEquals(arrayOf("com.mingliqiye.utils.springboot.autoconfigure"), packages as Array<*>)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试不写包名时默认使用标注类所在包 */
|
||||||
|
@Test
|
||||||
|
fun testDefaultPackage() {
|
||||||
|
val registry = DefaultListableBeanFactory()
|
||||||
|
val metadata = AnnotationMetadata.introspect(DefaultPackageConfig::class.java)
|
||||||
|
|
||||||
|
FastServiceScanRegistrar().registerBeanDefinitions(metadata, registry)
|
||||||
|
|
||||||
|
val beanDefinition = registry.getBeanDefinition("fastServiceScannerProcessor")
|
||||||
|
val packages = beanDefinition.constructorArgumentValues.getIndexedArgumentValue(0, Array<String>::class.java)?.value
|
||||||
|
assertArrayEquals(arrayOf("com.mingliqiye.utils.springboot.autoconfigure"), packages as Array<*>)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试重复处理同一个配置类不会重复注册扫描器 */
|
||||||
|
@Test
|
||||||
|
fun testIdempotentRegistration() {
|
||||||
|
val registry = DefaultListableBeanFactory()
|
||||||
|
val metadata = AnnotationMetadata.introspect(ExplicitPackagesConfig::class.java)
|
||||||
|
val registrar = FastServiceScanRegistrar()
|
||||||
|
|
||||||
|
registrar.registerBeanDefinitions(metadata, registry)
|
||||||
|
registrar.registerBeanDefinitions(metadata, registry)
|
||||||
|
|
||||||
|
assertEquals(1, registry.beanDefinitionCount)
|
||||||
|
}
|
||||||
|
}
|
||||||
+76
@@ -0,0 +1,76 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.test
|
||||||
|
* CurrentFile FastServiceScannerProcessorTest.kt
|
||||||
|
* LastUpdate 2026-11-23 14:05:00
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.springboot.autoconfigure
|
||||||
|
|
||||||
|
import com.mingliqiye.utils.mybatisplus.FastBaseIService
|
||||||
|
import com.mingliqiye.utils.mybatisplus.FastBaseIServiceNew3518
|
||||||
|
import com.mingliqiye.utils.mybatisplus.FastBaseMapper
|
||||||
|
import org.junit.jupiter.api.Assertions.assertFalse
|
||||||
|
import org.junit.jupiter.api.Assertions.assertTrue
|
||||||
|
import org.junit.jupiter.api.Test
|
||||||
|
import org.springframework.beans.factory.support.DefaultListableBeanFactory
|
||||||
|
|
||||||
|
private class ScanTestEntity
|
||||||
|
|
||||||
|
private interface ScanTestMapper : FastBaseMapper<ScanTestEntity>
|
||||||
|
|
||||||
|
private class LegacyScanTestService : FastBaseIService<ScanTestEntity, ScanTestMapper>()
|
||||||
|
|
||||||
|
private class NewScanTestService : FastBaseIServiceNew3518<ScanTestEntity, ScanTestMapper>()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* FastServiceScannerProcessor 的扫描测试:两个基类的子类都应被注册。
|
||||||
|
*/
|
||||||
|
class FastServiceScannerProcessorTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testScansBothBaseServices() {
|
||||||
|
val registry = DefaultListableBeanFactory()
|
||||||
|
|
||||||
|
FastServiceScannerProcessor(arrayOf("com.mingliqiye.utils.springboot.autoconfigure"))
|
||||||
|
.postProcessBeanFactory(registry)
|
||||||
|
|
||||||
|
assertTrue(registry.containsBeanDefinition("legacyScanTestService"))
|
||||||
|
assertTrue(registry.containsBeanDefinition("newScanTestService"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试某个基类加载失败时只跳过该基类,不抛 NoClassDefFoundError */
|
||||||
|
@Test
|
||||||
|
fun testMissingBaseClassIsSkipped() {
|
||||||
|
val registry = DefaultListableBeanFactory()
|
||||||
|
registry.beanClassLoader = object : ClassLoader(FastServiceScannerProcessorTest::class.java.classLoader) {
|
||||||
|
override fun loadClass(name: String, resolve: Boolean): Class<*> {
|
||||||
|
if (name == "com.mingliqiye.utils.mybatisplus.FastBaseIService") {
|
||||||
|
throw ClassNotFoundException(name)
|
||||||
|
}
|
||||||
|
return super.loadClass(name, resolve)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
FastServiceScannerProcessor(arrayOf("com.mingliqiye.utils.springboot.autoconfigure"))
|
||||||
|
.postProcessBeanFactory(registry)
|
||||||
|
|
||||||
|
assertTrue(registry.containsBeanDefinition("newScanTestService"))
|
||||||
|
assertFalse(registry.containsBeanDefinition("legacyScanTestService"))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 mingliqiye
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
* ProjectName mingli-utils
|
||||||
|
* ModuleName mingli-utils.test
|
||||||
|
* CurrentFile SuspendUtilsTest.kt
|
||||||
|
* LastUpdate 2026-11-23 09:14:46
|
||||||
|
* UpdateUser MingLiPro
|
||||||
|
*/
|
||||||
|
|
||||||
|
package com.mingliqiye.utils.suspend
|
||||||
|
|
||||||
|
import com.mingliqiye.utils.thread.GlobalThreadPool
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import org.junit.jupiter.api.Assertions.assertNotEquals
|
||||||
|
import org.junit.jupiter.api.Assertions.assertSame
|
||||||
|
import org.junit.jupiter.api.Assertions.assertTrue
|
||||||
|
import org.junit.jupiter.api.Test
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SuspendUtils 协程工具与 [GlobalThreadPool] 调度器的集成测试
|
||||||
|
*/
|
||||||
|
class SuspendUtilsTest {
|
||||||
|
|
||||||
|
/** 测试 CoroutineContext.runBlocking 使用接收者上下文执行协程 */
|
||||||
|
@Test
|
||||||
|
fun testContextRunBlockingUsesReceiverContext() {
|
||||||
|
val caller = Thread.currentThread()
|
||||||
|
val worker = GlobalThreadPool.ioDispatcher.runBlocking { Thread.currentThread() }
|
||||||
|
assertNotEquals(caller, worker, "receiver context was ignored")
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试顶层 runBlocking 使用调用线程的事件循环,不占用全局线程池 */
|
||||||
|
@Test
|
||||||
|
fun testRunBlockingRunsOnCallerThread() {
|
||||||
|
val caller = Thread.currentThread()
|
||||||
|
val thread = com.mingliqiye.utils.suspend.runBlocking { Thread.currentThread() }
|
||||||
|
assertSame(caller, thread)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试 runBlocking 内挂起(delay)后仍能按时恢复 */
|
||||||
|
@Test
|
||||||
|
fun testRunBlockingSupportsDelay() {
|
||||||
|
val start = System.nanoTime()
|
||||||
|
com.mingliqiye.utils.suspend.runBlocking { delay(100) }
|
||||||
|
val elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)
|
||||||
|
assertTrue(elapsedMillis >= 90, "delay resumed too early: ${elapsedMillis}ms")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -16,14 +16,21 @@
|
|||||||
* ProjectName mingli-utils
|
* ProjectName mingli-utils
|
||||||
* ModuleName mingli-utils.test
|
* ModuleName mingli-utils.test
|
||||||
* CurrentFile AsyncTasksTest.kt
|
* CurrentFile AsyncTasksTest.kt
|
||||||
* LastUpdate 2026-10-19 20:58:00
|
* LastUpdate 2026-11-23 09:45:49
|
||||||
* UpdateUser MingLiPro
|
* UpdateUser MingLiPro
|
||||||
*/
|
*/
|
||||||
|
|
||||||
package com.mingliqiye.utils.thread
|
package com.mingliqiye.utils.thread
|
||||||
|
|
||||||
|
import kotlinx.coroutines.ExecutorCoroutineDispatcher
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
import org.junit.jupiter.api.Assertions.assertEquals
|
import org.junit.jupiter.api.Assertions.assertEquals
|
||||||
|
import org.junit.jupiter.api.Assertions.assertFalse
|
||||||
|
import org.junit.jupiter.api.Assertions.assertNotEquals
|
||||||
import org.junit.jupiter.api.Assertions.assertNull
|
import org.junit.jupiter.api.Assertions.assertNull
|
||||||
|
import org.junit.jupiter.api.Assertions.assertSame
|
||||||
import org.junit.jupiter.api.Assertions.assertThrows
|
import org.junit.jupiter.api.Assertions.assertThrows
|
||||||
import org.junit.jupiter.api.Assertions.assertTrue
|
import org.junit.jupiter.api.Assertions.assertTrue
|
||||||
import org.junit.jupiter.api.Test
|
import org.junit.jupiter.api.Test
|
||||||
@@ -254,44 +261,99 @@ class AsyncTasksTest {
|
|||||||
|
|
||||||
// ---- GlobalThreadPool ----
|
// ---- GlobalThreadPool ----
|
||||||
|
|
||||||
/** 测试 GlobalThreadPool 的 io/cpu/scheduled 全局线程池已正确初始化 */
|
/** 测试 GlobalThreadPool 的 main/io/cpu/scheduled 全局线程池已正确初始化 */
|
||||||
@Test
|
@Test
|
||||||
fun testGlobalPools() {
|
fun testGlobalPools() {
|
||||||
|
assertFalse(GlobalThreadPool.isShutdown)
|
||||||
|
assertTrue(GlobalThreadPool.main.corePoolSize > 0)
|
||||||
assertTrue(GlobalThreadPool.io.corePoolSize > 0)
|
assertTrue(GlobalThreadPool.io.corePoolSize > 0)
|
||||||
assertTrue(GlobalThreadPool.cpu.corePoolSize > 0)
|
assertTrue(GlobalThreadPool.cpu.corePoolSize > 0)
|
||||||
assertTrue(GlobalThreadPool.scheduled.corePoolSize > 0)
|
assertTrue(GlobalThreadPool.scheduled.corePoolSize > 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 测试全局池注册表与批量快照的名称、顺序一致 */
|
||||||
|
@Test
|
||||||
|
fun testGlobalPoolRegistry() {
|
||||||
|
val pools = GlobalThreadPool.pools()
|
||||||
|
assertEquals(listOf("main", "io", "cpu", "scheduled"), pools.keys.toList())
|
||||||
|
val snapshots = GlobalThreadPool.snapshotAll()
|
||||||
|
assertEquals(pools.keys.toList(), snapshots.keys.toList())
|
||||||
|
assertTrue(snapshots.getValue("io").maximumPoolSize > 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试全局池的工作线程为守护线程,不会阻止 JVM 退出 */
|
||||||
|
@Test
|
||||||
|
fun testGlobalPoolThreadsAreDaemon() {
|
||||||
|
val daemon = GlobalThreadPool.callAsync { Thread.currentThread().isDaemon }.get(5, TimeUnit.SECONDS)
|
||||||
|
assertTrue(daemon)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试 mainDispatcher 复用 Dispatchers.Default,而不是 main 线程池 */
|
||||||
|
@Test
|
||||||
|
fun testMainDispatcher() = runBlocking {
|
||||||
|
val caller = Thread.currentThread()
|
||||||
|
val thread = withContext(GlobalThreadPool.mainDispatcher) { Thread.currentThread() }
|
||||||
|
assertNotEquals(caller, thread)
|
||||||
|
assertTrue(thread.name.startsWith("DefaultDispatcher-worker"), "unexpected thread: ${thread.name}")
|
||||||
|
assertTrue(thread.isDaemon)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试 dispatcher 映射:main/io 是共享调度器的命名限流视图,cpu 绑定 cpu 池 */
|
||||||
|
@Test
|
||||||
|
fun testDispatchersMapping() {
|
||||||
|
assertEquals("MingLiGlobalMainDispatcher", GlobalThreadPool.mainDispatcher.toString())
|
||||||
|
assertEquals("MingLiGlobalIODispatcher", GlobalThreadPool.ioDispatcher.toString())
|
||||||
|
val cpuExecutor = (GlobalThreadPool.cpuDispatcher as? ExecutorCoroutineDispatcher)?.executor
|
||||||
|
assertSame(GlobalThreadPool.cpu, cpuExecutor)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试 cpuDispatcher 在 MingLiGlobalCPU 的守护线程上执行 */
|
||||||
|
@Test
|
||||||
|
fun testCpuDispatcher() = runBlocking {
|
||||||
|
val thread = withContext(GlobalThreadPool.cpuDispatcher) { Thread.currentThread() }
|
||||||
|
assertTrue(thread.name.startsWith("MingLiGlobalCPU"), "unexpected thread: ${thread.name}")
|
||||||
|
assertTrue(thread.isDaemon)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 测试 ioDispatcher 上的 delay 悬起后仍能按时恢复 */
|
||||||
|
@Test
|
||||||
|
fun testIoDispatcherDelay() = runBlocking {
|
||||||
|
val start = System.nanoTime()
|
||||||
|
withContext(GlobalThreadPool.ioDispatcher) { delay(100) }
|
||||||
|
val elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)
|
||||||
|
assertTrue(elapsedMillis >= 90, "delay resumed too early: ${elapsedMillis}ms")
|
||||||
|
}
|
||||||
|
|
||||||
/** 测试 runAsync 异步执行无返回值任务 */
|
/** 测试 runAsync 异步执行无返回值任务 */
|
||||||
@Test
|
@Test
|
||||||
fun testRunAsync() {
|
fun testRunAsync() {
|
||||||
assertNull(runAsync { }.get(5, TimeUnit.SECONDS))
|
assertNull(GlobalThreadPool.runAsync { }.get(5, TimeUnit.SECONDS))
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 测试 callAsync 在 IO 线程池异步执行并返回结果 */
|
/** 测试 callAsync 在 IO 线程池异步执行并返回结果 */
|
||||||
@Test
|
@Test
|
||||||
fun testCallAsync() {
|
fun testCallAsync() {
|
||||||
assertEquals("io", callAsync { "io" }.get(5, TimeUnit.SECONDS))
|
assertEquals("io", GlobalThreadPool.callAsync { "io" }.get(5, TimeUnit.SECONDS))
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 测试 computeAsync 在 CPU 线程池异步计算并返回结果 */
|
/** 测试 computeAsync 在 CPU 线程池异步计算并返回结果 */
|
||||||
@Test
|
@Test
|
||||||
fun testComputeAsync() {
|
fun testComputeAsync() {
|
||||||
assertEquals(4, computeAsync { 2 + 2 }.get(5, TimeUnit.SECONDS))
|
assertEquals(4, GlobalThreadPool.computeAsync { 2 + 2 }.get(5, TimeUnit.SECONDS))
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 测试 runAsyncAwait 异步执行并阻塞等待完成 */
|
/** 测试 runAsyncAwait 异步执行并阻塞等待完成 */
|
||||||
@Test
|
@Test
|
||||||
fun testRunAsyncAwait() {
|
fun testRunAsyncAwait() {
|
||||||
val counter = AtomicInteger()
|
val counter = AtomicInteger()
|
||||||
runAsyncAwait { counter.incrementAndGet() }
|
GlobalThreadPool.runAsyncAwait { counter.incrementAndGet() }
|
||||||
assertEquals(1, counter.get())
|
assertEquals(1, counter.get())
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 测试 callAsyncAwait 异步执行并阻塞等待返回结果 */
|
/** 测试 callAsyncAwait 异步执行并阻塞等待返回结果 */
|
||||||
@Test
|
@Test
|
||||||
fun testCallAsyncAwait() {
|
fun testCallAsyncAwait() {
|
||||||
assertEquals("await", callAsyncAwait { "await" })
|
assertEquals("await", GlobalThreadPool.callAsyncAwait { "await" })
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 测试 GlobalThreadPool.execute 提交任务并被执行 */
|
/** 测试 GlobalThreadPool.execute 提交任务并被执行 */
|
||||||
|
|||||||
@@ -21,7 +21,9 @@
|
|||||||
~ UpdateUser MingLiPro
|
~ UpdateUser MingLiPro
|
||||||
-->
|
-->
|
||||||
|
|
||||||
<Configuration status="WARN">
|
<Configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:noNamespaceSchemaLocation="log4j2.xsd"
|
||||||
|
status="WARN">
|
||||||
<Appenders>
|
<Appenders>
|
||||||
<Console name="CONSOLE" target="SYSTEM_OUT">
|
<Console name="CONSOLE" target="SYSTEM_OUT">
|
||||||
<PatternLayout
|
<PatternLayout
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user