コード例 #1
0
 public WorkflowManager
 (
     IActivityLibrary activityLibrary,
     IWorkflowTypeStore workflowTypeRepository,
     IWorkflowStore workflowRepository,
     IWorkflowIdGenerator workflowIdGenerator,
     Resolver <IEnumerable <IWorkflowValueSerializer> > workflowValueSerializers,
     IDistributedLock distributedLock,
     ILogger <WorkflowManager> logger,
     ILogger <MissingActivity> missingActivityLogger,
     IStringLocalizer <MissingActivity> missingActivityLocalizer,
     IClock clock
 )
 {
     _activityLibrary          = activityLibrary;
     _workflowTypeStore        = workflowTypeRepository;
     _workflowStore            = workflowRepository;
     _workflowIdGenerator      = workflowIdGenerator;
     _workflowValueSerializers = workflowValueSerializers;
     _distributedLock          = distributedLock;
     _logger = logger;
     _missingActivityLogger    = missingActivityLogger;
     _missingActivityLocalizer = missingActivityLocalizer;
     _clock = clock;
 }
コード例 #2
0
 public BaseScheduledJob(IDistributedLock distributedLock, IOptions <CommonOptions> options, ILogger <BaseScheduledJob> logger, IScheduledJobStore scheduledJobStore)
 {
     DistributedLock   = distributedLock;
     Options           = options.Value;
     Logger            = logger;
     ScheduledJobStore = scheduledJobStore;
 }
コード例 #3
0
        /// <summary>
        /// InitializeDatabaseAsync
        /// </summary>
        /// <param name="database"></param>
        /// <param name="lockManager"></param>
        /// <returns></returns>
        /// <exception cref="DatabaseException"></exception>
        public static async Task InitializeDatabaseAsync(HB.FullStack.Database.IDatabase database, IDistributedLockManager lockManager, IEnumerable <Migration>?migrations)
        {
            GlobalSettings.Logger.LogDebug($"开始初始化数据库:{database.DatabaseNames.ToJoinedString(",")}");

            IDistributedLock distributedLock = await lockManager.LockAsync(
                resources : database.DatabaseNames,
                expiryTime : TimeSpan.FromMinutes(5),
                waitTime : TimeSpan.FromMinutes(10)).ConfigureAwait(false);

            try
            {
                if (!distributedLock.IsAcquired)
                {
                    ThrowIfDatabaseInitLockNotGet(database.DatabaseNames);
                }

                GlobalSettings.Logger.LogDebug($"获取了初始化数据库的锁:{database.DatabaseNames.ToJoinedString(",")}");

                await database.InitializeAsync(migrations).ConfigureAwait(false);
            }
            finally
            {
                await distributedLock.DisposeAsync().ConfigureAwait(false);
            }
        }
        public async Task <bool> RenewAsync(IDistributedLock lockHandle, CancellationToken cancellationToken)
        {
            var kubernetesLock    = (KubernetesLockHandle)lockHandle;
            var renewedLockHandle = await _kubernetesClient.TryAcquireLock(kubernetesLock.LockId, kubernetesLock.Owner, TimeSpan.Parse(kubernetesLock.LockPeriod), cancellationToken);

            return(!string.IsNullOrEmpty(renewedLockHandle.LockId));
        }
コード例 #5
0
        private async Task AcquireLock(IDistributedLock consulLock, CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                if (!consulLock.IsHeld)
                {
                    if (_currentRole != NodeRole.Follower)
                    {
                        _applicationEvents.Publish(new NodeRoleTransitioned(NodeRole.Follower));
                        _currentRole = NodeRole.Follower;
                    }

                    consulLock.Acquire(cancellationToken);
                }

                while (!cancellationToken.IsCancellationRequested && consulLock.IsHeld)
                {
                    if (_currentRole != NodeRole.Leader)
                    {
                        _applicationEvents.Publish(new NodeRoleTransitioned(NodeRole.Leader));
                        _currentRole = NodeRole.Leader;
                    }

                    await Task.Delay(TimeSpan.FromSeconds(10), cancellationToken).ConfigureAwait(false);
                }
            }
        }
コード例 #6
0
        private void CreateRedisClient()
        {
            string writeServerList    = AppRuntime.Instance.CurrentApplication.ConfigSource.Config.Redis.WriteHosts;
            string readOnlyServerList = AppRuntime.Instance.CurrentApplication.ConfigSource.Config.Redis.ReadOnlyHosts;

            string[] writeHosts    = writeServerList.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            string[] readOnlyHosts = readOnlyServerList.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

            RedisClientManagerConfig config = new RedisClientManagerConfig();

            config.MaxWritePoolSize = AppRuntime.Instance.CurrentApplication.ConfigSource.Config.Redis.MaxWritePoolSize;
            config.MaxReadPoolSize  = AppRuntime.Instance.CurrentApplication.ConfigSource.Config.Redis.MaxReadPoolSize;
            config.AutoStart        = AppRuntime.Instance.CurrentApplication.ConfigSource.Config.Redis.AutoStart;

            this.redisClientManager = new PooledRedisClientManager(writeHosts, readOnlyHosts, config);

            this.redisClient = (RedisClient)redisClientManager.GetClient();

            this.redistTypedClient = this.redisClient.As <TMessage>();

            this.redisDistributedLock = new DistributedLock();

            this.redisDistributedLock.Lock(lockName, 0, 0, out this.lockExpire, this.redisClient);

            this.redisTypedTransaction = this.redistTypedClient.CreateTransaction();
        }
コード例 #7
0
        private static void Main(string[] args)
        {
            var storageKey = ConfigurationManager.AppSettings["storageKey"];

            Task.Run(async() =>
            {
                locker = AzureStorageDistributedLock.Create(
                    "parallelwork1",
                    options =>
                {
                    options.ConnectionString = storageKey;
                    options.Directory        = "leaserenewal";
                    options.LeaseDuration    = TimeSpan.FromSeconds(30);
                });

                var tasks = new List <Task>
                {
                    DoHugeWork(),
                };

                await Task.Delay(200); // wait until start the small work to be started in the second place always

                tasks.Add(DoSmallWork());

                await Task.WhenAll(tasks);
            }).Wait();

            Console.ReadLine();
        }
 private BlockchainIndexationStateRepository(
     IBlobStorage blobStorage,
     IDistributedLock @lock)
 {
     _blobStorage = blobStorage;
     _lock        = @lock;
 }
        public async Task ReleaseLockAsync(IDistributedLock lockHandle, CancellationToken cancellationToken)
        {
            var kubernetesLock = (KubernetesLockHandle)lockHandle;
            var response       = await _kubernetesClient.ReleaseLock(kubernetesLock.LockId, kubernetesLock.Owner);

            response.EnsureSuccessStatusCode();
        }
コード例 #10
0
        static void ZooKeeperReadWriteLockTest()
        {
            var rd = new Random();

            for (int i = 0; i < 5; i++)
            {
                Task.Factory.StartNew(() =>
                {
                    var seed = rd.Next(1, 100);
                    IDistributedLock zkLock = ((seed % 2) == 1)
                    ?
                                              new ZooKeeperWriteLock(new ZooKeeperReadWriteLockOptions()) as IDistributedLock
                    :
                                              new ZooKeeperReadLock(new ZooKeeperReadWriteLockOptions()) as IDistributedLock;

                    using (zkLock)
                    {
                        if (zkLock.Lock())
                        {
                            Thread.Sleep(1000);

                            zkLock.UnLock();
                            Trace.WriteLine("UnLock");
                        }
                        else
                        {
                            Trace.WriteLine("Get Lock Failed.");
                        }
                    }
                });
            }
        }
コード例 #11
0
 public PatchRepresentationCommandHandler(ISCIMRepresentationQueryRepository scimRepresentationQueryRepository, ISCIMRepresentationCommandRepository scimRepresentationCommandRepository, IDistributedLock distributedLock, IOptions <SCIMHostOptions> options)
 {
     _scimRepresentationQueryRepository   = scimRepresentationQueryRepository;
     _scimRepresentationCommandRepository = scimRepresentationCommandRepository;
     _distributedLock = distributedLock;
     _options         = options.Value;
 }
コード例 #12
0
 /// <summary>
 /// Lock
 /// </summary>
 /// <param name="client"></param>
 /// <param name="globalLockKey"></param>
 /// <param name="acquisitionTimeout">in seconds</param>
 /// <param name="lockTimeout">in seconds</param>
 public DisposableDistributedLock(IRedisClient client, string globalLockKey, int acquisitionTimeout, int lockTimeout)
 {
     myLock = new DistributedLock();
     myClient = client;
     this.globalLockKey = globalLockKey;
     lockState = myLock.Lock(globalLockKey, acquisitionTimeout, lockTimeout, out lockExpire, myClient);
 }
コード例 #13
0
 /// <summary>
 /// Lock
 /// </summary>
 /// <param name="client"></param>
 /// <param name="globalLockKey"></param>
 /// <param name="acquisitionTimeout">in seconds</param>
 /// <param name="lockTimeout">in seconds</param>
 public DisposableDistributedLock(IRedisClient client, string globalLockKey, int acquisitionTimeout, int lockTimeout)
 {
     myLock             = new DistributedLock();
     myClient           = client;
     this.globalLockKey = globalLockKey;
     lockState          = myLock.Lock(globalLockKey, acquisitionTimeout, lockTimeout, out lockExpire, myClient);
 }
コード例 #14
0
        protected override async Task StartInternal()
        {
            using (_dlock = await _lockService.CreateLockAsync(this.ProcessName,
                                                               TimeSpan.FromSeconds(1),
                                                               TimeSpan.MaxValue,
                                                               TimeSpan.FromSeconds(1),
                                                               StopRequested.Token,
                                                               () =>
            {
                // if process was not stopped from outside, restart it so it can try to acquire lock again
                if (!StopRequested.IsCancellationRequested)
                {
                    try
                    {
                        Stop().Wait();
                    }
                    catch (Exception e)
                    {
                        //todo : log
                    }
                    Start();
                }
            }))
            {
                if (_dlock != null && _dlock.IsAcquired)
                {
                    await _innerProcess.Start();

                    //await Stop();
                    return;
                }
            }
            await StartInternal();
        }
コード例 #15
0
 public ProcessCasePlanInstanceJob(IEventStoreRepository eventStoreRepository, IMessageBroker messageBroker, IOptions <CommonOptions> options, ICasePlanInstanceProcessor casePlanInstanceProcessor, IDistributedLock distributedLock, ICommitAggregateHelper commitAggregateHelper) : base(messageBroker, options)
 {
     _eventStoreRepository      = eventStoreRepository;
     _casePlanInstanceProcessor = casePlanInstanceProcessor;
     _distributedLock           = distributedLock;
     _commitAggregateHelper     = commitAggregateHelper;
 }
コード例 #16
0
ファイル: Program.cs プロジェクト: iracding/DistributedLocks
        private static void Main(string[] args)
        {
            var storageKey = ConfigurationManager.AppSettings["storageKey"];

            Task.Run(async() =>
            {
                locker = await AzureStorageDistributedLock.CreateAsync(
                    "parallelwork1",
                    options =>
                {
                    options.ConnectionString = storageKey;
                    options.Directory        = "singlenode";
                });

                var tasks = new List <Task>
                {
                    DoWork(1),
                    DoWork(2),
                    DoWork(3),
                    DoWork(4),
                    DoWork(5),
                    DoWork(6),
                    DoWork(7),
                    DoWork(8)
                };

                await Task.WhenAll(tasks);
            }).Wait();

            Console.ReadLine();
        }
コード例 #17
0
 public async Task ReleaseDistributedLockAsync(IDistributedLock <TIdentity> distributedLock)
 {
     foreach (var connection in Connections)
     {
         await UnlockOnInstanceAsync(connection, distributedLock);
     }
 }
コード例 #18
0
 public ReplaceRepresentationCommandHandler(ISCIMSchemaQueryRepository scimSchemaQueryRepository, ISCIMRepresentationQueryRepository scimRepresentationQueryRepository, ISCIMRepresentationHelper scimRepresentationHelper, ISCIMRepresentationCommandRepository scimRepresentationCommandRepository, IDistributedLock distributedLock)
 {
     _scimSchemaQueryRepository           = scimSchemaQueryRepository;
     _scimRepresentationQueryRepository   = scimRepresentationQueryRepository;
     _scimRepresentationHelper            = scimRepresentationHelper;
     _scimRepresentationCommandRepository = scimRepresentationCommandRepository;
     _distributedLock = distributedLock;
 }
コード例 #19
0
        public static IDisposable Acquire(IDistributedLock @lock, TimeSpan?timeout, CancellationToken cancellationToken)
        {
            var handle = @lock.TryAcquire(timeout ?? Timeout.InfiniteTimeSpan, cancellationToken);

            ValidateTryAcquireResult(handle, timeout);

            return(handle);
        }
コード例 #20
0
        [MethodImpl(MethodImplOptions.NoInlining)] // need to isolate for GC
        private WeakReference TestCleanupHelper(IDistributedLock lock1, IDistributedLock lock2)
        {
            var handle = lock1.Acquire();

            Assert.IsNull(lock2.TryAcquireAsync().Result);

            return(new WeakReference(handle));
        }
コード例 #21
0
 /// <summary>
 /// Lock
 /// </summary>
 /// <param name="client"></param>
 /// <param name="globalLockKey"></param>
 /// <param name="acquisitionTimeout">in seconds</param>
 /// <param name="lockTimeout">in seconds</param>
 public DisposableDistributedLock(ConnectionMultiplexer connection, string globalLockKey, int lockTimeout)
 {
     myLock             = new DistributedLock();
     myConnection       = connection;
     this.globalLockKey = globalLockKey;
     this.lockValue     = Guid.NewGuid().ToString();
     isLocked           = myLock.Lock(globalLockKey, this.lockValue, lockTimeout, myConnection);
 }
コード例 #22
0
        protected void Init(Action <IServiceCollection> lockServiceRegistration)
        {
            IServiceCollection services = new ServiceCollection();

            lockServiceRegistration(services);
            _serviceProvider = services.BuildServiceProvider();
            _distributedLock = _serviceProvider.GetRequiredService <IDistributedLock>();
        }
コード例 #23
0
 public BaseScheduledJob(
     IOptions <OpenIDHostOptions> options,
     ILogger <BaseScheduledJob> logger,
     IDistributedLock distributedLock)
 {
     Options         = options.Value;
     Logger          = logger;
     DistributedLock = distributedLock;
 }
コード例 #24
0
        public static void Acquire(this IDistributedLock mutexLock, int millisecondsTimeout)
        {
            var locked = mutexLock.TryAcquire(millisecondsTimeout);

            if (!locked)
            {
                throw new TimeoutException("Acquire lock timeout");
            }
        }
コード例 #25
0
ファイル: RedLockTests.cs プロジェクト: yzbai/HB.FullStack
        public async Task TestSingleLockAsync()
        {
            var resources = Mocker.MockResourcesWithThree();

            using (IDistributedLock redisLock = await _lockManager.LockAsync(resources, TimeSpan.FromSeconds(30), null, null).ConfigureAwait(false))
            {
                Assert.True(redisLock.IsAcquired);
            }
        }
コード例 #26
0
            public Task ReleaseLockAsync(IDistributedLock lockHandle, CancellationToken cancellationToken)
            {
                FakeLock x = (FakeLock)lockHandle;

                lock (_locks)
                {
                    _locks.Remove(x.LockId);
                }
                return(Task.CompletedTask);
            }
コード例 #27
0
        private ITaskSeriesTimer CreateLeaseRenewalTimer(TimeSpan leasePeriod, IDistributedLock lockHandle)
        {
            // renew the lease when it is halfway to expiring
            TimeSpan normalUpdateInterval = new TimeSpan(leasePeriod.Ticks / 2);

            IDelayStrategy     speedupStrategy = new LinearSpeedupStrategy(normalUpdateInterval, MinimumLeaseRenewalInterval);
            ITaskSeriesCommand command         = new RenewLeaseCommand(this._lockManager, lockHandle, speedupStrategy);

            return(new TaskSeriesTimer(command, this._exceptionHandler, Task.Delay(normalUpdateInterval)));
        }
コード例 #28
0
        private void StartLeaderElection(IDistributedLock consulLock, CancellationToken cancellationToken)
        {
            Task.Run(async() => await AcquireLock(consulLock, cancellationToken).ConfigureAwait(false), cancellationToken)
            .ContinueWith(t =>
            {
                (t.Exception ?? new AggregateException()).Handle(ex => true);

                StartLeaderElection(consulLock, cancellationToken);
            }, TaskContinuationOptions.OnlyOnFaulted);
        }
コード例 #29
0
 public BCNotificationJob(
     IBCAuthorizeRepository bcAuthorizeRepository,
     IEnumerable <IBCNotificationHandler> notificationHandlers,
     IOptions <OpenIDHostOptions> options,
     ILogger <BaseScheduledJob> logger,
     IDistributedLock distributedLock) : base(options, logger, distributedLock)
 {
     _bcAuthorizeRepository = bcAuthorizeRepository;
     _notificationHandlers  = notificationHandlers;
 }
コード例 #30
0
 public VolatileDocumentManager(
     IDistributedCache distributedCache,
     IDistributedLock distributedLock,
     IMemoryCache memoryCache,
     IOptionsMonitor <DocumentOptions> options)
     : base(distributedCache, memoryCache, options)
 {
     _isVolatile      = true;
     _distributedLock = distributedLock;
 }
コード例 #31
0
        private static Task DoWork(IDistributedLock locker, int number, string key)
        {
            Console.WriteLine($"Worker {key} work n {number} launched");

            return(locker.ExecuteAsync(async context =>
            {
                Console.WriteLine($"Worker {key} work n {number} starting");
                await Task.Delay(2000);
                Console.WriteLine($"Worker {key} work n {number} finished");
            }));
        }
コード例 #32
0
        public bool TryAcquireLock(string name, TimeSpan? maxValidFor, TimeSpan? timeout, out IDistributedLock dLock) {
            try {
                dLock = AcquireLockInternal(name, maxValidFor, timeout, throwOnTimeout: false);

                if (dLock != null) {
                    Logger.Debug("Successfully acquired lock '{0}'.", name);
                    return true;
                }

                Logger.Warning("Failed to acquire lock '{0}' within the specified timeout ({1}).", name, timeout);
            }
            catch (Exception ex) {
                Logger.Error(ex, "Error while trying to acquire lock '{0}'.", name);
                // TODO: Is it correct to not throw here? Should we instead ONLY swallow TimeoutException?
            }

            dLock = null;
            return false;
        }
コード例 #33
0
 /// <summary>
 /// Tries to acquire a lock with the specified parameters
 /// </summary>
 /// <param name="name">Unique name of the lock</param>
 /// <param name="timeout">Time span to wait for the lock before timing out</param>
 /// <param name="distributedLock">The ILockFile instance on success or null if the lock couldn't be acquired.</param>
 /// <returns>True if the lock could be acquired and false if not.</returns>
 public static bool TryAcquireLock(this IDistributedLockManager lockFileManager, string name, TimeSpan timeout, out IDistributedLock distributedLock)
 {
     distributedLock = lockFileManager.TryAcquireLock(name, timeout);
     return distributedLock != null;
 }
コード例 #34
0
 /// <summary>
 /// Lock
 /// </summary>
 /// <param name="client"></param>
 /// <param name="globalLockKey"></param>
 /// <param name="acquisitionTimeout">in seconds</param>
 /// <param name="lockTimeout">in seconds</param>
 public DisposableDistributedLock(IRedisClient client, string globalLockKey, int acquisitionTimeout, int lockTimeout)
 {
     myLock = new DistributedLock(client);
     lockState = myLock.Lock(globalLockKey, acquisitionTimeout, lockTimeout);
 }
コード例 #35
0
		/// <summary>
		/// Tries to immediately acquire a named distributed lock with no expiration time within the current tenant.
		/// </summary>
		/// <param name="name">The name of the lock to acquire.</param>
		/// <param name="lock">This out parameter will be assigned the acquired lock if successful.</param>
		/// <returns><c>true</c> if the lock could be immediately acquired, otherwise <c>false</c>.</returns>
		public static bool TryAcquireLock(this IDistributedLockService service, string name, out IDistributedLock @lock) {
            return service.TryAcquireLock(name, null, TimeSpan.Zero, out @lock);
        }