public async Task TestDistributedLocker() { //autodelay = false var cacheKey = nameof(TestDistributedLocker).ToLower() + "-" + new Random().Next(10000, 20000).ToString(); var flagtrue = await _distributedLocker.LockAsync(cacheKey, 20, false); Assert.True(flagtrue.Success); var flagfalse = await _distributedLocker.LockAsync(cacheKey, 20, false); Assert.False(flagfalse.Success); var unLockResult = await _distributedLocker.SafedUnLockAsync(cacheKey, "111"); Assert.False(unLockResult); flagfalse = await _distributedLocker.LockAsync(cacheKey, 20, false); Assert.False(flagfalse.Success); unLockResult = await _distributedLocker.SafedUnLockAsync(cacheKey, flagtrue.LockValue); Assert.True(unLockResult); //autodelay = true cacheKey = nameof(TestDistributedLocker).ToLower() + "-" + new Random().Next(20001, 30000).ToString(); flagtrue = await _distributedLocker.LockAsync(cacheKey, 3, true); Assert.True(flagtrue.Success); await Task.Delay(1000 * 10); flagfalse = await _distributedLocker.LockAsync(cacheKey, 20); Assert.False(flagfalse.Success); unLockResult = await _distributedLocker.SafedUnLockAsync(cacheKey, "111"); Assert.False(unLockResult); unLockResult = await _distributedLocker.SafedUnLockAsync(cacheKey, flagtrue.LockValue); Assert.True(unLockResult); }
internal async Task InitWorkerNodesAsync(string serviceName) { var workerIdSortedSetCacheKey = string.Format(SharedCachingConsts.WorkerIdSortedSetCacheKey, serviceName); if (!_redisProvider.KeyExists(workerIdSortedSetCacheKey)) { _logger.LogInformation("Starting InitWorkerNodes:{0}", workerIdSortedSetCacheKey); var flag = await _distributedLocker.LockAsync(workerIdSortedSetCacheKey); if (!flag.Success) { await Task.Delay(300); await InitWorkerNodesAsync(serviceName); } long count = 0; try { var set = new Dictionary <long, double>(); for (long index = 0; index <= YitterSnowFlake.MaxWorkerId; index++) { set.Add(index, DateTime.Now.GetTotalMilliseconds()); } count = await _redisProvider.ZAddAsync(workerIdSortedSetCacheKey, set); } catch (Exception ex) { throw new Exception(ex.Message, ex); } finally { await _distributedLocker.SafedUnLockAsync(workerIdSortedSetCacheKey, flag.LockValue); } _logger.LogInformation("Finlished InitWorkerNodes:{0}:{1}", workerIdSortedSetCacheKey, count); } else { _logger.LogInformation("Exists WorkerNodes:{0}", workerIdSortedSetCacheKey); } }