Lock() public method

acquire distributed, non-reentrant lock on key
public Lock ( string key, int acquisitionTimeout, int lockTimeout, long &lockExpire, IRedisClient client ) : long
key string global key for this lock
acquisitionTimeout int timeout for acquiring lock
lockTimeout int timeout for lock, in seconds (stored as value against lock key)
lockExpire long
client IRedisClient
return long
        public void Can_create_distributed_lock()
        {
            var key = "lockkey";
            int lockTimeout = 2;

            var distributedLock = new DistributedLock();
            long lockExpire;
            Assert.AreEqual(distributedLock.Lock(key, lockTimeout, lockTimeout, out lockExpire, Redis), DistributedLock.LOCK_ACQUIRED);

            //can't re-lock
            distributedLock = new DistributedLock();
            Assert.AreEqual(distributedLock.Lock(key, lockTimeout, lockTimeout, out lockExpire, Redis), DistributedLock.LOCK_NOT_ACQUIRED);

            // re-acquire lock after timeout
            Thread.Sleep(lockTimeout * 1000 + 1000);
            distributedLock = new DistributedLock();
            Assert.AreEqual(distributedLock.Lock(key, lockTimeout, lockTimeout, out lockExpire, Redis), DistributedLock.LOCK_RECOVERED);


            Assert.IsTrue(distributedLock.Unlock(key, lockExpire, Redis));

            //can now lock
            distributedLock = new DistributedLock();
            Assert.AreEqual(distributedLock.Lock(key, lockTimeout, lockTimeout, out lockExpire, Redis), DistributedLock.LOCK_ACQUIRED);


            //cleanup
            Assert.IsTrue(distributedLock.Unlock(key, lockExpire, Redis));
        }
示例#2
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        public override void Lock(object key)
        {
            using (var disposable = new PooledRedisClientManager.DisposablePooledClient<SerializingRedisClient>(ClientManager))
            {
                long lockExpire = 0;
                var aLock = new DistributedLock();
                var globalKey = CacheNamespace.GlobalKey(key, RedisNamespace.NumTagsForLockKey);
                try
                {
                    long rc = aLock.Lock(globalKey, _lockAcquisitionTimeout, _lockTimeout, out lockExpire, disposable.Client);
                    if (rc != DistributedLock.LOCK_NOT_ACQUIRED)
                        AcquiredLocks[key] = lockExpire;
                }
                catch (Exception)
                {
                    if (lockExpire != 0)
                        aLock.Unlock(globalKey, lockExpire, disposable.Client);
                }

            }
        }