Redisson readWriteLock

Redisson readWriteLock 其实是通过两个类:

  1. RedissonReadLock
  2. RedissonWriteLock

核心代码就是这两个类里面的script,如readlock的获取读锁如下

 return commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, command,
                                "local mode = redis.call('hget', KEYS[1], 'mode'); " +
                               //锁不存在
                                "if (mode == false) then " +
                                //设置hash内容
                                  "redis.call('hset', KEYS[1], 'mode', 'read'); " +
                                  "redis.call('hset', KEYS[1], ARGV[2], 1); " +
                                  //设置一个{lock}:6ebc68ab-79ce-42d7-9c7d-00401fab055e:1:rwlock_timeout:1 对象,注意结尾是:1
                                  "redis.call('set', KEYS[2] .. ':1', 1); " +
                                  "redis.call('pexpire', KEYS[2] .. ':1', ARGV[1]); " +
                                  "redis.call('pexpire', KEYS[1], ARGV[1]); " +
                                  "return nil; " +
                                "end; " +
                                "if (mode == 'read') or (mode == 'write' and redis.call('hexists', KEYS[1], ARGV[3]) == 1) then " +
                                //如果当前是读锁,或者写锁也是由当前线程获得
                                  "local ind = redis.call('hincrby', KEYS[1], ARGV[2], 1); " + 
                                  "local key = KEYS[2] .. ':' .. ind;" +
                                  "redis.call('set', key, 1); " +
                                  "redis.call('pexpire', key, ARGV[1]); " +
                                  "local remainTime = redis.call('pttl', KEYS[1]); " +
                                  "redis.call('pexpire', KEYS[1], math.max(remainTime, ARGV[1])); " +
                                  "return nil; " +
                                "end;" +
                                "return redis.call('pttl', KEYS[1]);",
                        Arrays.asList(getName(), getReadWriteTimeoutNamePrefix(threadId)), 
                        internalLockLeaseTime, getLockName(threadId), getWriteLockName(threadId));
 
  

可以看到几点:

  1. 以hash模式存放
  2. 整个hash设置了过期时间,即会自动释放锁
  3. 锁也设置了过期时间

你可能感兴趣的:(redis)