Skip to content

Commit 04498ff

Browse files
committed
feat(cache/redisson): RedisUtils 新增上锁、释放锁方法
1 parent bd60411 commit 04498ff

File tree

1 file changed

+76
-0
lines changed
  • continew-starter-cache/continew-starter-cache-redisson/src/main/java/top/continew/starter/cache/redisson/util

1 file changed

+76
-0
lines changed

continew-starter-cache/continew-starter-cache-redisson/src/main/java/top/continew/starter/cache/redisson/util/RedisUtils.java

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@
2424
import java.time.Duration;
2525
import java.util.Collection;
2626
import java.util.List;
27+
import java.util.concurrent.ExecutionException;
28+
import java.util.concurrent.TimeUnit;
2729

2830
/**
2931
* Redis 工具类
@@ -207,6 +209,80 @@ public static boolean rateLimit(String key, RateType rateType, int rate, int rat
207209
return rateLimiter.tryAcquire(1);
208210
}
209211

212+
/**
213+
* 尝试获取锁
214+
*
215+
* @param key 键
216+
* @param expireTime 锁过期时间(单位:毫秒)
217+
* @param timeout 获取锁超时时间(单位:毫秒)
218+
* @return true:成功;false:失败
219+
* @since 2.7.2
220+
*/
221+
public static boolean tryLock(String key, long expireTime, long timeout) {
222+
return tryLock(key, expireTime, timeout, TimeUnit.MILLISECONDS);
223+
}
224+
225+
/**
226+
* 释放锁
227+
*
228+
* @param key 键
229+
* @return true:释放成功;false:释放失败
230+
* @since 2.7.2
231+
*/
232+
public static boolean unlock(String key) {
233+
RLock lock = getLock(key);
234+
return unlock(lock);
235+
}
236+
237+
/**
238+
* 尝试获取锁
239+
*
240+
* @param key 键
241+
* @param expireTime 锁过期时间
242+
* @param timeout 获取锁超时时间
243+
* @param unit 时间单位
244+
* @return true:成功;false:失败
245+
* @since 2.7.2
246+
*/
247+
public static boolean tryLock(String key, long expireTime, long timeout, TimeUnit unit) {
248+
RLock lock = getLock(key);
249+
try {
250+
return lock.tryLock(timeout, expireTime, unit);
251+
} catch (InterruptedException e) {
252+
return false;
253+
}
254+
}
255+
256+
/**
257+
* 释放锁
258+
*
259+
* @param lock 锁实例
260+
* @return true:释放成功;false:释放失败
261+
* @since 2.7.2
262+
*/
263+
public static boolean unlock(RLock lock) {
264+
if (lock.isHeldByCurrentThread()) {
265+
try {
266+
lock.unlockAsync().get();
267+
return true;
268+
} catch (ExecutionException | InterruptedException e) {
269+
return false;
270+
}
271+
}
272+
return false;
273+
}
274+
275+
/**
276+
* 获取锁实例
277+
*
278+
* @param key 键
279+
* @return 锁实例
280+
* @since 2.7.2
281+
*/
282+
public static RLock getLock(String key) {
283+
return CLIENT.getLock(key);
284+
}
285+
210286
/**
211287
* 格式化键,将各子键用 : 拼接起来
212288
*

0 commit comments

Comments
 (0)