From 04498ffe56b062bce1200292b23d2c31341771e6 Mon Sep 17 00:00:00 2001 From: Charles7c Date: Thu, 7 Nov 2024 20:29:47 +0800 Subject: [PATCH] =?UTF-8?q?feat(cache/redisson):=20RedisUtils=20=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=E4=B8=8A=E9=94=81=E3=80=81=E9=87=8A=E6=94=BE=E9=94=81?= =?UTF-8?q?=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cache/redisson/util/RedisUtils.java | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/continew-starter-cache/continew-starter-cache-redisson/src/main/java/top/continew/starter/cache/redisson/util/RedisUtils.java b/continew-starter-cache/continew-starter-cache-redisson/src/main/java/top/continew/starter/cache/redisson/util/RedisUtils.java index c65f7b8e..a4beefd3 100644 --- a/continew-starter-cache/continew-starter-cache-redisson/src/main/java/top/continew/starter/cache/redisson/util/RedisUtils.java +++ b/continew-starter-cache/continew-starter-cache-redisson/src/main/java/top/continew/starter/cache/redisson/util/RedisUtils.java @@ -24,6 +24,8 @@ import java.time.Duration; import java.util.Collection; import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; /** * Redis 工具类 @@ -207,6 +209,80 @@ public static boolean rateLimit(String key, RateType rateType, int rate, int rat return rateLimiter.tryAcquire(1); } + /** + * 尝试获取锁 + * + * @param key 键 + * @param expireTime 锁过期时间(单位:毫秒) + * @param timeout 获取锁超时时间(单位:毫秒) + * @return true:成功;false:失败 + * @since 2.7.2 + */ + public static boolean tryLock(String key, long expireTime, long timeout) { + return tryLock(key, expireTime, timeout, TimeUnit.MILLISECONDS); + } + + /** + * 释放锁 + * + * @param key 键 + * @return true:释放成功;false:释放失败 + * @since 2.7.2 + */ + public static boolean unlock(String key) { + RLock lock = getLock(key); + return unlock(lock); + } + + /** + * 尝试获取锁 + * + * @param key 键 + * @param expireTime 锁过期时间 + * @param timeout 获取锁超时时间 + * @param unit 时间单位 + * @return true:成功;false:失败 + * @since 2.7.2 + */ + public static boolean tryLock(String key, long expireTime, long timeout, TimeUnit unit) { + RLock lock = getLock(key); + try { + return lock.tryLock(timeout, expireTime, unit); + } catch (InterruptedException e) { + return false; + } + } + + /** + * 释放锁 + * + * @param lock 锁实例 + * @return true:释放成功;false:释放失败 + * @since 2.7.2 + */ + public static boolean unlock(RLock lock) { + if (lock.isHeldByCurrentThread()) { + try { + lock.unlockAsync().get(); + return true; + } catch (ExecutionException | InterruptedException e) { + return false; + } + } + return false; + } + + /** + * 获取锁实例 + * + * @param key 键 + * @return 锁实例 + * @since 2.7.2 + */ + public static RLock getLock(String key) { + return CLIENT.getLock(key); + } + /** * 格式化键,将各子键用 : 拼接起来 *