Skip to main content

java Rlock of redisson

背景

在重构一个java的服务的时候,发现使用了redisson的RLock,所以看一下RLock 如何实现

例子

        String LOCK = "lock";
String ID = "1";
RLock rLock = redissonClient.getLock(LOCK + ID);
if (!rLock.tryLock()) {
log.info("processingTask get Lock fail return, threadId:{}", Thread.currentThread());
return;
}

我发现这个getLock 和tryLock都没有过期时间,那么她是怎么实现的呢?

最后发现堆栈

tryLockInnerAsync:217, RedissonLock (org.redisson)
tryAcquireOnceAsync:153, RedissonLock (org.redisson)
tryLockAsync:470, RedissonLock (org.redisson)
tryLockAsync:465, RedissonLock (org.redisson)
tryLock:201, RedissonLock (org.redisson)
doTestLock:22, LockTest (lock)
    <T> RFuture<T> tryLockInnerAsync(long waitTime, long leaseTime, TimeUnit unit, long threadId, RedisStrictCommand<T> command) {
return evalWriteAsync(getRawName(), LongCodec.INSTANCE, command,
"if (redis.call('exists', KEYS[1]) == 0) then " +
"redis.call('hincrby', KEYS[1], ARGV[2], 1); " +
"redis.call('pexpire', KEYS[1], ARGV[1]); " +
"return nil; " +
"end; " +
"if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then " +
"redis.call('hincrby', KEYS[1], ARGV[2], 1); " +
"redis.call('pexpire', KEYS[1], ARGV[1]); " +
"return nil; " +
"end; " +
"return redis.call('pttl', KEYS[1]);",
Collections.singletonList(getRawName()), unit.toMillis(leaseTime), getLockName(threadId));
}

相关阅读