Пример #1
0
        public void TestCancelBlockingLock()
        {
            var cts = new CancellationTokenSource();

            var resource = $"testredislock-{Guid.NewGuid()}";

            using (var redisLockFactory = new RedisLockFactory(AllActiveEndPoints))
            {
                using (var firstLock = redisLockFactory.Create(
                           resource,
                           TimeSpan.FromSeconds(30),
                           TimeSpan.FromSeconds(10),
                           TimeSpan.FromSeconds(1)))
                {
                    Assert.That(firstLock.IsAcquired);

                    cts.CancelAfter(TimeSpan.FromSeconds(2));

                    Assert.Throws <OperationCanceledException>(() =>
                    {
                        using (var secondLock = redisLockFactory.Create(
                                   resource,
                                   TimeSpan.FromSeconds(30),
                                   TimeSpan.FromSeconds(10),
                                   TimeSpan.FromSeconds(1),
                                   cts.Token))
                        {
                            // should never get here
                            Assert.Fail();
                        }
                    });
                }
            }
        }
Пример #2
0
        public void TimeLock()
        {
            using (var redisLockFactory = new RedisLockFactory(AllActiveEndPoints))
            {
                var resource = $"testredislock-{Guid.NewGuid()}";

                for (var i = 0; i < 10; i++)
                {
                    var sw = Stopwatch.StartNew();

                    using (var redisLock = redisLockFactory.Create(resource, TimeSpan.FromSeconds(30)))
                    {
                        sw.Stop();

                        Logger.Info($"Acquire {i} took {sw.ElapsedTicks} ticks, success {redisLock.IsAcquired}");

                        sw.Restart();
                    }

                    sw.Stop();

                    Logger.Info($"Release {i} took {sw.ElapsedTicks} ticks, success");
                }
            }
        }
Пример #3
0
 public void Dispose()
 {
     _connection?.Close();
     _connection?.Dispose();
     _redisLockFactory?.Dispose();
     _connection       = null;
     _redisLockFactory = null;
 }
Пример #4
0
        public LockTestClass(EndPoint[] endPoints, int expire, int interval)
        {
            _redisLockFactory = new RedisLockFactory(endPoints);

            _resource = "the-thing-we-are-locking-on";
            _expiry   = TimeSpan.FromMilliseconds(expire);
            _interval = interval;
        }
Пример #5
0
        public void TestRaceForQuorum()
        {
            var locksAcquired = 0;

            var lockKey = $"testredislock-{ThreadSafeRandom.Next(10000)}";

            var tasks = new List <Task>();

            for (var i = 0; i < 3; i++)
            {
                var task = new Task(() =>
                {
                    Logger.Debug("Starting task");

                    using (var redisLockFactory = new RedisLockFactory(AllActiveEndPoints))
                    {
                        var sw = Stopwatch.StartNew();

                        using (var redisLock = redisLockFactory.Create(lockKey, TimeSpan.FromSeconds(30)))
                        {
                            sw.Stop();

                            Logger.Debug($"Lock method took {sw.ElapsedMilliseconds}ms to return, IsAcquired = {redisLock.IsAcquired}");

                            if (redisLock.IsAcquired)
                            {
                                Logger.Debug($"Got lock with id {redisLock.LockId}, sleeping for a bit");

                                Interlocked.Increment(ref locksAcquired);

                                // Sleep for long enough for the other threads to give up
                                //Thread.Sleep(TimeSpan.FromSeconds(2));
                                Task.Delay(TimeSpan.FromSeconds(2)).Wait();

                                Logger.Debug($"Lock with id {redisLock.LockId} done sleeping");
                            }
                            else
                            {
                                Logger.Debug("Couldn't get lock, giving up");
                            }
                        }
                    }
                }, TaskCreationOptions.LongRunning);

                tasks.Add(task);
            }

            foreach (var task in tasks)
            {
                task.Start();
            }

            Task.WaitAll(tasks.ToArray());

            Assert.That(locksAcquired, Is.EqualTo(1));
        }
        private RedisLockFactory GetLockFactory()
        {
            var endPoint = new List <EndPoint>
            {
                new DnsEndPoint(_host, _port)
            };

            var redLockFactory = new RedisLockFactory(endPoint);

            return(redLockFactory);
        }
Пример #7
0
        private static void CheckSingleRedisLock(IEnumerable <RedisLockEndPoint> endPoints, bool expectedToAcquire)
        {
            using (var redisLockFactory = new RedisLockFactory(endPoints))
            {
                var resource = $"testredislock-{Guid.NewGuid()}";

                using (var redisLock = redisLockFactory.Create(resource, TimeSpan.FromSeconds(30)))
                {
                    Assert.That(redisLock.IsAcquired, Is.EqualTo(expectedToAcquire));
                }
            }
        }
        public LocateAnExistingSaga_WithPrefix()
        {
            _redis = new Redis();
            var clientManager = ConnectionMultiplexer.Connect(new ConfigurationOptions()
            {
                EndPoints = { _redis.Endpoint }
            });
            var factory = new RedisLockFactory(new RedisLockEndPoint
            {
                EndPoint = _redis.Endpoint
            });

            _sagaRepository = new Lazy <ISagaRepository <SimpleSaga> >(() => new RedLockSagaRepository <SimpleSaga>(clientManager, factory, "prefix"));
        }
Пример #9
0
        public RedisConnectionWrapper(string connString = null)
        {
            this._connectionString = new Lazy <string>(
                () =>
            {
                if (string.IsNullOrEmpty(connString))
                {
                    connString = GetConnectionString();
                }
                return(connString);
            }
                );

            this._redisLockFactory = CreateRedisLockFactory();
        }
        public bool Execute(string key, Action action, double expirySec = 2)
        {
            RedisLockFactory redLockFactory = GetLockFactory();

            using (var redisLock = redLockFactory.Create(key, TimeSpan.FromSeconds(expirySec)))
            {
                if (redisLock.IsAcquired)
                {
                    action();
                    return(true);
                }
            }

            return(false);
        }
Пример #11
0
 /// <summary>
 /// 跳过式调用,如果事情正在被调用,直接跳过
 /// </summary>
 /// <param name="resource">锁定资源的标识</param>
 /// <param name="expiryTime">锁过期时间</param>
 /// <param name="work"></param>
 public bool OverlappingWork(string resource, TimeSpan expiryTime, Action work)
 {
     resource = this.CreateKey(resource);
     using (var redisLockFactory = new RedisLockFactory(redisLockEndPoints))
     {
         using (var redisLock = redisLockFactory.Create(resource, expiryTime))
         {
             if (redisLock.IsAcquired)
             {
                 work.Invoke();
                 return(true);
             }
         }
         return(false);
     }
 }
Пример #12
0
        public void TestFactoryHasAtLeastOneEndPoint()
        {
            Assert.Throws <ArgumentException>(() =>
            {
                using (var redisLockFactory = new RedisLockFactory(new EndPoint[] {}))
                {
                }
            });

            Assert.Throws <ArgumentNullException>(() =>
            {
                using (var redisLockFactory = new RedisLockFactory((IEnumerable <EndPoint>)null))
                {
                }
            });
        }
Пример #13
0
        public void TestSequentialLocks()
        {
            using (var redisLockFactory = new RedisLockFactory(AllActiveEndPoints))
            {
                var resource = $"testredislock-{Guid.NewGuid()}";

                using (var firstLock = redisLockFactory.Create(resource, TimeSpan.FromSeconds(30)))
                {
                    Assert.That(firstLock.IsAcquired, Is.True);
                }

                using (var secondLock = redisLockFactory.Create(resource, TimeSpan.FromSeconds(30)))
                {
                    Assert.That(secondLock.IsAcquired, Is.True);
                }
            }
        }
Пример #14
0
        private async Task DoOverlappingLocksAsync()
        {
            using (var redisLockFactory = new RedisLockFactory(AllActiveEndPoints))
            {
                var resource = $"testredislock-{Guid.NewGuid()}";

                using (var firstLock = await redisLockFactory.CreateAsync(resource, TimeSpan.FromSeconds(30)))
                {
                    Assert.That(firstLock.IsAcquired, Is.True);

                    using (var secondLock = await redisLockFactory.CreateAsync(resource, TimeSpan.FromSeconds(30)))
                    {
                        Assert.That(secondLock.IsAcquired, Is.False);
                    }
                }
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="T:EasyCaching.Redis.DefaultRedisCachingProvider"/> class.
        /// </summary>
        /// <param name="name">Name.</param>
        /// <param name="dbProviders">Db providers.</param>
        /// <param name="serializers">Serializers.</param>
        /// <param name="options">Options.</param>
        /// <param name="factory">Distributed lock factory</param>
        /// <param name="loggerFactory">Logger factory.</param>
        public DefaultRedisCachingProvider(
            string name,
            IEnumerable <IRedisDatabaseProvider> dbProviders,
            IEnumerable <IEasyCachingSerializer> serializers,
            RedisOptions options,
            RedisLockFactory factory     = null,
            ILoggerFactory loggerFactory = null)
            : base(factory, options)
        {
            ArgumentCheck.NotNullAndCountGTZero(dbProviders, nameof(dbProviders));
            ArgumentCheck.NotNullAndCountGTZero(serializers, nameof(serializers));

            this._name       = name;
            this._dbProvider = dbProviders.Single(x => x.DBProviderName.Equals(name));
            this._options    = options;
            this._logger     = loggerFactory?.CreateLogger <DefaultRedisCachingProvider>();
            this._cache      = _dbProvider.GetDatabase();
            this._servers    = _dbProvider.GetServerList();
            this._cacheStats = new CacheStats();

            this._serializer = !string.IsNullOrWhiteSpace(options.SerializerName)
                ? serializers.Single(x => x.Name.Equals(options.SerializerName))
                : serializers.FirstOrDefault(x => x.Name.Equals(_name)) ?? serializers.Single(x => x.Name.Equals(EasyCachingConstValue.DefaultSerializerName));

            this.ProviderName          = this._name;
            this.ProviderType          = CachingProviderType.Redis;
            this.ProviderStats         = this._cacheStats;
            this.ProviderMaxRdSecond   = _options.MaxRdSecond;
            this.IsDistributedProvider = true;

            _info = new ProviderInfo
            {
                CacheStats            = _cacheStats,
                EnableLogging         = options.EnableLogging,
                IsDistributedProvider = IsDistributedProvider,
                LockMs         = options.LockMs,
                MaxRdSecond    = options.MaxRdSecond,
                ProviderName   = ProviderName,
                ProviderType   = ProviderType,
                SerializerName = options.SerializerName,
                SleepMs        = options.SleepMs,
                Serializer     = _serializer,
                CacheNulls     = options.CacheNulls
            };
        }
Пример #16
0
        public void TestBlockingConcurrentLocks()
        {
            var locksAcquired = 0;

            using (var redisLockFactory = new RedisLockFactory(AllActiveEndPoints))
            {
                var resource = $"testblockingconcurrentlocks-{Guid.NewGuid()}";

                var threads = new List <Thread>();

                for (var i = 0; i < 2; i++)
                {
                    var thread = new Thread(() =>
                    {
                        // ReSharper disable once AccessToDisposedClosure (we join on threads before disposing)
                        using (var redisLock = redisLockFactory.Create(
                                   resource,
                                   TimeSpan.FromSeconds(2),
                                   TimeSpan.FromSeconds(10),
                                   TimeSpan.FromSeconds(0.5)))
                        {
                            Logger.Info("Entering lock");
                            if (redisLock.IsAcquired)
                            {
                                Interlocked.Increment(ref locksAcquired);
                            }
                            Thread.Sleep(4000);
                            Logger.Info("Leaving lock");
                        }
                    });

                    thread.Start();

                    threads.Add(thread);
                }

                foreach (var thread in threads)
                {
                    thread.Join();
                }
            }

            Assert.That(locksAcquired, Is.EqualTo(2));
        }
Пример #17
0
        public void TestRenewing()
        {
            using (var redisLockFactory = new RedisLockFactory(AllActiveEndPoints))
            {
                var resource = $"testrenewinglock-{Guid.NewGuid()}";

                int extendCount;

                using (var redisLock = redisLockFactory.Create(resource, TimeSpan.FromSeconds(2)))
                {
                    Assert.That(redisLock.IsAcquired, Is.True);

                    Thread.Sleep(4000);

                    extendCount = redisLock.ExtendCount;
                }

                Assert.That(extendCount, Is.GreaterThan(2));
            }
        }
Пример #18
0
        public void TestLockReleasedAfterTimeout()
        {
            using (var lockFactory = new RedisLockFactory(AllActiveEndPoints))
            {
                var resource = $"testrenewinglock-{Guid.NewGuid()}";

                using (var firstLock = lockFactory.Create(resource, TimeSpan.FromSeconds(1)))
                {
                    Assert.That(firstLock.IsAcquired, Is.True);

                    Thread.Sleep(550);                           // should cause keep alive timer to fire once
                    ((RedisLock)firstLock).StopKeepAliveTimer(); // stop the keep alive timer to simulate process crash
                    Thread.Sleep(1200);                          // wait until the key expires from redis

                    using (var secondLock = lockFactory.Create(resource, TimeSpan.FromSeconds(1)))
                    {
                        Assert.That(secondLock.IsAcquired, Is.True);                         // Eventually the outer lock should timeout
                    }
                }
            }
        }
Пример #19
0
 public RedisConnectionWrapper(SiteConfig config)
 {
     this._config           = config;
     this._connectionString = new Lazy <string>(GetConnectionString);
     this._redisLockFactory = CreateRedisLockFactory();
 }
 public RedLockSagaRepository(IConnectionMultiplexer redisConnection, RedisLockFactory lockFactory)
 {
     _redisConnection = redisConnection;
     _lockFactory     = lockFactory;
 }
Пример #21
0
 public RedisConnectionWrapper(DapperRepositoryConfig config)
 {
     _config           = config;
     _connectionString = new Lazy <string>(GetConnectionString);
     _redisLockFactory = CreateRedisLockFactory();
 }
Пример #22
0
 public RedisConnectionWrapper(string connectionString)
 {
     this._connectionString = connectionString;
     this._redisLockFactory = CreateRedisLockFactory();
 }