Compare commits

..
3 Commits
Author SHA1 Message Date
minglipro 53e30351a7 v5.7.2
Gitea Actions Build / Build (push) Waiting to run
- spring: 新增 @FastServiceScan 扫描注解与 FastServiceScanRegistrar / FastServiceScannerProcessor,支持扫描 FastBaseIService 和 FastBaseIServiceNew3518 两个基类、value/basePackages 别名、缺失基类跳过

- spring: ApplicationDestroyedRunner / ApplicationReadyEventListener / ApplicationStartedRunner / ContextClosedEventListener 迁移为 Kotlin,弃用注解补全 @Deprecated + ReplaceWith

- build: 新增 VERSIONSTYPE 控制 RELEASES/SNAPSHOT 版本后缀,补充 Spring / MyBatis-Plus 测试依赖

- test: 新增 FastServiceScanRegistrarTest 5 个用例与 FastServiceScannerProcessorTest 2 个用例
2026-11-23 15:23:07 +08:00
minglipro d43f273aa7 v5.7.0
Gitea Actions Build / Build (push) Waiting to run
- lock: 新增 RedisLock 分布式锁工具(Redisson 异步 API、协程挂起等待、看门狗续期、公平锁、tryWithLock)与 RedisLockTimeoutException

- build: 改用 providers.gradleProperty / 显式模板变量,消除 Gradle 9 配置期弃用警告;.gitignore 的 *lock* 改为 *.lock

- test: 新增 RedisLockTest 7 个用例
2026-11-23 10:44:29 +08:00
minglipro 838a03560e docs(changelog): 补充 5.6.0 变更记录
Gitea Actions Build / Build (push) Waiting to run
2026-11-23 09:59:34 +08:00
21 changed files with 1490 additions and 368 deletions
+1 -1
View File
@@ -43,6 +43,6 @@ bin/
log
.idea
node_modules
*lock*
*.lock
.kotlin
secret.gpg
+98
View File
@@ -4,6 +4,104 @@
本文件记录 mingli-utils 各版本的主要变更。
## [5.7.2] - 2026-11-23
### 新增
- **spring**:新增 `@FastServiceScan` 注解及 `FastServiceScanRegistrar`、
`FastServiceScannerProcessor`——扫描继承 `FastBaseIService` 或 `FastBaseIServiceNew3518`
的具体类并注册为 Spring Bean;仅在启动类/配置类标注该注解时生效,扫描时机在所有
`BeanDefinitionRegistryPostProcessor`(包括 `@MapperScan` 的 `MapperScannerConfigurer`)之后。
支持 `value` / `basePackages` / `basePackageClasses`,`value` 与 `basePackages` 通过
`@AliasFor` 互为别名;未指定包时使用标注类所在包;已标注 `@Component` / `@Service`
的类自动跳过,避免重复注册。
- **test**:新增 `FastServiceScanRegistrarTest`(5 个用例)与
`FastServiceScannerProcessorTest`(2 个用例,覆盖两个基类与某个基类缺失时的跳过逻辑)。
### 变更
- **spring**:`ApplicationDestroyedRunner`、`ApplicationReadyEventListener`、
`ApplicationStartedRunner`、`ContextClosedEventListener` 由 Java 迁移为 Kotlin 实现,
包名、属性及 `@AliasFor` 关系保持不变。
- **spring**:`ApplicationDestroyedRunner` / `ApplicationStartedRunner` 补全
`@Deprecated` + `ReplaceWith`,IDE 可一键替换为 `ContextClosedEventListener` /
`ApplicationReadyEventListener`;旧 Java 版本只有 `@Deprecated(since = ...)`。
- **build**:新增 `VERSIONSTYPE`(`r` = RELEASES,`s` = SNAPSHOT)控制版本后缀;
补充 Spring / MyBatis-Plus 测试依赖。
### 修复
- **spring**:`FastServiceScannerProcessor` 改为按类名探测两个服务基类,
仅引入一套 MyBatis-Plus 时只跳过缺失的基类,不再因类字面量加载父类失败抛出
`NoClassDefFoundError`。
### 注意
- 事件监听注解的 `defaultExecution` 属性仅在 Spring Framework 6.2+ 中提供;
在 Spring 5.3 下解析这些组合注解会抛出 `AnnotationConfigurationException`,使用方需按实际
Spring 版本选择。
## [5.7.0] - 2026-11-23
### 新增
- **lock**:新增 `RedisLock` Redis 分布式锁工具——基于 Redisson 异步 API 实现协程挂起式加锁,
等待期间不占用线程;默认启用看门狗自动续期,支持公平锁、自定义 key 前缀与固定租期;
提供 `withLock`(等待获取)与 `tryWithLock`(抢不到立即返回 `null`);
新增 `RedisLockTimeoutException`。Redisson 为可选依赖(`compileOnly`),
使用方需自行引入(建议 Redisson 3.13+ / 4.x)。
### 变更
- **build**:`build.gradle.kts` 与 `settings.gradle.kts` 移除已废弃的 `project.properties`、
`settings.extra` 委托写法,改用 `providers.gradleProperty` 与显式访问器;
`processResources` 的模板展开改为显式变量表,消除 Gradle 9 的配置期弃用警告。
- **build**:`.gitignore` 的 `*lock*` 规则改为 `*.lock`,避免把新增的 `lock` 包整体忽略。
### 测试
- 新增 `RedisLockTest`(7 个用例),通过动态代理模拟 Redisson 客户端,
覆盖正常加锁释放、等待超时、跳过执行、公平锁、业务异常仍释放、wait/lease 透传。
## [5.6.0] - 2026-11-23
### 新增
- **thread**:新增 `SuspendUtils` 协程工具——`CoroutineContext.withContext`、
`CoroutineContext.runBlocking`(按接收者上下文执行)与顶层 `runBlocking`
(使用调用线程的事件循环)、`asCompletableDeferred`。
- **thread**:`GlobalThreadPool` 新增 `mainDispatcher` / `ioDispatcher` / `cpuDispatcher`、
`pools()`、`snapshotAll()`、`isShutdown`,并自动注册 JVM 关闭钩子——
进程正常退出时优雅关闭全部池(最多等待 5 秒,超时强制关闭)。
- **thread**:`runAsync` / `callAsync` / `computeAsync` / `runAsyncAwait` / `callAsyncAwait`
移入 `GlobalThreadPool` 并加 `@JvmStatic`;参数改为 `Runnable` / `Callable`,
Kotlin 与 Java 均可直接使用 lambda。
- **thread**:新增 `namedThreadFactory`;`ioThreadPool` / `cpuThreadPool` /
`scheduledThreadPool` 增加 `daemon` 与 `rejectedHandler` 参数。
- **collection**:新增 `newArrayDeque()` 的三个重载。
### 变更
- **thread**:重构 `GlobalThreadPool`——main / io / cpu / scheduled 统一守护线程与池配置;
`shutdownAll` 覆盖全部池、改用统一截止时间、幂等、超时 `shutdownNow` 并返回是否正常终止;
全局池关闭后提交任务抛出 `RejectedExecutionException`;scheduled 开启 `removeOnCancelPolicy`、
关闭时丢弃未到期延迟任务;补充池与调度器初始化、拒绝策略、关闭流程及关闭钩子的 Debug 日志。
- **thread**:`mainDispatcher` / `ioDispatcher` 复用 kotlinx-coroutines 共享调度器
(命名限流视图),`cpuDispatcher` 绑定独立 cpu 池;`ThreadPoolBuilder` 抽出
`namedThreadFactory` 供各线程池复用。
- **stream**:`SuperStream.toArray` 返回类型补充 jspecify `@NonNull`;
`Collection.toArray` 泛型收紧为 `T : Any`。
- 移除 `ForEach`;更新依赖与版权年份。
### 修复
- **thread**:`CoroutineContext.runBlocking` 未使用接收者上下文,行为与普通 `runBlocking` 相同。
- **thread**:全局池关闭后任务被静默丢弃、`submit` 返回永不完成 `Future` 的问题。
### 测试
- 新增 `SuspendUtilsTest`;补充 `AsyncTasksTest` 中全局池、调度器与关闭钩子相关用例。
## [5.5.4] - 2026-11-18
### 新增
+21 -8
View File
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils
* CurrentFile build.gradle.kts
* LastUpdate 2026-11-22 07:59:57
* LastUpdate 2026-11-23 15:17:59
* UpdateUser MingLiPro
*/
@@ -59,11 +59,13 @@ plugins {
id("org.jetbrains.dokka-javadoc") version "2.1.0"
kotlin("plugin.spring") version "2.1.0"
}
val GROUPSID = project.properties["GROUPSID"] as String
val VERSIONS = project.properties["VERSIONS"] as String
val ARTIFACTID = project.properties["ARTIFACTID"] as String
val JDKVERSIONS = (project.properties["JDKVERSIONS"] as String).toInt()
val GROUPSID = providers.gradleProperty("GROUPSID").get()
val VERSION = providers.gradleProperty("VERSIONS").get()
val ARTIFACTID = providers.gradleProperty("ARTIFACTID").get()
val JDKVERSIONS = providers.gradleProperty("JDKVERSIONS").get().toInt()
val VERSIONSTYPE = providers.gradleProperty("VERSIONSTYPE").get()
val VERSIONS =
VERSION + if (VERSIONSTYPE == "s") "-SNAPSHOT" else if (VERSIONSTYPE == "r") "" else error("VERSIONSTYPE is not supported in gradle.properties $VERSIONSTYPE")
group = GROUPSID
version = VERSIONS
@@ -113,9 +115,16 @@ dependencies {
compileOnly("com.baomidou:mybatis-plus-spring:3.5.9")
compileOnly("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2")
compileOnly("org.jetbrains.kotlinx:kotlinx-coroutines-reactor:1.10.2")
compileOnly("org.redisson:redisson:4.8.0")
testImplementation("org.junit.jupiter:junit-jupiter:5.7.1")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2")
testImplementation(fileTree("libs"))
testImplementation("com.baomidou:mybatis-plus-core:3.5.15")
testImplementation("com.baomidou:mybatis-plus-extension:3.5.15")
testImplementation("com.baomidou:mybatis-plus-spring:3.5.9")
testImplementation("org.springframework:spring-context:5.3.39")
testImplementation("org.redisson:redisson:4.8.0")
testImplementation("com.mingliqiye.logger:logger-log4j2:1.0.9")
testImplementation("com.google.code.gson:gson:2.13.2")
@@ -255,12 +264,16 @@ tasks.processResources {
outputs.upToDateWhen { false }
filesMatching(listOf("META-INF/meta-data", "fabric.mod.json")) {
expand(
project.properties + mapOf(
mapOf(
"GROUPSID" to GROUPSID,
"ARTIFACTID" to ARTIFACTID,
"VERSIONS" to VERSIONS,
"JDKVERSIONS" to JDKVERSIONS,
"buildTime" to LocalDateTime.now().format(
DateTimeFormatter.ofPattern(
"yyyy-MM-dd HH:mm:ss.SSSSSSS"
)
)
),
)
)
}
+5 -2
View File
@@ -16,10 +16,13 @@
# ProjectName mingli-utils
# ModuleName mingli-utils
# CurrentFile gradle.properties
# LastUpdate 2026-11-23 09:56:18
# LastUpdate 2026-11-23 15:24:00
# UpdateUser MingLiPro
#
JDKVERSIONS=17
GROUPSID=com.mingliqiye.utils
ARTIFACTID=mingli-utils
VERSIONS=5.6.0
# r = RELEASES
# s = SNAPSHOT
VERSIONSTYPE=r
VERSIONS=5.7.2
+2 -2
View File
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils
* CurrentFile settings.gradle.kts
* LastUpdate 2026-02-26 10:52:01
* LastUpdate 2026-11-23 10:23:56
* UpdateUser MingLiPro
*/
@@ -24,7 +24,7 @@ plugins {
id("com.gradleup.nmcp.settings").version("1.4.4")
}
val ARTIFACTID: String by settings.extra
val ARTIFACTID = settings.extra["ARTIFACTID"] as String
rootProject.name = ARTIFACTID
nmcpSettings {
@@ -1,83 +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 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;
}
@@ -1,95 +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 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;
}
@@ -1,84 +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 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;
}
@@ -1,93 +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 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;
}
@@ -0,0 +1,94 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile FastServiceScan.java
* LastUpdate 2026-11-23 14:44:48
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.annotation;
import com.mingliqiye.utils.springboot.autoconfigure.FastServiceScanRegistrar;
import org.springframework.context.annotation.Import;
import org.springframework.core.annotation.AliasFor;
import java.lang.annotation.*;
/**
* 扫描继承自 {@code com.mingliqiye.utils.mybatisplus.FastBaseIService} 或
* {@code com.mingliqiye.utils.mybatisplus.FastBaseIServiceNew3518} 的具体类并注册为 Spring Bean。
* 两个基类分别对应旧版 {@code mybatis-plus-extension} 与新版 {@code mybatis-plus-spring},
* 子类都会被扫描到;行为与 {@code @MapperScan} 类似:只有标注了本注解的启动类/配置类才会触发扫描。
*
* <p>扫描由 {@link FastServiceScanRegistrar} 注册的
* {@code com.mingliqiye.utils.springboot.autoconfigure.FastServiceScannerProcessor} 完成,
* 后者是 {@code BeanFactoryPostProcessor},会在所有 {@code BeanDefinitionRegistryPostProcessor}
* (包括 {@code @MapperScan} 的 {@code MapperScannerConfigurer})之后执行,
* 因此扫描注册时机在 mapper 之后,服务里的 {@code baseMapper} 可以正常注入。</p>
*
* <p>已经标注 {@code @Component} / {@code @Service} 的类会被跳过,交给普通组件扫描处理,避免重复注册。</p>
*
* <p>Java 用法:</p>
* <pre>{@code
* @SpringBootApplication
* @MapperScan(basePackages = "com.example.mapper")
* @FastServiceScan(basePackages = "com.example.service")
* public class ExampleApplication {
* }
* }</pre>
*
* <p>Kotlin 用法:</p>
* <pre>{@code
* @SpringBootApplication
* @MapperScan(basePackages = ["com.example.mapper"])
* @FastServiceScan(basePackages = ["com.example.service"])
* class ExampleApplication
* }</pre>
*
* <p>不指定扫描包时,默认扫描标注类所在包。</p>
* <p>{@code Kotlin} 请指定 {@code Service} 为 {@code open}</p>
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(FastServiceScanRegistrar.class)
public @interface FastServiceScan {
/**
* 要扫描的包,等价于 {@link #basePackages()}。
*
* @return 要扫描的包
*/
@AliasFor("basePackages")
String[] value() default {};
/**
* 要扫描的包。
*
* @return 要扫描的包
*/
@AliasFor("value")
String[] basePackages() default {};
/**
* 以这些类所在包作为扫描包。
*
* @return 用于推导扫描包的类
*/
Class<?>[] basePackageClasses() default {};
}
@@ -0,0 +1,34 @@
/*
* 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 RedisLockTimeoutException.kt
* LastUpdate 2026-11-23 10:21:41
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.exception
/**
* Redis 分布式锁等待超时异常。
*
* @param lockKey 未获取到的完整锁 key(含前缀)
* @param waitMillis 等待时长(毫秒)
*/
class RedisLockTimeoutException(
val lockKey: String,
val waitMillis: Long,
) : MingLiUtilsBaseException("获取 Redis 分布式锁超时: $lockKey,等待 ${waitMillis}ms")
@@ -0,0 +1,226 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile RedisLock.kt
* LastUpdate 2026-11-23 10:26:28
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.lock
import com.mingliqiye.utils.exception.RedisLockTimeoutException
import com.mingliqiye.utils.logger.MingLiLoggerFactory
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.future.await
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import org.redisson.api.RLock
import org.redisson.api.RedissonClient
import java.util.concurrent.CompletionStage
import java.util.concurrent.ThreadLocalRandom
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicLong
import kotlin.time.Duration.Companion.milliseconds
/**
* 基于 Redisson 的 Redis 分布式锁工具,提供「协程挂起等待」的加锁 API。
*
* 与 `RLock.lock()` 的线程阻塞不同,加锁/解锁都走 Redisson 异步 API,
* 等待期间只挂起协程、不占用业务线程,适合十秒级左右的操作:
*
* ```kotlin
* val lock = RedisLock(redisson)
* lock.withLock("settle:2026-11") {
* // 同一时刻只有一个节点会执行到这里
* doSettle()
* }
* ```
*
* 特性:
* - 默认启用 Redisson 看门狗(`leaseMillis = -1`),业务执行超时也会自动续期
* - 支持公平锁、自定义 key 前缀、固定租期
* - `tryWithLock` 抢不到锁立即返回 `null`,不等待
*
* 使用前提:调用方需自行引入 Redisson(本库对 Redisson 仅有 `compileOnly` 依赖),
* 建议 Redisson 3.13+ / 4.x。
*
* 注意:
* - **不可重入**:每次加锁都会分配独立的 owner id,同一协程嵌套调用同一个 key 会等待超时
* - Redis 锁可能因主从切换、网络分区而丢失,业务仍需幂等/唯一约束兜底
* - [leaseMillis] 为正数时为固定租期、不会自动续期,[withLock] 的业务必须在该时间内完成
* - 等待超时会抛出 [RedisLockTimeoutException]
*
* @param redisson Redisson 客户端
* @param keyPrefix 锁 key 前缀,默认 `mingli:lock:`
* @param fair 是否使用公平锁(`getFairLock`),默认非公平
* @param defaultWaitMillis 默认最长等待时间(毫秒),默认 15 秒
* @param leaseMillis 租约时间:默认 `-1` 使用看门狗自动续期;正数为固定租期
*/
class RedisLock @JvmOverloads constructor(
private val redisson: RedissonClient,
private val keyPrefix: String = DEFAULT_KEY_PREFIX,
private val fair: Boolean = false,
private val defaultWaitMillis: Long = DEFAULT_WAIT_MILLIS,
private val leaseMillis: Long = WATCHDOG_LEASE,
) {
private val log = MingLiLoggerFactory.getLogger<RedisLock>()
init {
require(defaultWaitMillis >= 0) { "defaultWaitMillis 不能为负数: $defaultWaitMillis" }
require(leaseMillis == WATCHDOG_LEASE || leaseMillis > 0) {
"leaseMillis 必须是 -1(看门狗自动续期)或正数: $leaseMillis"
}
}
/**
* 获取锁并在持有期间执行 [block],锁被占用时挂起等待,最长等待 [waitMillis]。
*
* 正常返回或 [block] 抛异常都会释放锁;等待期间协程被取消也会尽力释放。
*
* @param key 业务锁 key,实际 Redis key 为 `keyPrefix + key`
* @param waitMillis 最长等待时间(毫秒),默认取构造参数
* @param block 持锁执行的业务逻辑
* @return [block] 的返回值
* @throws RedisLockTimeoutException 等待超过 [waitMillis] 仍未获取到锁
*/
suspend fun <T> withLock(
key: String,
waitMillis: Long = defaultWaitMillis,
block: suspend () -> T,
): T {
require(key.isNotBlank()) { "锁 key 不能为空" }
require(waitMillis >= 0) { "waitMillis 不能为负数: $waitMillis" }
val lock = lockOf(key)
val ownerId = nextOwnerId()
var acquired = false
var cancelled = false
try {
acquired = awaitAcquire(lock, waitMillis, ownerId)
if (!acquired) {
log.debug("获取 Redis 分布式锁超时: key={}, wait={}ms", lock.name, waitMillis)
throw RedisLockTimeoutException(lock.name, waitMillis)
}
log.debug("已获取 Redis 分布式锁: key={}, owner={}", lock.name, ownerId)
return block()
} catch (e: CancellationException) {
cancelled = true
throw e
} finally {
// 等待中被取消时,锁可能刚好已经拿到,这里统一尝试释放
if (acquired || cancelled) {
release(lock, ownerId)
}
}
}
/**
* 尝试获取锁:抢不到立即返回 `null`,不等待;抢到则执行 [block] 并返回其结果。
*
* 注意:如果 [block] 允许返回 `null`,调用方无法区分「锁被占用」和「业务返回 null」。
*
* @param key 业务锁 key,实际 Redis key 为 `keyPrefix + key`
* @param block 持锁执行的业务逻辑
* @return [block] 的返回值;锁被占用时返回 `null`
*/
suspend fun <T> tryWithLock(
key: String,
block: suspend () -> T,
): T? {
require(key.isNotBlank()) { "锁 key 不能为空" }
val lock = lockOf(key)
val ownerId = nextOwnerId()
var acquired = false
var cancelled = false
try {
acquired = awaitAcquire(lock, 0, ownerId)
if (!acquired) {
log.debug("Redis 分布式锁被占用,跳过执行: key={}", lock.name)
return null
}
log.debug("已获取 Redis 分布式锁: key={}, owner={}", lock.name, ownerId)
return block()
} catch (e: CancellationException) {
cancelled = true
throw e
} finally {
if (acquired || cancelled) {
release(lock, ownerId)
}
}
}
/**
* 计算某个业务 key 对应的完整 Redis 锁 key(`keyPrefix + key`)。
*/
fun lockName(key: String): String = keyPrefix + key
private suspend fun awaitAcquire(lock: RLock, waitMillis: Long, ownerId: Long): Boolean {
val future = lock.tryLockAsync(waitMillis, leaseMillis, TimeUnit.MILLISECONDS, ownerId)
// RFuture 同时实现了 Future 和 CompletionStage,显式转成 CompletionStage 以匹配 await 扩展
return (future as CompletionStage<Boolean>).await()
}
private suspend fun release(lock: RLock, ownerId: Long) {
withContext(NonCancellable) {
try {
val released = withTimeoutOrNull(RELEASE_TIMEOUT_MILLIS.milliseconds) {
(lock.unlockAsync(ownerId) as CompletionStage<Void>).await()
true
}
if (released == true) {
log.debug("已释放 Redis 分布式锁: key={}, owner={}", lock.name, ownerId)
} else {
log.warn("释放 Redis 分布式锁超时: key={}, owner={}", lock.name, ownerId)
}
} catch (t: Throwable) {
// 锁可能已因租约到期/主从切换丢失,unlock 会抛 IllegalMonitorStateException
log.debug("释放 Redis 分布式锁失败: key={}, owner={}", lock.name, ownerId, t)
}
}
}
private fun lockOf(key: String): RLock =
if (fair) redisson.getFairLock(keyPrefix + key) else redisson.getLock(keyPrefix + key)
companion object {
/** 默认锁 key 前缀 */
const val DEFAULT_KEY_PREFIX: String = "mingli:lock:"
/** 默认等待时间:15 秒 */
const val DEFAULT_WAIT_MILLIS: Long = 15_000L
/** 使用 Redisson 看门狗自动续期租约 */
const val WATCHDOG_LEASE: Long = -1L
/** 释放锁的等待上限,避免 Redis 故障时卡住调用方 */
private const val RELEASE_TIMEOUT_MILLIS: Long = 2_000L
/**
* owner id 生成器。
*
* Redisson 用 `clientUuid:threadId` 区分持有者;这里不绑定真实线程,
* 而是给每次加锁生成一个唯一的 id,从而支持跨线程的协程解锁。
* 随机起始值是为了避开真实线程 id,避免和同一客户端里其它锁语义冲突。
*/
private val OWNER_IDS = AtomicLong(ThreadLocalRandom.current().nextLong())
private fun nextOwnerId(): Long = OWNER_IDS.incrementAndGet()
}
}
@@ -0,0 +1,87 @@
/*
* 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.kt
* LastUpdate 2026-11-23 15:07:06
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.annotation
import org.springframework.context.event.ContextClosedEvent
import org.springframework.context.event.EventListener
import org.springframework.core.Ordered
import org.springframework.core.annotation.AliasFor
import org.springframework.core.annotation.Order
/**
* 应用销毁(上下文关闭)事件监听注解。
*
* 标注在 Spring Bean 的方法上,当 Spring 应用上下文关闭
* ([ContextClosedEvent] 发布)时自动调用该方法。
*
* 已弃用,请改用 [ContextClosedEventListener](监听相同事件,命名更规范)。
*
* @see ContextClosedEventListener
* @see EventListener
* @see ContextClosedEvent
*/
@Deprecated(
message = "已弃用,请改用 ContextClosedEventListener(监听相同事件,命名更规范)",
replaceWith = ReplaceWith(
expression = "ContextClosedEventListener",
imports = ["com.mingliqiye.utils.springboot.annotation.ContextClosedEventListener"],
),
)
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.ANNOTATION_CLASS)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
@EventListener(ContextClosedEvent::class)
@Order
annotation class ApplicationDestroyedRunner(
/**
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
*
* 默认为空字符串,表示无条件执行。
*/
@get:AliasFor(annotation = EventListener::class, attribute = "condition")
val condition: String = "",
/**
* 当事件不是 [ContextClosedEvent] 类型时是否仍默认执行监听方法。
*
* 默认为 `true`。
*/
@get:AliasFor(annotation = EventListener::class, attribute = "defaultExecution")
val defaultExecution: Boolean = true,
/**
* 监听器的唯一标识,用于注册可指定 id 的监听器。
*
* 默认为空字符串,表示自动生成。
*/
@get:AliasFor(annotation = EventListener::class, attribute = "id")
val id: String = "",
/**
* 监听器的执行顺序,值越小优先级越高。
*
* 默认为 [Ordered.LOWEST_PRECEDENCE]。
*/
@get:AliasFor(annotation = Order::class, attribute = "value")
val order: Int = Ordered.LOWEST_PRECEDENCE,
)
@@ -0,0 +1,88 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ApplicationReadyEventListener.kt
* LastUpdate 2026-11-23 15:07:06
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.annotation
import org.springframework.boot.context.event.ApplicationReadyEvent
import org.springframework.context.event.EventListener
import org.springframework.core.Ordered
import org.springframework.core.annotation.AliasFor
import org.springframework.core.annotation.Order
/**
* 应用就绪事件监听注解。
*
* 标注在 Spring Bean 的方法上,当 Spring Boot 应用完成启动并就绪
* ([ApplicationReadyEvent] 发布)时自动调用该方法,
* 等价于 `@EventListener(ApplicationReadyEvent::class)` 的组合简化写法。
*
* ```kotlin
* @Component
* class InitTask {
* @ApplicationReadyEventListener(order = 0)
* fun onReady() {
* // 应用就绪后执行的初始化逻辑
* }
* }
* ```
*
* @see EventListener
* @see ApplicationReadyEvent
*/
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.ANNOTATION_CLASS)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
@EventListener(ApplicationReadyEvent::class)
@Order
annotation class ApplicationReadyEventListener(
/**
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
*
* 默认为空字符串,表示无条件执行。
*/
@get:AliasFor(annotation = EventListener::class, attribute = "condition")
val condition: String = "",
/**
* 当事件不是 [ApplicationReadyEvent] 类型时是否仍默认执行监听方法。
*
* 默认为 `true`。
*/
@get:AliasFor(annotation = EventListener::class, attribute = "defaultExecution")
val defaultExecution: Boolean = true,
/**
* 监听器的唯一标识,用于注册可指定 id 的监听器。
*
* 默认为空字符串,表示自动生成。
*/
@get:AliasFor(annotation = EventListener::class, attribute = "id")
val id: String = "",
/**
* 监听器的执行顺序,值越小优先级越高。
*
* 默认为 [Ordered.LOWEST_PRECEDENCE]。
*/
@get:AliasFor(annotation = Order::class, attribute = "value")
val order: Int = Ordered.LOWEST_PRECEDENCE,
)
@@ -0,0 +1,87 @@
/*
* 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.kt
* LastUpdate 2026-11-23 15:07:06
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.annotation
import org.springframework.boot.context.event.ApplicationReadyEvent
import org.springframework.context.event.EventListener
import org.springframework.core.Ordered
import org.springframework.core.annotation.AliasFor
import org.springframework.core.annotation.Order
/**
* 应用启动完成事件监听注解。
*
* 标注在 Spring Bean 的方法上,当 Spring Boot 应用完成启动并就绪
* ([ApplicationReadyEvent] 发布)时自动调用该方法。
*
* 已弃用,请改用 [ApplicationReadyEventListener](功能完全一致,命名更规范)。
*
* @see ApplicationReadyEventListener
* @see EventListener
* @see ApplicationReadyEvent
*/
@Deprecated(
message = "已弃用,请改用 ApplicationReadyEventListener(功能完全一致,命名更规范)",
replaceWith = ReplaceWith(
expression = "ApplicationReadyEventListener",
imports = ["com.mingliqiye.utils.springboot.annotation.ApplicationReadyEventListener"],
),
)
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.ANNOTATION_CLASS)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
@EventListener(ApplicationReadyEvent::class)
@Order
annotation class ApplicationStartedRunner(
/**
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
*
* 默认为空字符串,表示无条件执行。
*/
@get:AliasFor(annotation = EventListener::class, attribute = "condition")
val condition: String = "",
/**
* 当事件不是 [ApplicationReadyEvent] 类型时是否仍默认执行监听方法。
*
* 默认为 `true`。
*/
@get:AliasFor(annotation = EventListener::class, attribute = "defaultExecution")
val defaultExecution: Boolean = true,
/**
* 监听器的唯一标识,用于注册可指定 id 的监听器。
*
* 默认为空字符串,表示自动生成。
*/
@get:AliasFor(annotation = EventListener::class, attribute = "id")
val id: String = "",
/**
* 监听器的执行顺序,值越小优先级越高。
*
* 默认为 [Ordered.LOWEST_PRECEDENCE]。
*/
@get:AliasFor(annotation = Order::class, attribute = "value")
val order: Int = Ordered.LOWEST_PRECEDENCE,
)
@@ -0,0 +1,89 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ContextClosedEventListener.kt
* LastUpdate 2026-11-23 15:07:06
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.annotation
import org.springframework.context.event.ContextClosedEvent
import org.springframework.context.event.EventListener
import org.springframework.core.Ordered
import org.springframework.core.annotation.AliasFor
import org.springframework.core.annotation.Order
/**
* 应用上下文关闭事件监听注解。
*
* 标注在 Spring Bean 的方法上,当 Spring 应用上下文关闭
* ([ContextClosedEvent] 发布)时自动调用该方法,
* 等价于 `@EventListener(ContextClosedEvent::class)` 的组合简化写法,
* 适用于应用停机前的资源清理、状态保存等场景。
*
* ```kotlin
* @Component
* class CleanupTask {
* @ContextClosedEventListener
* fun onClosed() {
* // 上下文关闭前执行的清理逻辑
* }
* }
* ```
*
* @see EventListener
* @see ContextClosedEvent
*/
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.ANNOTATION_CLASS)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
@EventListener(ContextClosedEvent::class)
@Order
annotation class ContextClosedEventListener(
/**
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
*
* 默认为空字符串,表示无条件执行。
*/
@get:AliasFor(annotation = EventListener::class, attribute = "condition")
val condition: String = "",
/**
* 当事件不是 [ContextClosedEvent] 类型时是否仍默认执行监听方法。
*
* 默认为 `true`。
*/
@get:AliasFor(annotation = EventListener::class, attribute = "defaultExecution")
val defaultExecution: Boolean = true,
/**
* 监听器的唯一标识,用于注册可指定 id 的监听器。
*
* 默认为空字符串,表示自动生成。
*/
@get:AliasFor(annotation = EventListener::class, attribute = "id")
val id: String = "",
/**
* 监听器的执行顺序,值越小优先级越高。
*
* 默认为 [Ordered.LOWEST_PRECEDENCE]。
*/
@get:AliasFor(annotation = Order::class, attribute = "value")
val order: Int = Ordered.LOWEST_PRECEDENCE,
)
@@ -0,0 +1,94 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile FastServiceScanRegistrar.kt
* LastUpdate 2026-11-23 14:21:18
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.autoconfigure
import com.mingliqiye.utils.springboot.annotation.FastServiceScan
import org.springframework.beans.factory.config.BeanDefinition
import org.springframework.beans.factory.support.BeanDefinitionRegistry
import org.springframework.beans.factory.support.RootBeanDefinition
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar
import org.springframework.core.type.AnnotationMetadata
import org.springframework.util.ClassUtils
/**
* [FastServiceScan] 的注册器:解析注解上的扫描包,并把 [FastServiceScannerProcessor] 注册成 Bean。
*
* 通过 Spring 的 `MergedAnnotation.synthesize()` 读取注解,这样 `value` 与 `basePackages`
* 之间的 `@AliasFor` 会像 `@MapperScan` 一样被正确合并(两者同时指定不同值时也会按 Spring
* 的规则报错,而不是被静默合并)。
*
* 这里不直接扫描,而是注册一个 `BeanFactoryPostProcessor`,由 Spring 在所有
* `BeanDefinitionRegistryPostProcessor`(如 `@MapperScan` 的 `MapperScannerConfigurer`)之后执行,
* 从而保证扫描注册时机在 mapper 之后。
*/
class FastServiceScanRegistrar : ImportBeanDefinitionRegistrar {
override fun registerBeanDefinitions(
importingClassMetadata: AnnotationMetadata,
registry: BeanDefinitionRegistry,
) {
val mergedAnnotation = importingClassMetadata.annotations.get(FastServiceScan::class.java)
if (!mergedAnnotation.isPresent) return
// synthesize 会应用 @AliasFor,value/basePackages 指向同一个值
val annotation = mergedAnnotation.synthesize()
val packages = resolvePackages(annotation, importingClassMetadata)
if (packages.isEmpty()) return
if (registry.containsBeanDefinition(PROCESSOR_BEAN_NAME)) return
val definition = RootBeanDefinition(FastServiceScannerProcessor::class.java)
definition.constructorArgumentValues.addIndexedArgumentValue(0, packages.toTypedArray())
definition.role = BeanDefinition.ROLE_INFRASTRUCTURE
registry.registerBeanDefinition(PROCESSOR_BEAN_NAME, definition)
}
/**
* 解析注解上的扫描包;未指定时取标注类所在包。
*/
private fun resolvePackages(
annotation: FastServiceScan,
importingClassMetadata: AnnotationMetadata,
): Set<String> {
val packages = LinkedHashSet<String>()
// value 与 basePackages 互为 @AliasFor,这里各读一遍只是防御;重复值会被 Set 去重
for (packageName in annotation.value) {
if (packageName.isNotBlank()) packages += packageName.trim()
}
for (packageName in annotation.basePackages) {
if (packageName.isNotBlank()) packages += packageName.trim()
}
for (baseClass in annotation.basePackageClasses) {
packages += ClassUtils.getPackageName(baseClass.java)
}
if (packages.isEmpty()) {
packages += ClassUtils.getPackageName(importingClassMetadata.className)
}
return packages
}
companion object {
private const val PROCESSOR_BEAN_NAME = "fastServiceScannerProcessor"
}
}
@@ -0,0 +1,137 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile FastServiceScannerProcessor.kt
* LastUpdate 2026-11-23 14:05:00
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.autoconfigure
import com.mingliqiye.utils.logger.MingLiLoggerFactory
import org.springframework.beans.factory.config.BeanFactoryPostProcessor
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory
import org.springframework.beans.factory.support.BeanDefinitionRegistry
import org.springframework.context.annotation.AnnotationBeanNameGenerator
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider
import org.springframework.core.Ordered
import org.springframework.core.type.filter.AnnotationTypeFilter
import org.springframework.core.type.filter.AssignableTypeFilter
import org.springframework.stereotype.Component
import org.springframework.util.ClassUtils
/**
* 扫描继承自 `com.mingliqiye.utils.mybatisplus.FastBaseIService` 或
* `com.mingliqiye.utils.mybatisplus.FastBaseIServiceNew3518` 的具体类并注册为 Spring Bean。
*
* 两个基类分别适配旧版 `mybatis-plus-extension` 与新版 `mybatis-plus-spring`,哪个子类都能扫到。
* 基类按类名在运行期探测:缺少对应 MyBatis-Plus 依赖时只跳过该基类,
* 不会因为类字面量加载父类失败而抛 `NoClassDefFoundError` 导致启动中断。
*
* 这是一个 [BeanFactoryPostProcessor],Spring 保证它在所有
* `BeanDefinitionRegistryPostProcessor`(包括 `@MapperScan` 的 `MapperScannerConfigurer`)之后执行,
* 因此 mapper 的 BeanDefinition 已经注册完毕,服务里的 `baseMapper` 注入不会因为时机问题失败。
*
* 已经标注 `@Component` / `@Service` 的类会交给普通组件扫描,这里跳过以避免重复注册。
*
* @param basePackages 要扫描的包
*/
class FastServiceScannerProcessor(
private val basePackages: Array<String>,
) : BeanFactoryPostProcessor, Ordered {
private val log = MingLiLoggerFactory.getLogger<FastServiceScannerProcessor>()
override fun postProcessBeanFactory(beanFactory: ConfigurableListableBeanFactory) {
val registry = beanFactory as? BeanDefinitionRegistry ?: return
if (basePackages.isEmpty()) return
val classLoader = beanFactory.beanClassLoader ?: FastServiceScannerProcessor::class.java.classLoader
val scanner = ClassPathScanningCandidateComponentProvider(false).apply {
// 已有 @Component/@Service 的由组件扫描负责,避免重复注册
addExcludeFilter(AnnotationTypeFilter(Component::class.java))
}
var includeFilterCount = 0
for (baseClassName in BASE_SERVICE_CLASS_NAMES) {
// isPresent 内部 catch Throwable,父类缺失导致的 NoClassDefFoundError 也会返回 false
if (!ClassUtils.isPresent(baseClassName, classLoader)) {
log.debug("跳过未加载的服务基类: {}", baseClassName)
continue
}
val baseClass = try {
ClassUtils.forName(baseClassName, classLoader)
} catch (t: Throwable) {
log.debug("加载服务基类失败,已跳过: {}", baseClassName, t)
continue
}
// 多个 include filter 之间是 OR 关系
scanner.addIncludeFilter(AssignableTypeFilter(baseClass))
includeFilterCount++
}
if (includeFilterCount == 0) {
log.debug("没有可用的服务基类,跳过 FastBaseIService 扫描: packages={}", basePackages.toList())
return
}
val nameGenerator = AnnotationBeanNameGenerator()
var registered = 0
for (basePackage in basePackages) {
for (candidate in scanner.findCandidateComponents(basePackage)) {
val className = candidate.beanClassName ?: continue
val beanName = nameGenerator.generateBeanName(candidate, registry)
val existing = if (registry.containsBeanDefinition(beanName)) {
registry.getBeanDefinition(beanName)
} else null
when {
existing == null -> {
registry.registerBeanDefinition(beanName, candidate)
registered++
}
existing.beanClassName == className -> Unit
else -> {
// 不同包下简单类名相同,用全限定名避免覆盖
registry.registerBeanDefinition(className, candidate)
registered++
}
}
}
}
log.debug(
"FastBaseIService/FastBaseIServiceNew3518 扫描完成: packages={}, registered={}",
basePackages.toList(),
registered,
)
}
override fun getOrder(): Int = Ordered.LOWEST_PRECEDENCE
companion object {
/**
* 服务基类全限定名。用字符串而不是类字面量,避免运行期缺少对应 MyBatis-Plus 依赖时加载失败。
*/
private val BASE_SERVICE_CLASS_NAMES = listOf(
"com.mingliqiye.utils.mybatisplus.FastBaseIService",
"com.mingliqiye.utils.mybatisplus.FastBaseIServiceNew3518",
)
}
}
@@ -0,0 +1,236 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.test
* CurrentFile RedisLockTest.kt
* LastUpdate 2026-11-23 10:21:41
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.lock
import com.mingliqiye.utils.exception.RedisLockTimeoutException
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.redisson.api.RFuture
import org.redisson.api.RLock
import org.redisson.api.RedissonClient
import java.lang.reflect.Proxy
import java.util.concurrent.CompletableFuture
import java.util.concurrent.atomic.AtomicInteger
/**
* RedisLock 的单元测试,通过动态代理模拟 Redisson 客户端,不依赖真实 Redis。
*/
class RedisLockTest {
/** 测试正常加锁、执行业务并释放锁,等待时间/租约/owner 传递正确 */
@Test
fun testWithLockAcquiresAndReleases() = runBlocking {
val fake = FakeRedisson(acquireResult = true)
val lock = RedisLock(fake.client, keyPrefix = "test:", defaultWaitMillis = 1234)
var executed = false
lock.withLock("order:1") { executed = true }
assertTrue(executed)
assertEquals(listOf("test:order:1"), fake.lockNames)
assertEquals("test:order:1", lock.lockName("order:1"))
assertEquals(1, fake.acquireCalls.get())
assertEquals(1, fake.unlockCalls.get())
assertEquals(fake.acquireOwnerId, fake.unlockOwnerId)
assertEquals(1234L, fake.lastWaitMillis)
assertEquals(RedisLock.WATCHDOG_LEASE, fake.lastLeaseMillis)
}
/** 测试等待超时:抛 RedisLockTimeoutException,业务不执行、不释放锁 */
@Test
fun testWithLockTimeout() {
val fake = FakeRedisson(acquireResult = false)
val lock = RedisLock(fake.client)
var executed = false
assertThrows(RedisLockTimeoutException::class.java) {
runBlocking {
lock.withLock("k", waitMillis = 50) { executed = true }
}
}
assertFalse(executed)
assertEquals(0, fake.unlockCalls.get())
}
/** 测试 tryWithLock 抢不到锁时立即返回 null,不等待、不执行 */
@Test
fun testTryWithLockBusy() = runBlocking {
val fake = FakeRedisson(acquireResult = false)
val lock = RedisLock(fake.client)
val result = lock.tryWithLock("k") { "should not run" }
assertNull(result)
assertEquals(0L, fake.lastWaitMillis)
assertEquals(0, fake.unlockCalls.get())
}
/** 测试 tryWithLock 抢到锁时执行并返回结果,随后释放 */
@Test
fun testTryWithLockSuccess() = runBlocking {
val fake = FakeRedisson(acquireResult = true)
val lock = RedisLock(fake.client)
assertEquals("ok", lock.tryWithLock("k") { "ok" })
assertEquals(1, fake.unlockCalls.get())
assertEquals(fake.acquireOwnerId, fake.unlockOwnerId)
}
/** 测试公平锁配置使用 getFairLock */
@Test
fun testFairLock() = runBlocking {
val fake = FakeRedisson(acquireResult = true)
val lock = RedisLock(fake.client, fair = true)
lock.withLock("k") { }
assertTrue(fake.fairUsed)
}
/** 测试业务抛异常时依然释放锁 */
@Test
fun testReleaseOnBlockFailure() {
val fake = FakeRedisson(acquireResult = true)
val lock = RedisLock(fake.client)
assertThrows(IllegalStateException::class.java) {
runBlocking {
lock.withLock("k") { error("boom") }
}
}
assertEquals(1, fake.unlockCalls.get())
}
/** 测试自定义等待时间与固定租期会透传给 Redisson */
@Test
fun testCustomWaitAndLease() = runBlocking {
val fake = FakeRedisson(acquireResult = true)
val lock = RedisLock(fake.client, defaultWaitMillis = 100, leaseMillis = 5_000)
lock.withLock("k", waitMillis = 200) { }
assertEquals(200L, fake.lastWaitMillis)
assertEquals(5_000L, fake.lastLeaseMillis)
}
}
/**
* 使用动态代理模拟 RedissonClient / RLock。
*/
private class FakeRedisson(private val acquireResult: Boolean) {
val lockNames = mutableListOf<String>()
val acquireCalls = AtomicInteger()
val unlockCalls = AtomicInteger()
@Volatile
var acquireOwnerId: Long = -1
@Volatile
var unlockOwnerId: Long = -1
@Volatile
var lastWaitMillis: Long = -1
@Volatile
var lastLeaseMillis: Long = -1
@Volatile
var fairUsed: Boolean = false
private val lock: RLock = Proxy.newProxyInstance(
RLock::class.java.classLoader,
arrayOf(RLock::class.java),
) { proxy, method, args ->
when (method.name) {
"tryLockAsync" -> {
acquireCalls.incrementAndGet()
lastWaitMillis = args[0] as Long
lastLeaseMillis = args[1] as Long
acquireOwnerId = args[3] as Long
completedFuture(acquireResult)
}
"unlockAsync" -> {
unlockCalls.incrementAndGet()
unlockOwnerId = args[0] as Long
completedFuture<Void>(null)
}
"getName" -> "fake-lock"
"toString" -> "FakeRLock"
"hashCode" -> System.identityHashCode(proxy)
"equals" -> proxy === args[0]
else -> defaultValue(method.returnType)
}
} as RLock
val client: RedissonClient = Proxy.newProxyInstance(
RedissonClient::class.java.classLoader,
arrayOf(RedissonClient::class.java),
) { proxy, method, args ->
when (method.name) {
"getLock" -> {
lockNames += args[0] as String
fairUsed = false
lock
}
"getFairLock" -> {
lockNames += args[0] as String
fairUsed = true
lock
}
"toString" -> "FakeRedisson"
"hashCode" -> System.identityHashCode(proxy)
"equals" -> proxy === args[0]
else -> defaultValue(method.returnType)
}
} as RedissonClient
}
private fun <V> completedFuture(value: V?): RFuture<V> = object : CompletableFuture<V>(), RFuture<V> {
init {
complete(value)
}
}
private fun defaultValue(type: Class<*>): Any? = when (type) {
java.lang.Boolean.TYPE -> false
java.lang.Byte.TYPE -> 0.toByte()
java.lang.Short.TYPE -> 0.toShort()
java.lang.Integer.TYPE -> 0
java.lang.Long.TYPE -> 0L
java.lang.Float.TYPE -> 0f
java.lang.Double.TYPE -> 0.0
java.lang.Character.TYPE -> '\u0000'
else -> null
}
@@ -0,0 +1,115 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.test
* CurrentFile FastServiceScanRegistrarTest.kt
* LastUpdate 2026-11-23 14:21:18
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.autoconfigure
import com.mingliqiye.utils.springboot.annotation.FastServiceScan
import org.junit.jupiter.api.Assertions.assertArrayEquals
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.support.DefaultListableBeanFactory
import org.springframework.core.type.AnnotationMetadata
/**
* FastServiceScanRegistrar 的单元测试,不启动 Spring 容器,只验证注解解析与注册行为。
*/
class FastServiceScanRegistrarTest {
@FastServiceScan(basePackages = ["com.example.service"])
private class ExplicitPackagesConfig
@FastServiceScan("com.example.value")
private class ValueAliasConfig
@FastServiceScan(basePackageClasses = [FastServiceScanRegistrarTest::class])
private class ClassPackagesConfig
@FastServiceScan
private class DefaultPackageConfig
/** 测试显式 basePackages 会注册扫描器并使用配置的包 */
@Test
fun testExplicitPackages() {
val registry = DefaultListableBeanFactory()
val metadata = AnnotationMetadata.introspect(ExplicitPackagesConfig::class.java)
FastServiceScanRegistrar().registerBeanDefinitions(metadata, registry)
assertTrue(registry.containsBeanDefinition("fastServiceScannerProcessor"))
val beanDefinition = registry.getBeanDefinition("fastServiceScannerProcessor")
val packages = beanDefinition.constructorArgumentValues.getIndexedArgumentValue(0, Array<String>::class.java)?.value
assertArrayEquals(arrayOf("com.example.service"), packages as Array<*>)
}
/** 测试 value 与 basePackages 的 @AliasFor 生效 */
@Test
fun testValueAlias() {
val registry = DefaultListableBeanFactory()
val metadata = AnnotationMetadata.introspect(ValueAliasConfig::class.java)
FastServiceScanRegistrar().registerBeanDefinitions(metadata, registry)
val beanDefinition = registry.getBeanDefinition("fastServiceScannerProcessor")
val packages = beanDefinition.constructorArgumentValues.getIndexedArgumentValue(0, Array<String>::class.java)?.value
assertArrayEquals(arrayOf("com.example.value"), packages as Array<*>)
}
/** 测试 basePackageClasses 会转换为其所在包 */
@Test
fun testBasePackageClasses() {
val registry = DefaultListableBeanFactory()
val metadata = AnnotationMetadata.introspect(ClassPackagesConfig::class.java)
FastServiceScanRegistrar().registerBeanDefinitions(metadata, registry)
val beanDefinition = registry.getBeanDefinition("fastServiceScannerProcessor")
val packages = beanDefinition.constructorArgumentValues.getIndexedArgumentValue(0, Array<String>::class.java)?.value
assertArrayEquals(arrayOf("com.mingliqiye.utils.springboot.autoconfigure"), packages as Array<*>)
}
/** 测试不写包名时默认使用标注类所在包 */
@Test
fun testDefaultPackage() {
val registry = DefaultListableBeanFactory()
val metadata = AnnotationMetadata.introspect(DefaultPackageConfig::class.java)
FastServiceScanRegistrar().registerBeanDefinitions(metadata, registry)
val beanDefinition = registry.getBeanDefinition("fastServiceScannerProcessor")
val packages = beanDefinition.constructorArgumentValues.getIndexedArgumentValue(0, Array<String>::class.java)?.value
assertArrayEquals(arrayOf("com.mingliqiye.utils.springboot.autoconfigure"), packages as Array<*>)
}
/** 测试重复处理同一个配置类不会重复注册扫描器 */
@Test
fun testIdempotentRegistration() {
val registry = DefaultListableBeanFactory()
val metadata = AnnotationMetadata.introspect(ExplicitPackagesConfig::class.java)
val registrar = FastServiceScanRegistrar()
registrar.registerBeanDefinitions(metadata, registry)
registrar.registerBeanDefinitions(metadata, registry)
assertEquals(1, registry.beanDefinitionCount)
}
}
@@ -0,0 +1,76 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.test
* CurrentFile FastServiceScannerProcessorTest.kt
* LastUpdate 2026-11-23 14:05:00
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.autoconfigure
import com.mingliqiye.utils.mybatisplus.FastBaseIService
import com.mingliqiye.utils.mybatisplus.FastBaseIServiceNew3518
import com.mingliqiye.utils.mybatisplus.FastBaseMapper
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.support.DefaultListableBeanFactory
private class ScanTestEntity
private interface ScanTestMapper : FastBaseMapper<ScanTestEntity>
private class LegacyScanTestService : FastBaseIService<ScanTestEntity, ScanTestMapper>()
private class NewScanTestService : FastBaseIServiceNew3518<ScanTestEntity, ScanTestMapper>()
/**
* FastServiceScannerProcessor 的扫描测试:两个基类的子类都应被注册。
*/
class FastServiceScannerProcessorTest {
@Test
fun testScansBothBaseServices() {
val registry = DefaultListableBeanFactory()
FastServiceScannerProcessor(arrayOf("com.mingliqiye.utils.springboot.autoconfigure"))
.postProcessBeanFactory(registry)
assertTrue(registry.containsBeanDefinition("legacyScanTestService"))
assertTrue(registry.containsBeanDefinition("newScanTestService"))
}
/** 测试某个基类加载失败时只跳过该基类,不抛 NoClassDefFoundError */
@Test
fun testMissingBaseClassIsSkipped() {
val registry = DefaultListableBeanFactory()
registry.beanClassLoader = object : ClassLoader(FastServiceScannerProcessorTest::class.java.classLoader) {
override fun loadClass(name: String, resolve: Boolean): Class<*> {
if (name == "com.mingliqiye.utils.mybatisplus.FastBaseIService") {
throw ClassNotFoundException(name)
}
return super.loadClass(name, resolve)
}
}
FastServiceScannerProcessor(arrayOf("com.mingliqiye.utils.springboot.autoconfigure"))
.postProcessBeanFactory(registry)
assertTrue(registry.containsBeanDefinition("newScanTestService"))
assertFalse(registry.containsBeanDefinition("legacyScanTestService"))
}
}