diff --git a/.gitignore b/.gitignore index 2be46cb..0c19fd8 100644 --- a/.gitignore +++ b/.gitignore @@ -43,6 +43,6 @@ bin/ log .idea node_modules -*lock* +*.lock .kotlin secret.gpg diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f894b8..246a0ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,28 @@ 本文件记录 mingli-utils 各版本的主要变更。 +## [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 ### 新增 diff --git a/build.gradle.kts b/build.gradle.kts index 029ff0e..76696de 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -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 10:24:07 * UpdateUser MingLiPro */ @@ -59,10 +59,10 @@ 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 VERSIONS = providers.gradleProperty("VERSIONS").get() +val ARTIFACTID = providers.gradleProperty("ARTIFACTID").get() +val JDKVERSIONS = providers.gradleProperty("JDKVERSIONS").get().toInt() group = GROUPSID @@ -113,9 +113,11 @@ 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("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 +257,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" ) - ) + ), ) ) } diff --git a/gradle.properties b/gradle.properties index b9f31ff..a5c78ba 100644 --- a/gradle.properties +++ b/gradle.properties @@ -16,10 +16,10 @@ # ProjectName mingli-utils # ModuleName mingli-utils # CurrentFile gradle.properties -# LastUpdate 2026-11-23 09:56:18 +# LastUpdate 2026-11-23 10:43:58 # UpdateUser MingLiPro # JDKVERSIONS=17 GROUPSID=com.mingliqiye.utils ARTIFACTID=mingli-utils -VERSIONS=5.6.0 +VERSIONS=5.7.0 diff --git a/settings.gradle.kts b/settings.gradle.kts index d13a582..fb3c59e 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -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 { diff --git a/src/main/kotlin/com/mingliqiye/utils/exception/RedisLockTimeoutException.kt b/src/main/kotlin/com/mingliqiye/utils/exception/RedisLockTimeoutException.kt new file mode 100644 index 0000000..1d30bee --- /dev/null +++ b/src/main/kotlin/com/mingliqiye/utils/exception/RedisLockTimeoutException.kt @@ -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") diff --git a/src/main/kotlin/com/mingliqiye/utils/lock/RedisLock.kt b/src/main/kotlin/com/mingliqiye/utils/lock/RedisLock.kt new file mode 100644 index 0000000..a87ba02 --- /dev/null +++ b/src/main/kotlin/com/mingliqiye/utils/lock/RedisLock.kt @@ -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() + + 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 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 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).await() + } + + private suspend fun release(lock: RLock, ownerId: Long) { + withContext(NonCancellable) { + try { + val released = withTimeoutOrNull(RELEASE_TIMEOUT_MILLIS.milliseconds) { + (lock.unlockAsync(ownerId) as CompletionStage).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() + } +} diff --git a/src/test/kotlin/com/mingliqiye/utils/lock/RedisLockTest.kt b/src/test/kotlin/com/mingliqiye/utils/lock/RedisLockTest.kt new file mode 100644 index 0000000..2337944 --- /dev/null +++ b/src/test/kotlin/com/mingliqiye/utils/lock/RedisLockTest.kt @@ -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() + 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(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 completedFuture(value: V?): RFuture = object : CompletableFuture(), RFuture { + 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 +}