Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c169064637
|
||
|
|
ae41240806
|
||
|
|
cb7fdb4f19
|
||
|
|
3d1896bd64
|
||
|
|
0e0d2b03cc
|
||
|
|
2e54e3d651
|
||
|
|
528802d881
|
||
|
|
487f956f4f
|
||
|
|
64e3af50ed
|
||
|
|
7760201639
|
||
|
|
713342bbc6
|
||
|
|
988a0c0dc1
|
||
|
|
44ea9b114d
|
||
|
|
3bacf90940
|
@@ -1,10 +1,44 @@
|
||||
# Changelog
|
||||
|
||||

|
||||
|
||||
本文件记录 mingli-utils 各版本的主要变更。
|
||||
|
||||
## [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 种比较场景。
|
||||
@@ -12,6 +46,7 @@
|
||||
## [5.5.1] - 2026-11-17
|
||||
|
||||
### 新增
|
||||
|
||||
- **json**:新增 `reader` / `witer` / `judgment` 三组抽象,为 Jackson2 与 Jackson3 分别提供
|
||||
`JsonReader`、`JsonArrayReader`、`JsonObjectReader`、`JsonWriter`、`ArrayWriter`、`ObjectWriter`
|
||||
与 `ReaderJudgment` 实现(`BaseJsonReader` / `BaseJsonWriter` / `BaseJsonJudgment` 等基类)。
|
||||
@@ -20,6 +55,7 @@
|
||||
`toString()` 输出包含 `zoneId`。
|
||||
|
||||
### 变更
|
||||
|
||||
- **json**:重构转换器体系——移除按类型划分的 `BaseJsonIntConverter`、`BaseJsonStringConverter`
|
||||
等 10 个转换器及 `JsonConverter` 接口,统一由 `BaseJsonConverter` 与 `JsonConverterUtils` 处理;
|
||||
简化 `DateTimeJsonConverter`、`UUIDJsonConverter`、`NetworkEndpointJsonConverter` 与
|
||||
@@ -29,23 +65,28 @@
|
||||
同步适配新的 JSON 转换器体系。
|
||||
|
||||
### 文档
|
||||
|
||||
- 补全 src 下全部 Kotlin 文件的中文 KDoc 与 Java 文件的 Javadoc(约 1.3 万处),
|
||||
覆盖 exception、json、springboot、mybatis/mybatisplus、thread/netty/http、
|
||||
Tuple1~Tuple100 生成类、MediaType 全部枚举项及测试代码;已有文档保持不变。
|
||||
|
||||
## [5.4.4] - 2026-11-17
|
||||
|
||||
- 构建脚本调整(build.gradle.kts 发布配置完善)。
|
||||
- SpringBoot 自动配置重构:新增 `JsonAutoConfiguration` 与 `JacksonBuilder`,
|
||||
精简 Jackson2/Jackson3 JsonApi 自动配置。
|
||||
|
||||
## [5.4.3] - 2026-11-17
|
||||
|
||||
- 新增 `JacksonJsonBuilder` / `JacksonJsonBuilderImpl` 构建器。
|
||||
- `DateTime`、`UUID` 小幅调整;补充 log4j2 测试配置。
|
||||
|
||||
## [5.4.2] - 2026-11
|
||||
|
||||
- 修复 `JSONA.jsonApi` 编译错误。
|
||||
- **mybatisplus**:新增 `FastBaseIServiceNew3518`(适配 MyBatis-Plus 3.5.18)。
|
||||
|
||||
## [5.4.0] - 2026-11
|
||||
|
||||
- **mybatisplus**:新增 `FastBaseIService`。
|
||||
- 全项目统一 Tab 缩进并补全尾随逗号。
|
||||
@@ -1,5 +1,5 @@
|
||||
mingli-utils
|
||||
Copyright 2025 mingliqiye
|
||||
Copyright 2026 mingliqiye
|
||||
|
||||
This product includes software developed by third parties.
|
||||
The original copyright notices and licenses are reproduced below.
|
||||
|
||||
+4
-2
@@ -16,13 +16,12 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils
|
||||
* CurrentFile build.gradle.kts
|
||||
* LastUpdate 2026-11-17 10:19:02
|
||||
* LastUpdate 2026-11-22 07:59:57
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
import java.time.LocalDateTime
|
||||
import java.time.format.DateTimeFormatter
|
||||
import kotlin.math.sign
|
||||
|
||||
/*
|
||||
* Copyright 2026 mingliqiye
|
||||
@@ -112,8 +111,11 @@ dependencies {
|
||||
compileOnly("com.baomidou:mybatis-plus-extension:3.5.15")
|
||||
compileOnly("com.baomidou:mybatis-plus-jsqlparser:3.5.15")
|
||||
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")
|
||||
testImplementation("org.junit.jupiter:junit-jupiter:5.7.1")
|
||||
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
|
||||
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2")
|
||||
testImplementation("com.mingliqiye.logger:logger-log4j2:1.0.9")
|
||||
testImplementation("com.google.code.gson:gson:2.13.2")
|
||||
|
||||
|
||||
+2
-2
@@ -16,10 +16,10 @@
|
||||
# ProjectName mingli-utils
|
||||
# ModuleName mingli-utils
|
||||
# CurrentFile gradle.properties
|
||||
# LastUpdate 2026-11-17 09:07:20
|
||||
# LastUpdate 2026-11-23 09:56:18
|
||||
# UpdateUser MingLiPro
|
||||
#
|
||||
JDKVERSIONS=17
|
||||
GROUPSID=com.mingliqiye.utils
|
||||
ARTIFACTID=mingli-utils
|
||||
VERSIONS=5.5.2
|
||||
VERSIONS=5.6.0
|
||||
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
/*
|
||||
* 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 ApplicationDestroyedRunner.java
|
||||
* LastUpdate 2026-11-18 08:21:37
|
||||
* 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;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 应用销毁(上下文关闭)事件监听注解。
|
||||
*
|
||||
* <p>标注在 Spring Bean 的方法上,当 Spring 应用上下文关闭
|
||||
* ({@link ContextClosedEvent} 发布)时自动调用该方法。</p>
|
||||
*
|
||||
* @deprecated 已弃用,请改用 {@link ContextClosedEventListener}(监听相同事件,命名更规范)。
|
||||
* @see ContextClosedEventListener
|
||||
* @see EventListener
|
||||
* @see ContextClosedEvent
|
||||
*/
|
||||
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
@EventListener(ContextClosedEvent.class)
|
||||
@Order
|
||||
@Deprecated(since = "use ApplicationReadyEventListener")
|
||||
public @interface ApplicationDestroyedRunner {
|
||||
/**
|
||||
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
|
||||
*
|
||||
* @return 条件表达式,默认为空字符串(无条件执行)
|
||||
*/
|
||||
@AliasFor(annotation = EventListener.class, attribute = "condition")
|
||||
String condition() default "";
|
||||
|
||||
/**
|
||||
* 当事件不是 {@link ContextClosedEvent} 类型时是否仍默认执行监听方法。
|
||||
*
|
||||
* @return 是否默认执行,默认为 true
|
||||
*/
|
||||
@AliasFor(annotation = EventListener.class, attribute = "defaultExecution")
|
||||
boolean defaultExecution() default true;
|
||||
|
||||
/**
|
||||
* 监听器的唯一标识,用于注册可指定 id 的监听器。
|
||||
*
|
||||
* @return 监听器 id,默认为空字符串(自动生成)
|
||||
*/
|
||||
@AliasFor(annotation = EventListener.class, attribute = "id")
|
||||
String id() default "";
|
||||
|
||||
/**
|
||||
* 监听器的执行顺序,值越小优先级越高。
|
||||
*
|
||||
* @return 顺序值,默认为 {@link Ordered#LOWEST_PRECEDENCE}
|
||||
* @see Ordered#getOrder()
|
||||
*/
|
||||
@AliasFor(annotation = Order.class, attribute = "value")
|
||||
int order() default Ordered.LOWEST_PRECEDENCE;
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
/*
|
||||
* 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.java
|
||||
* LastUpdate 2026-11-18 08:21:57
|
||||
* 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;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
|
||||
/**
|
||||
* 应用就绪事件监听注解。
|
||||
*
|
||||
* <p>标注在 Spring Bean 的方法上,当 Spring Boot 应用完成启动并就绪
|
||||
* ({@link ApplicationReadyEvent} 发布)时自动调用该方法,
|
||||
* 等价于 {@code @EventListener(ApplicationReadyEvent.class)} 的组合简化写法。</p>
|
||||
*
|
||||
* <p>使用示例:</p>
|
||||
* <pre>{@code
|
||||
* @Component
|
||||
* public class InitTask {
|
||||
* @ApplicationReadyEventListener(order = 0)
|
||||
* public void onReady() {
|
||||
* // 应用就绪后执行的初始化逻辑
|
||||
* }
|
||||
* }
|
||||
* }</pre>
|
||||
*
|
||||
* @see EventListener
|
||||
* @see ApplicationReadyEvent
|
||||
*/
|
||||
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
@Order
|
||||
public @interface ApplicationReadyEventListener {
|
||||
/**
|
||||
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
|
||||
*
|
||||
* @return 条件表达式,默认为空字符串(无条件执行)
|
||||
*/
|
||||
@AliasFor(annotation = EventListener.class, attribute = "condition")
|
||||
String condition() default "";
|
||||
|
||||
/**
|
||||
* 当事件不是 {@link ApplicationReadyEvent} 类型时是否仍默认执行监听方法。
|
||||
*
|
||||
* @return 是否默认执行,默认为 true
|
||||
*/
|
||||
@AliasFor(annotation = EventListener.class, attribute = "defaultExecution")
|
||||
boolean defaultExecution() default true;
|
||||
|
||||
/**
|
||||
* 监听器的唯一标识,用于注册可指定 id 的监听器。
|
||||
*
|
||||
* @return 监听器 id,默认为空字符串(自动生成)
|
||||
*/
|
||||
@AliasFor(annotation = EventListener.class, attribute = "id")
|
||||
String id() default "";
|
||||
|
||||
|
||||
/**
|
||||
* 监听器的执行顺序,值越小优先级越高。
|
||||
*
|
||||
* @return 顺序值,默认为 {@link Ordered#LOWEST_PRECEDENCE}
|
||||
* @see Ordered#getOrder()
|
||||
*/
|
||||
@AliasFor(annotation = Order.class, attribute = "value")
|
||||
int order() default Ordered.LOWEST_PRECEDENCE;
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* 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 ApplicationStartedRunner.java
|
||||
* LastUpdate 2026-11-18 08:21:57
|
||||
* 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;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 应用启动完成事件监听注解。
|
||||
*
|
||||
* <p>标注在 Spring Bean 的方法上,当 Spring Boot 应用完成启动并就绪
|
||||
* ({@link ApplicationReadyEvent} 发布)时自动调用该方法。</p>
|
||||
*
|
||||
* @deprecated 已弃用,请改用 {@link ApplicationReadyEventListener}(功能完全一致,命名更规范)。
|
||||
* @see ApplicationReadyEventListener
|
||||
* @see EventListener
|
||||
* @see ApplicationReadyEvent
|
||||
*/
|
||||
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
@Order
|
||||
@Deprecated(since = "use ApplicationReadyEventListener")
|
||||
public @interface ApplicationStartedRunner {
|
||||
/**
|
||||
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
|
||||
*
|
||||
* @return 条件表达式,默认为空字符串(无条件执行)
|
||||
*/
|
||||
@AliasFor(annotation = EventListener.class, attribute = "condition")
|
||||
String condition() default "";
|
||||
|
||||
/**
|
||||
* 当事件不是 {@link ApplicationReadyEvent} 类型时是否仍默认执行监听方法。
|
||||
*
|
||||
* @return 是否默认执行,默认为 true
|
||||
*/
|
||||
@AliasFor(annotation = EventListener.class, attribute = "defaultExecution")
|
||||
boolean defaultExecution() default true;
|
||||
|
||||
/**
|
||||
* 监听器的唯一标识,用于注册可指定 id 的监听器。
|
||||
*
|
||||
* @return 监听器 id,默认为空字符串(自动生成)
|
||||
*/
|
||||
@AliasFor(annotation = EventListener.class, attribute = "id")
|
||||
String id() default "";
|
||||
|
||||
|
||||
/**
|
||||
* 监听器的执行顺序,值越小优先级越高。
|
||||
*
|
||||
* @return 顺序值,默认为 {@link Ordered#LOWEST_PRECEDENCE}
|
||||
* @see Ordered#getOrder()
|
||||
*/
|
||||
@AliasFor(annotation = Order.class, attribute = "value")
|
||||
int order() default Ordered.LOWEST_PRECEDENCE;
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* 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.java
|
||||
* LastUpdate 2026-11-18 08:21:23
|
||||
* 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;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 应用上下文关闭事件监听注解。
|
||||
*
|
||||
* <p>标注在 Spring Bean 的方法上,当 Spring 应用上下文关闭
|
||||
* ({@link ContextClosedEvent} 发布)时自动调用该方法,
|
||||
* 等价于 {@code @EventListener(ContextClosedEvent.class)} 的组合简化写法,
|
||||
* 适用于应用停机前的资源清理、状态保存等场景。</p>
|
||||
*
|
||||
* <p>使用示例:</p>
|
||||
* <pre>{@code
|
||||
* @Component
|
||||
* public class CleanupTask {
|
||||
* @ContextClosedEventListener
|
||||
* public void onClosed() {
|
||||
* // 上下文关闭前执行的清理逻辑
|
||||
* }
|
||||
* }
|
||||
* }</pre>
|
||||
*
|
||||
* @see EventListener
|
||||
* @see ContextClosedEvent
|
||||
*/
|
||||
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
@EventListener(ContextClosedEvent.class)
|
||||
@Order
|
||||
public @interface ContextClosedEventListener {
|
||||
/**
|
||||
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
|
||||
*
|
||||
* @return 条件表达式,默认为空字符串(无条件执行)
|
||||
*/
|
||||
@AliasFor(annotation = EventListener.class, attribute = "condition")
|
||||
String condition() default "";
|
||||
|
||||
/**
|
||||
* 当事件不是 {@link ContextClosedEvent} 类型时是否仍默认执行监听方法。
|
||||
*
|
||||
* @return 是否默认执行,默认为 true
|
||||
*/
|
||||
@AliasFor(annotation = EventListener.class, attribute = "defaultExecution")
|
||||
boolean defaultExecution() default true;
|
||||
|
||||
/**
|
||||
* 监听器的唯一标识,用于注册可指定 id 的监听器。
|
||||
*
|
||||
* @return 监听器 id,默认为空字符串(自动生成)
|
||||
*/
|
||||
@AliasFor(annotation = EventListener.class, attribute = "id")
|
||||
String id() default "";
|
||||
|
||||
/**
|
||||
* 监听器的执行顺序,值越小优先级越高。
|
||||
*
|
||||
* @return 顺序值,默认为 {@link Ordered#LOWEST_PRECEDENCE}
|
||||
* @see Ordered#getOrder()
|
||||
*/
|
||||
@AliasFor(annotation = Order.class, attribute = "value")
|
||||
int order() default Ordered.LOWEST_PRECEDENCE;
|
||||
}
|
||||
@@ -13,10 +13,10 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
* ProjectName FastBaseMapper.kt
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile SuperStream.java
|
||||
* LastUpdate 2026-10-26 23:22:18
|
||||
* LastUpdate 2026-11-22 10:10:33
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
@@ -26,6 +26,7 @@ import com.mingliqiye.utils.collection.Collections;
|
||||
import com.mingliqiye.utils.functions.P1Function;
|
||||
import com.mingliqiye.utils.functions.P2Function;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jspecify.annotations.NonNull;
|
||||
|
||||
import java.lang.reflect.Array;
|
||||
import java.util.*;
|
||||
@@ -987,7 +988,7 @@ public class SuperStream<T> implements Stream<T> {
|
||||
*/
|
||||
@NotNull
|
||||
@SuppressWarnings("unchecked")
|
||||
public T[] toArray(Class<T> clazz) {
|
||||
public T @NonNull [] toArray(Class<T> clazz) {
|
||||
return stream.toArray(i -> (T[]) Array.newInstance(clazz, i));
|
||||
}
|
||||
|
||||
@@ -997,7 +998,7 @@ public class SuperStream<T> implements Stream<T> {
|
||||
* @return 转换后的Object数组
|
||||
*/
|
||||
@NotNull
|
||||
public Object[] toArray() {
|
||||
public Object @NonNull [] toArray() {
|
||||
return stream.toArray();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2025 mingliqiye
|
||||
* 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.
|
||||
@@ -16,7 +16,7 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile Collection.kt
|
||||
* LastUpdate 2025-09-21 14:36:57
|
||||
* LastUpdate 2026-11-23 07:33:23
|
||||
* 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 实例,并指定比较器。
|
||||
*
|
||||
@@ -980,9 +1012,9 @@ fun toArray(list: List<Char>): CharArray {
|
||||
* @param list 输入的 List
|
||||
* @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())
|
||||
return arrayOf<T>()
|
||||
return arrayOf()
|
||||
return SuperStream.of<T>(list)
|
||||
.toArray(T::class.java)
|
||||
}
|
||||
@@ -995,7 +1027,7 @@ inline fun <reified T> toArray(list: List<T>): Array<T> {
|
||||
* @param clazz 数组元素类型对应的 Class 对象
|
||||
* @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)
|
||||
.toArray(clazz)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile HashUtils.kt
|
||||
* LastUpdate 2026-01-11 09:09:52
|
||||
* LastUpdate 2026-11-18 18:53:11
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
@file:JvmName("HashUtils")
|
||||
|
||||
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
|
||||
|
||||
/**
|
||||
* 计算指定文件的哈希值。
|
||||
*
|
||||
* @param file 要计算哈希值的文件对象
|
||||
* @param algorithm 使用的哈希算法名称(如 SHA-256、MD5 等)
|
||||
* @return 文件的十六进制格式哈希值字符串
|
||||
* @throws IOException 当文件不存在或读取过程中发生 I/O 错误时抛出
|
||||
* @throws NoSuchAlgorithmException 当指定的哈希算法不可用时抛出
|
||||
* 提供 MD2 哈希器的懒加载实例。
|
||||
* 该哈希器输出 128 位摘要,算法已过时,仅用于兼容遗留系统。
|
||||
*/
|
||||
@Throws(IOException::class, NoSuchAlgorithmException::class)
|
||||
fun calculateFileHash(file: File, algorithm: String): String {
|
||||
// 检查文件是否存在
|
||||
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())
|
||||
}
|
||||
@get:JvmName("getMd2Codec")
|
||||
val MD2 by lazy(::Md2Codec)
|
||||
|
||||
/**
|
||||
* 使用 BCrypt 算法对字符串进行加密。
|
||||
*
|
||||
* @param string 需要加密的明文字符串
|
||||
* @return 加密后的 BCrypt 哈希字符串
|
||||
* 提供 MD5 哈希器的懒加载实例。
|
||||
* 该哈希器输出 128 位摘要,存在碰撞漏洞,不得用于安全场景,仅建议非安全性校验。
|
||||
*/
|
||||
fun bcrypt(string: String): String {
|
||||
return hashpw(string)
|
||||
}
|
||||
@get:JvmName("getMd5Codec")
|
||||
val MD5 by lazy(::Md5Codec)
|
||||
|
||||
/**
|
||||
* 验证给定字符串与 BCrypt 哈希是否匹配。
|
||||
*
|
||||
* @param string 明文字符串
|
||||
* @param bcrypted 已经使用 BCrypt 加密的哈希字符串
|
||||
* @return 如果匹配返回 true,否则返回 false
|
||||
* 提供 SHA-1 哈希器的懒加载实例。
|
||||
* 该哈希器输出 160 位摘要,存在碰撞攻击,不得用于安全场景,仅建议非安全性校验。
|
||||
*/
|
||||
fun checkBcrypt(string: String, bcrypted: String): Boolean {
|
||||
return checkpw(string, bcrypted)
|
||||
}
|
||||
@get:JvmName("getSha1Codec")
|
||||
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()))
|
||||
|
||||
}
|
||||
+6
-12
@@ -15,22 +15,16 @@
|
||||
*
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile ApplicationDestroyedRunner.kt
|
||||
* LastUpdate 2026-03-10 09:04:02
|
||||
* CurrentFile Md2Codec.kt
|
||||
* LastUpdate 2026-11-18 11:18:32
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.springboot.annotation
|
||||
package com.mingliqiye.utils.hash.code
|
||||
|
||||
/**
|
||||
* 标记在 Spring 上下文关闭时执行的方法。
|
||||
* 被标注的方法会在 ContextClosedEvent 触发时由
|
||||
* [com.mingliqiye.utils.springboot.listener.ApplicationListener] 反射调用,
|
||||
* 多个方法按 [order] 升序执行。
|
||||
* MD2 哈希编解码器(输出 128 位 / 16 字节)。
|
||||
*
|
||||
* @property order 执行顺序,值越小越先执行,默认为 [Int.MIN_VALUE]
|
||||
* MD2 已过时且存在安全缺陷,仅用于兼容遗留系统,不建议在任何新场景使用。
|
||||
*/
|
||||
@Target(AnnotationTarget.FUNCTION)
|
||||
annotation class ApplicationDestroyedRunner(
|
||||
val order: Int = Int.MIN_VALUE,
|
||||
)
|
||||
class Md2Codec : MessageDigestCodec("MD2")
|
||||
+7
-12
@@ -15,22 +15,17 @@
|
||||
*
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile ApplicationStartedRunner.kt
|
||||
* LastUpdate 2026-03-11 08:46:40
|
||||
* CurrentFile Md5Codec.kt
|
||||
* LastUpdate 2026-11-18 11:18:32
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.springboot.annotation
|
||||
package com.mingliqiye.utils.hash.code
|
||||
|
||||
/**
|
||||
* 标记在 Spring Boot 应用启动完成后执行的方法。
|
||||
* 被标注的方法会在 ApplicationStartedEvent 触发时由
|
||||
* [com.mingliqiye.utils.springboot.listener.ApplicationListener] 反射调用,
|
||||
* 多个方法按 [order] 升序执行。
|
||||
* MD5 哈希编解码器(输出 128 位 / 16 字节)。
|
||||
*
|
||||
* @property order 执行顺序,值越小越先执行,默认为 [Int.MIN_VALUE]
|
||||
* MD5 已被证实存在碰撞漏洞,不得用于数字签名、密码存储等安全场景,
|
||||
* 仅建议用于兼容遗留系统或非安全性校验(如文件完整性粗检)。
|
||||
*/
|
||||
@Target(AnnotationTarget.FUNCTION)
|
||||
annotation class ApplicationStartedRunner(
|
||||
val order: Int = Int.MIN_VALUE,
|
||||
)
|
||||
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()
|
||||
}
|
||||
}
|
||||
+7
-15
@@ -15,25 +15,17 @@
|
||||
*
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile Listener.kt
|
||||
* LastUpdate 2026-03-10 09:04:02
|
||||
* CurrentFile Sha1Codec.kt
|
||||
* LastUpdate 2026-11-18 11:18:32
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.springboot.annotation
|
||||
|
||||
import org.springframework.core.annotation.AliasFor
|
||||
import org.springframework.stereotype.Component
|
||||
package com.mingliqiye.utils.hash.code
|
||||
|
||||
/**
|
||||
* 监听器组件注解,组合了 [Component] 的语义。
|
||||
* 被标注的类会被组件扫描注册为 Spring Bean,
|
||||
* [value] 通过 [AliasFor] 别名到 [Component.value],用于指定 Bean 名称。
|
||||
* SHA-1 哈希编解码器(输出 160 位 / 20 字节)。
|
||||
*
|
||||
* @property value Bean 名称,默认为空字符串(由 Spring 按类名生成)
|
||||
* SHA-1 已被证实存在碰撞攻击(SHAttered),不得用于安全场景,
|
||||
* 仅建议用于兼容遗留系统或非安全性校验。
|
||||
*/
|
||||
@Component
|
||||
annotation class Listener(
|
||||
@get:AliasFor(annotation = Component::class)
|
||||
val value: String = "",
|
||||
)
|
||||
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
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile DateTimeJsonConverter.kt
|
||||
* LastUpdate 2026-11-17 20:17:32
|
||||
* LastUpdate 2026-11-18 00:03:07
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.json.converters
|
||||
|
||||
import com.google.gson.JsonParseException
|
||||
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.converters.base.AnnotationGetter
|
||||
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
|
||||
@@ -68,12 +68,12 @@ class DateTimeJsonConverter : BaseJsonConverter<DateTime> {
|
||||
/**
|
||||
* 按 [DateTimeJsonFormat] 注解指定的格式从 JSON 字符串解析日期时间
|
||||
*
|
||||
* @throws JsonParseException 当节点不是字符串类型时抛出
|
||||
* @throws JsonParserException 当节点不是字符串类型时抛出
|
||||
*/
|
||||
override fun deConvert(jsonReader: BaseJsonReader, annotationGetter: AnnotationGetter): DateTime? {
|
||||
val dateTimeJsonFormat: DateTimeJsonFormat? = annotationGetter.getAnnotation<DateTimeJsonFormat>()
|
||||
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()
|
||||
return if (Formatter.NONE != dateTimeJsonFormat?.value && dateTimeJsonFormat != null) {
|
||||
DateTime.parse(obj, dateTimeJsonFormat.value, dateTimeJsonFormat.repcZero)
|
||||
|
||||
+4
-4
@@ -16,13 +16,13 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile NetworkEndpointJsonConverter.kt
|
||||
* LastUpdate 2026-11-17 20:01:08
|
||||
* LastUpdate 2026-11-18 00:03:17
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
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.converters.base.AnnotationGetter
|
||||
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
|
||||
@@ -58,14 +58,14 @@ class NetworkEndpointJsonConverter : BaseJsonConverter<NetworkEndpoint> {
|
||||
/**
|
||||
* 从 `host:port` 形式的 JSON 字符串还原网络端点
|
||||
*
|
||||
* @throws JsonParseException 当节点不是字符串类型时抛出
|
||||
* @throws JsonParserException 当节点不是字符串类型时抛出
|
||||
*/
|
||||
override fun deConvert(
|
||||
jsonReader: BaseJsonReader,
|
||||
annotationGetter: AnnotationGetter,
|
||||
): NetworkEndpoint? {
|
||||
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())
|
||||
} else null
|
||||
}
|
||||
|
||||
@@ -16,15 +16,15 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile UUIDJsonConverter.kt
|
||||
* LastUpdate 2026-11-17 20:01:08
|
||||
* LastUpdate 2026-11-18 00:03:17
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.json.converters
|
||||
|
||||
import com.google.gson.JsonParseException
|
||||
import com.mingliqiye.utils.annotation.UUIDJsonFormat
|
||||
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.converters.base.AnnotationGetter
|
||||
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
|
||||
@@ -72,14 +72,14 @@ class UUIDJsonConverter : BaseJsonConverter<UUID> {
|
||||
/**
|
||||
* 按 [UUIDJsonFormat] 注解指定的进制从 JSON 字符串解析 UUID
|
||||
*
|
||||
* @throws JsonParseException 当节点不是字符串类型时抛出
|
||||
* @throws JsonParserException 当节点不是字符串类型时抛出
|
||||
*/
|
||||
override fun deConvert(
|
||||
jsonReader: BaseJsonReader,
|
||||
annotationGetter: AnnotationGetter,
|
||||
): UUID? {
|
||||
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()
|
||||
|
||||
|
||||
+2
-1
@@ -16,7 +16,7 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile Okhttp3AutoConfiguration.kt
|
||||
* LastUpdate 2026-11-16 11:29:35
|
||||
* LastUpdate 2026-11-18 08:22:35
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
@@ -118,6 +118,7 @@ open class Okhttp3AutoConfiguration {
|
||||
* 仅当 [okhttp] 字段非空(即客户端由本配置创建)时执行;
|
||||
* 调用方自行声明的客户端不会被清理。
|
||||
*/
|
||||
|
||||
@EventListener(ContextClosedEvent::class)
|
||||
open fun handleContextClosed() {
|
||||
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
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile SystemUtil.kt
|
||||
* LastUpdate 2026-10-28 22:43:54
|
||||
* LastUpdate 2026-11-23 07:50:35
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
@file:JvmName("SystemUtils")
|
||||
@@ -264,7 +264,7 @@ val isNotJswarMode: Boolean get() = protocol != "jswar"
|
||||
/**
|
||||
* 当前操作系统的行分隔符
|
||||
*/
|
||||
val lineSeparator
|
||||
val lineSeparator: String
|
||||
get() = System.lineSeparator()
|
||||
|
||||
/**
|
||||
|
||||
@@ -16,57 +16,204 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile GlobalThreadPool.kt
|
||||
* LastUpdate 2026-10-19 20:51:35
|
||||
* LastUpdate 2026-11-23 09:48:34
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
package com.mingliqiye.utils.thread
|
||||
|
||||
import com.mingliqiye.utils.netty.NamedThreadFactory
|
||||
import com.mingliqiye.utils.logger.MingLiLoggerFactory
|
||||
import com.mingliqiye.utils.system.availableProcessors
|
||||
import java.util.concurrent.Callable
|
||||
import java.util.concurrent.Future
|
||||
import java.util.concurrent.ScheduledThreadPoolExecutor
|
||||
import java.util.concurrent.ThreadPoolExecutor
|
||||
import com.mingliqiye.utils.thread.GlobalThreadPool.SHUTDOWN_HOOK_TIMEOUT_SECONDS
|
||||
import com.mingliqiye.utils.thread.GlobalThreadPool.cpu
|
||||
import com.mingliqiye.utils.thread.GlobalThreadPool.cpuDispatcher
|
||||
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
|
||||
* GlobalThreadPool.io.execute { download() }
|
||||
* val result = GlobalThreadPool.cpu.submit { compute() }.get()
|
||||
* runAsync { log("done") }
|
||||
* GlobalThreadPool.runAsync { log("done") }
|
||||
* ```
|
||||
*/
|
||||
object GlobalThreadPool {
|
||||
|
||||
/** IO 密集型全局池:线程多、队列有界,适合网络/磁盘等阻塞任务 */
|
||||
val io: ThreadPoolExecutor by lazy {
|
||||
threadPool("MingLiGlobalIO") {
|
||||
corePoolSize = availableProcessors * 2
|
||||
maximumPoolSize = availableProcessors * 4
|
||||
boundedQueue(1024)
|
||||
private val log = MingLiLoggerFactory.getLogger<GlobalThreadPool>()
|
||||
|
||||
init {
|
||||
registerShutdownHook()
|
||||
}
|
||||
|
||||
/** 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
|
||||
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 {
|
||||
threadPool("MingLiGlobalCPU") {
|
||||
corePoolSize = availableProcessors
|
||||
maximumPoolSize = availableProcessors
|
||||
daemon = true
|
||||
log.debug("初始化全局池 [cpu]: core={}, max={}, queue=unbounded, daemon=true", cores, cores)
|
||||
cpuThreadPool("MingLiGlobalCPU", daemon = true, rejectedHandler = globalRejectedHandler)
|
||||
}
|
||||
|
||||
/**
|
||||
* 全局定时池:承载 [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")
|
||||
ScheduledThreadPoolExecutor(
|
||||
(availableProcessors / 2).coerceAtLeast(1),
|
||||
) { runnable -> base.newThread(runnable).apply { isDaemon = true } }
|
||||
// ---- 协程调度器 ----
|
||||
|
||||
/**
|
||||
* 通用协程调度器:[Dispatchers.Default] 的命名视图。
|
||||
*
|
||||
* 它不包装 [main] 线程池,而是直接使用 kotlinx-coroutines 的共享调度器
|
||||
* (每个 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
|
||||
fun <T> submit(runnable: Runnable, result: T): Future<T> = io.submit(runnable, result)
|
||||
|
||||
/**
|
||||
* 优雅关闭全部线程池(先正常关闭,超时后强制关闭)
|
||||
*/
|
||||
@JvmStatic
|
||||
fun shutdownAll() {
|
||||
io.shutdownGracefully()
|
||||
cpu.shutdownGracefully()
|
||||
scheduled.shutdownGracefully()
|
||||
}
|
||||
}
|
||||
// ---- 便捷任务 ----
|
||||
|
||||
/**
|
||||
* 向全局 IO 池提交无返回值任务
|
||||
*
|
||||
* Kotlin 可直接用 lambda,Java 也可直接传 `Runnable`。
|
||||
*
|
||||
* @param block 要执行的任务
|
||||
* @return 任务句柄,可用于等待完成或取消
|
||||
*/
|
||||
fun runAsync(block: () -> Unit): Future<*> = GlobalThreadPool.io.submit(block)
|
||||
@JvmStatic
|
||||
fun runAsync(block: Runnable): Future<*> = io.submit(block)
|
||||
|
||||
/**
|
||||
* 向全局 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 池提交计算任务
|
||||
*
|
||||
* 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 池执行任务并阻塞等待完成
|
||||
*
|
||||
* @param block 要执行的任务
|
||||
*/
|
||||
fun runAsyncAwait(block: () -> Unit) {
|
||||
GlobalThreadPool.io.submit(block).get()
|
||||
@JvmStatic
|
||||
fun runAsyncAwait(block: Runnable) {
|
||||
io.submit(block).get()
|
||||
}
|
||||
|
||||
/**
|
||||
* 在全局 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
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile ThreadExt.kt
|
||||
* LastUpdate 2026-10-19 20:51:35
|
||||
* LastUpdate 2026-11-23 07:50:35
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
@@ -69,7 +69,7 @@ fun Runnable.asThread(
|
||||
* ```
|
||||
*/
|
||||
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
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile ThreadPoolBuilder.kt
|
||||
* LastUpdate 2026-10-19 20:51:35
|
||||
* LastUpdate 2026-11-23 09:31:23
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
@@ -114,21 +114,9 @@ class ThreadPoolBuilder internal constructor() {
|
||||
* @return 配置完成的 [ThreadPoolExecutor]
|
||||
*/
|
||||
fun build(): ThreadPoolExecutor {
|
||||
val baseFactory = threadFactory ?: NamedThreadFactory.of(name)
|
||||
// 提取局部变量,避免 apply 块内与 Thread 自身属性混淆
|
||||
val daemonThread = daemon
|
||||
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
|
||||
val factory = threadFactory
|
||||
?.let { decorateThreadFactory(it, daemon, priority, uncaughtHandler) }
|
||||
?: namedThreadFactory(name, daemon, priority, uncaughtHandler)
|
||||
return ThreadPoolExecutor(
|
||||
corePoolSize,
|
||||
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 方式构建线程池
|
||||
*
|
||||
@@ -195,22 +228,45 @@ fun cachedThreadPool(name: String = "MingLiCachedPool"): ThreadPoolExecutor =
|
||||
|
||||
/**
|
||||
* 创建 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) {
|
||||
corePoolSize = availableProcessors * 2
|
||||
this.corePoolSize = corePoolSize
|
||||
maximumPoolSize = availableProcessors * 4
|
||||
boundedQueue(1024)
|
||||
allowCoreThreadTimeout = true
|
||||
this.daemon = daemon
|
||||
this.rejectedHandler = rejectedHandler
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建 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) {
|
||||
corePoolSize = 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 name 线程池名称
|
||||
* @param daemon 线程是否为守护线程
|
||||
*/
|
||||
@JvmOverloads
|
||||
fun scheduledThreadPool(
|
||||
coreSize: Int = (availableProcessors / 2).coerceAtLeast(1),
|
||||
name: String = "MingLiScheduledPool",
|
||||
daemon: Boolean = false,
|
||||
): ScheduledThreadPoolExecutor =
|
||||
ScheduledThreadPoolExecutor(coreSize, NamedThreadFactory.of(name))
|
||||
ScheduledThreadPoolExecutor(coreSize, namedThreadFactory(name, daemon = daemon))
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
* ProjectName mingli-utils
|
||||
* ModuleName mingli-utils.main
|
||||
* CurrentFile ThreadUtils.kt
|
||||
* LastUpdate 2026-02-09 20:14:22
|
||||
* LastUpdate 2026-11-22 10:03:03
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
@@ -134,4 +134,5 @@ object ThreadUtils {
|
||||
append("\n\n")
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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,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
|
||||
* ModuleName mingli-utils.test
|
||||
* CurrentFile AsyncTasksTest.kt
|
||||
* LastUpdate 2026-10-19 20:58:00
|
||||
* LastUpdate 2026-11-23 09:45:49
|
||||
* UpdateUser MingLiPro
|
||||
*/
|
||||
|
||||
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.assertFalse
|
||||
import org.junit.jupiter.api.Assertions.assertNotEquals
|
||||
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.assertTrue
|
||||
import org.junit.jupiter.api.Test
|
||||
@@ -254,44 +261,99 @@ class AsyncTasksTest {
|
||||
|
||||
// ---- GlobalThreadPool ----
|
||||
|
||||
/** 测试 GlobalThreadPool 的 io/cpu/scheduled 全局线程池已正确初始化 */
|
||||
/** 测试 GlobalThreadPool 的 main/io/cpu/scheduled 全局线程池已正确初始化 */
|
||||
@Test
|
||||
fun testGlobalPools() {
|
||||
assertFalse(GlobalThreadPool.isShutdown)
|
||||
assertTrue(GlobalThreadPool.main.corePoolSize > 0)
|
||||
assertTrue(GlobalThreadPool.io.corePoolSize > 0)
|
||||
assertTrue(GlobalThreadPool.cpu.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 异步执行无返回值任务 */
|
||||
@Test
|
||||
fun testRunAsync() {
|
||||
assertNull(runAsync { }.get(5, TimeUnit.SECONDS))
|
||||
assertNull(GlobalThreadPool.runAsync { }.get(5, TimeUnit.SECONDS))
|
||||
}
|
||||
|
||||
/** 测试 callAsync 在 IO 线程池异步执行并返回结果 */
|
||||
@Test
|
||||
fun testCallAsync() {
|
||||
assertEquals("io", callAsync { "io" }.get(5, TimeUnit.SECONDS))
|
||||
assertEquals("io", GlobalThreadPool.callAsync { "io" }.get(5, TimeUnit.SECONDS))
|
||||
}
|
||||
|
||||
/** 测试 computeAsync 在 CPU 线程池异步计算并返回结果 */
|
||||
@Test
|
||||
fun testComputeAsync() {
|
||||
assertEquals(4, computeAsync { 2 + 2 }.get(5, TimeUnit.SECONDS))
|
||||
assertEquals(4, GlobalThreadPool.computeAsync { 2 + 2 }.get(5, TimeUnit.SECONDS))
|
||||
}
|
||||
|
||||
/** 测试 runAsyncAwait 异步执行并阻塞等待完成 */
|
||||
@Test
|
||||
fun testRunAsyncAwait() {
|
||||
val counter = AtomicInteger()
|
||||
runAsyncAwait { counter.incrementAndGet() }
|
||||
GlobalThreadPool.runAsyncAwait { counter.incrementAndGet() }
|
||||
assertEquals(1, counter.get())
|
||||
}
|
||||
|
||||
/** 测试 callAsyncAwait 异步执行并阻塞等待返回结果 */
|
||||
@Test
|
||||
fun testCallAsyncAwait() {
|
||||
assertEquals("await", callAsyncAwait { "await" })
|
||||
assertEquals("await", GlobalThreadPool.callAsyncAwait { "await" })
|
||||
}
|
||||
|
||||
/** 测试 GlobalThreadPool.execute 提交任务并被执行 */
|
||||
|
||||
@@ -21,7 +21,9 @@
|
||||
~ UpdateUser MingLiPro
|
||||
-->
|
||||
|
||||
<Configuration status="WARN">
|
||||
<Configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="log4j2.xsd"
|
||||
status="WARN">
|
||||
<Appenders>
|
||||
<Console name="CONSOLE" target="SYSTEM_OUT">
|
||||
<PatternLayout
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user