我是靠谱客的博主 忧心鱼,最近开发中收集的这篇文章主要介绍redisson的MultiLock连锁,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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();

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();

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);
  }

相关资料:
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

最后

以上就是忧心鱼为你收集整理的redisson的MultiLock连锁的全部内容,希望文章能够帮你解决redisson的MultiLock连锁所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(40)

评论列表共有 0 条评论

立即
投稿
返回
顶部