数据库
首页 > 数据库> > 分布式锁(3)Redisson之MultiLock

分布式锁(3)Redisson之MultiLock

作者:互联网

MultiLock

MultiLock:将多个锁合并为一个大锁,对一个大锁进行统一的申请加锁以及释放锁,一次性锁定多个资源,再去处理一些事情,然后事后一次性释放所有的资源对应的锁。

代码示例:

Config config = new Config();
config.useClusterServers()
    .addNodeAddress("redis://192.168.31.114:7001")
    .addNodeAddress("redis://192.168.31.184:7002");

RedissonClient redisson = Redisson.create(config);

RLock lock1 = redisson.getLock("lock1");
RLock lock2 = redisson.getLock("lock2");
RLock lock3 = redisson.getLock("lock3");

RedissonMultiLock lock = new RedissonMultiLock(lock1, lock2, lock3);
// locks: lock1 lock2 lock3
lock.lock();
lock.unlock();

核心源码:

根据锁的个数,计算出基础的等待时间。

long baseWaitTime = locks.size() * 1500;

循环尝试获取锁,直到获取锁成功后返回。

while (true) {
    if (tryLock(waitTime, leaseTime, unit)) {
        return;
    }
}

调用RedissonLock的tryLock方法,尝试获取锁,如果获取锁成功,把锁添加到集合。

List<RLock> acquiredLocks = new ArrayList<RLock>(locks.size());
lockAcquired = lock.tryLock();
acquiredLocks.add(lock);

如果获取锁超时就会退出,重新再次死循环尝试获取锁。

if (locks.size() - acquiredLocks.size() == failedLocksLimit()) {
    break;
}

if (failedLocksLimit == 0) {
    unlockInner(acquiredLocks);
    if (waitTime == -1 && leaseTime == -1) {
        return false;
    }
    failedLocksLimit = failedLocksLimit();
    acquiredLocks.clear();
    // reset iterator
    while (iterator.hasPrevious()) {
        iterator.previous();
    }
} else {
    failedLocksLimit--;
}

标签:Redisson,lock,failedLocksLimit,MultiLock,locks,lock1,acquiredLocks,size,分布式
来源: https://blog.csdn.net/qq40988670/article/details/90710496