publicbooleantryLock(long waitTime, long leaseTime, TimeUnit unit)throws InterruptedException { long time = unit.toMillis(waitTime); long current = System.currentTimeMillis(); finallong threadId = Thread.currentThread().getId(); Long ttl = this.tryAcquire(leaseTime, unit, threadId); // 加锁 if (ttl == null) { returntrue; } else { } }
1 2 3
private Long tryAcquire(long leaseTime, TimeUnit unit, long threadId){ return (Long)this.get(this.tryAcquireAsync(leaseTime, unit, threadId)); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
private <T> RFuture<Long> tryAcquireAsync(long leaseTime, TimeUnit unit, finallong threadId){ if (leaseTime != -1L) { returnthis.tryLockInnerAsync(leaseTime, unit, threadId, RedisCommands.EVAL_LONG); // } else { RFuture<Long> ttlRemainingFuture = this.tryLockInnerAsync(this.commandExecutor.getConnectionManager().getCfg().getLockWatchdogTimeout(), TimeUnit.MILLISECONDS, threadId, RedisCommands.EVAL_LONG); ttlRemainingFuture.addListener(new FutureListener<Long>() { publicvoidoperationComplete(Future<Long> future)throws Exception { if (future.isSuccess()) { Long ttlRemaining = (Long)future.getNow(); if (ttlRemaining == null) { RedissonLock.this.scheduleExpirationRenewal(threadId); }
} } }); return ttlRemainingFuture; } }
1 2 3 4
<T> RFuture<T> tryLockInnerAsync(long leaseTime, TimeUnit unit, long threadId, RedisStrictCommand<T> command){ this.internalLockLeaseTime = unit.toMillis(leaseTime); returnthis.commandExecutor.evalWriteAsync(this.getName(), LongCodec.INSTANCE, command, "if (redis.call('exists', KEYS[1]) == 0) then redis.call('hset', 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(this.getName()), new Object[]{this.internalLockLeaseTime, this.getLockName(threadId)}); }