private async Task DistributedStart() { try { if (Interlocked.CompareExchange(ref distributedMonitorTimeLock, 1, 0) == 0) { var consumers = rabbitEventBusContainer.GetConsumers(); foreach (var consumer in consumers) { if (consumer is RabbitConsumer value) { for (int i = 0; i < value.QueueList.Count(); i++) { var queue = value.QueueList[i]; var key = queue.ToString(); if (!Runners.ContainsKey(key)) { var weight = 100000 - Runners.Count; var(isOk, lockId, expectMillisecondDelay) = await grainFactory.GetGrain <IWeightHoldLock>(key).Lock(weight, lockHoldingSeconds); if (isOk) { if (Runners.TryAdd(key, lockId)) { var runner = new ConsumerRunner(client, provider, value, queue); ConsumerRunners.TryAdd(key, runner); await runner.Run(); } } } } } } Interlocked.Exchange(ref distributedMonitorTimeLock, 0); if (logger.IsEnabled(LogLevel.Information)) { logger.LogInformation("EventBus Background Service is working."); } } } catch (Exception exception) { logger.LogError(exception.InnerException ?? exception, nameof(DistributedStart)); Interlocked.Exchange(ref distributedMonitorTimeLock, 0); } }
private async Task Start(string node = null, string[] nodeList = null) { var consumers = rabbitEventBusContainer.GetConsumers(); var hash = nodeList == null || nodeList.Length == 0 ? null : new ConsistentHash(nodeList); var consumerList = new SortedList <int, ConsumerRunner>(); var rd = new Random((int)DateTimeOffset.UtcNow.Ticks); foreach (var consumer in consumers) { if (consumer is RabbitConsumer value) { for (int i = 0; i < value.QueueList.Count(); i++) { var queue = value.QueueList[i]; var hashNode = hash != null && nodeList.Length > 1 ? hash.GetNode(queue.Queue) : node; if (node == hashNode) { consumerList.Add(rd.Next(), new ConsumerRunner(client, provider.GetService <ILogger <ConsumerRunner> >(), value, queue)); } } } } await Work(node, consumerList.Values.ToList()); }