当前位置:   article > 正文

redisson的MultiLock连锁_redisson getmultilock

redisson getmultilock
redisson中的MultiLock,可以把一组锁当作一个锁来加锁和释放。
1.官方文档的解释:

Redis based distributed RedissonMultiLock object groups multiple RLock objects and handles them as one lock. Each RLock object may belong to different Redisson instances.

基于Redis的分布式RedissonMultiLock对象将多个RLock对象分组,并将它们作为一个锁处理。每个RLock对象可能属于不同的Redisson实例。

RLock lock1 = redissonInstance1.getLock("lock1");
RLock lock2 = redissonInstance2.getLock("lock2");
RLock lock3 = redissonInstance3.getLock("lock3");

RedissonMultiLock lock = new RedissonMultiLock(lock1, lock2, lock3);
// locks: lock1 lock2 lock3
lock.lock();
...
lock.unlock();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

If Redis nodes stored lock state crash and multiple locks have been already acquired then they could hang forever. To avoid this Redisson maintains lock watchdog, it prolongs each lock expiration while lock holder Redisson instance is alive. By default lock watchdog timeout is 30 seconds and can be changed through Config.lockWatchdogTimeout setting.

如果Redis节点存储的锁状态崩溃,并且已经获得多个锁,那么它们可能永远挂起。为了避免这种情况,Redisson维护了一个监控锁的看门狗,它在锁持有者Redisson实例活动时延长每个锁过期时间。默认情况下锁看门狗超时时间为30秒,可以通过Config的lockWatchdogTimeout进行设置。

Also Redisson allow to specify leaseTime parameter during lock acquisition. After specified time interval all locked locks will be released automatically.

此外,Redisson允许在锁获取期间指定leaseTime参数。在指定的时间间隔后,所有锁将自动释放。

RedissonMultiLock lock = new RedissonMultiLock(lock1, lock2, lock3);
// Acquire lock1, lock2, lock3 and release it automatically after 10 seconds
// if unlock method hasn't been invoked
lock.lock(10, TimeUnit.SECONDS);

// Wait for 100 seconds and automatically unlock it after 10 seconds
boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS);
...
lock.unlock();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
2.用法示例

几个锁,会被当作一组锁,然后这一组锁,当做一个锁,进行加锁和释放锁,可以设置过期时间,在过期时间到来时,所有的锁都会被主动释放,这可以预防,因为服务的崩溃,导致锁hang住不释放的情况。

  public void multiLock(Integer expireTime,TimeUnit timeUnit,String ...lockKey){
    RLock [] rLocks = new RLock[lockKey.length];
    for(int i = 0,length = lockKey.length; i < length ;i ++){
      RLock lock = redissonClient.getLock(lockKey[i]);
      rLocks[i] = lock;
    }
    RedissonMultiLock multiLock = new RedissonMultiLock(rLocks);
    multiLock.lock(expireTime,timeUnit);
    logger.info("【Redisson lock】success to acquire multiLock for [ "+lockKey+" ],expire time:"+expireTime+timeUnit);
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

相关资料:
https://blog.csdn.net/u010359884/article/details/50310387
https://github.com/redisson/redisson/wiki/1.-概述
http://redis.cn/topics/distlock.html
https://blog.csdn.net/qq523786283/article/details/80648469
https://blog.csdn.net/lijingyao8206/article/details/51150936

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/200955
推荐阅读
相关标签
  

闽ICP备14008679号