Exemple #1
0
        // подписываемся на ключ сообщения о появлении свободных задач
        public void SubscribeOnEventRun(EventKeyNames eventKeysSet)
        {
            string eventKeyFrontGivesTask = eventKeysSet.EventKeyFrontGivesTask;

            _logger.LogInformation(201, "This BackServer subscribed on key {0}.", eventKeyFrontGivesTask);

            // типовая блокировка множественной подписки до специального разрешения повторной подписки
            bool flagToBlockEventRun = true;

            _keyEvents.Subscribe(eventKeyFrontGivesTask, async(string key, KeyEvent cmd) =>
            {
                if (cmd == eventKeysSet.EventCmd && flagToBlockEventRun)
                {
                    // временная защёлка, чтобы подписка выполнялась один раз
                    flagToBlockEventRun = false;
                    _logger.LogInformation(301, "Key {Key} with command {Cmd} was received, flagToBlockEventRun = {Flag}.", eventKeyFrontGivesTask, cmd, flagToBlockEventRun);

                    // вернуть изменённое значение flagEvent из FetchKeysOnEventRun для возобновления подписки
                    flagToBlockEventRun = await _captures.FetchKeysOnEventRun(eventKeysSet);

                    _logger.LogInformation(901, "END - FetchKeysOnEventRun finished and This BackServer waits the next event.");
                }
            });

            string eventKeyCommand = $"Key = {eventKeyFrontGivesTask}, Command = {eventKeysSet.EventCmd}";

            _logger.LogInformation(19205, "You subscribed on event - {EventKey}.", eventKeyCommand);
        }
Exemple #2
0
        public void SubscribeOnEventFrom(EventKeyNames eventKeysSet) // _logger = 201
        {
            // ждёт команды с консоли с количеством генерируемых пакетов
            string   eventKey = eventKeysSet.EventKeyFrom;
            KeyEvent eventCmd = eventKeysSet.EventCmd;

            _keyEvents.Subscribe(eventKey, async(string key, KeyEvent cmd) =>
            {
                if (cmd == eventCmd)
                {
                    // по получению начинает цикл создания пакетов с задачами
                    _logger.LogInformation("Key {Key} with command {Cmd} was received.", eventKey, cmd);
                    int tasksPackagesCount = await _front.FrontServerEmulationMain(eventKeysSet);
                    _logger.LogInformation("Tasks Packages created in count = {0}.", tasksPackagesCount);
                }
            });

            string eventKeyCommand = $"Key = {eventKey}, Command = {eventCmd}";

            _logger.LogInformation("You subscribed on event - {EventKey}.", eventKeyCommand);
            _logger.LogInformation("To start the front emulation please send from Redis console the following command - \n{_}{0} {1} count NN (NN - packages count).", "      ", eventCmd, eventKey);
        }
Exemple #3
0
        private async Task BackgroundProcessing(CancellationToken stoppingToken)
        {
            EventKeyNames eventKeysSet = await _data.FetchAllConstants();

            //string backServerGuid = _guid ?? throw new ArgumentNullException(nameof(_guid));
            //eventKeysSet.BackServerGuid = backServerGuid;
            //string backServerPrefixGuid = $"{eventKeysSet.PrefixBackServer}:{backServerGuid}";
            //eventKeysSet.BackServerPrefixGuid = backServerPrefixGuid;

            //string eventKey = "task:add";
            string cancelKey             = "task:del";
            int    createdProcessesCount = 0;
            string backServerGuid        = $"{eventKeysSet.PrefixBackServer}:{_guid}"; // backserver:(this server guid)

            _logger.LogInformation(1101, "INIT No: {0} - guid of This Server was fetched in QueuedHostedService.", backServerGuid);
            // создать ключ для подписки из констант
            string prefixProcessAdd   = eventKeysSet.PrefixProcessAdd; // process:add
            string eventKeyProcessAdd = $"{prefixProcessAdd}:{_guid}"; // process:add:(this server guid)
            // поле-пустышка, но одинаковое с тем, что создаётся в основном методе - чтобы достать значение
            string eventFieldBack = eventKeysSet.EventFieldBack;

            _logger.LogInformation(1103, "Processes creation on This Server was subscribed on key {0} / field {1}.", eventKeyProcessAdd, eventFieldBack);
            // подписка на ключ добавления бэкграунд процессов(поле без разницы), в значении можно было бы ставить количество необходимых процессов
            // типовая блокировка множественной подписки до специального разрешения повторной подписки
            bool flagToBlockEventAdd = true;

            _keyEvents.Subscribe(eventKeyProcessAdd, async(string key, KeyEvent cmd) =>
            {
                if (cmd == KeyEvent.HashSet && flagToBlockEventAdd)
                {
                    // временная защёлка, чтобы подписка выполнялась один раз
                    flagToBlockEventAdd = false;
                    _logger.LogInformation(1111, "Received key {0} with command {1}", eventKeyProcessAdd, cmd);
                    // название поля тоже можно создать здесь и передать в метод
                    // ещё лучше - достать нужное значение заранее и передать только его, тогда метод будет синхронный (наверное)
                    // не лучше
                    // лучше
                    int requiredProcessesCount = await _cache.GetHashedAsync <int>(eventKeyProcessAdd, eventFieldBack);
                    if (requiredProcessesCount > 0)
                    {
                        createdProcessesCount = await AddProcessesToPerformingTasks(stoppingToken, requiredProcessesCount);
                        _logger.LogInformation(1131, "AddProcessesToPerformingTasks created processes count {0}", createdProcessesCount);

                        if (createdProcessesCount > 0)
                        {
                            flagToBlockEventAdd = true;
                        }
                    }
                    // если вызвали с неправильным значением в ключе, подписка навсегда останется заблокированной, где-то тут ее надо разблокировать
                }
            });

            string eventKeyCommand = $"Key {eventKeyProcessAdd}, HashSet command";

            _logger.LogInformation(1311, "You subscribed on event - {EventKey}.", eventKeyCommand);

            _keyEvents.Subscribe(cancelKey, (string key, KeyEvent cmd) =>
            {
                if (cmd == KeyEvent.HashSet)
                {
                    _logger.LogInformation("key {0} - command {1}", key, cmd);
                    if (createdProcessesCount > 0)
                    {
                        // останавливаем процесс
                        var cts = completingTasksProcesses[createdProcessesCount - 1].CancellationTaskToken;
                        cts.Cancel();

                        completingTasksProcesses.RemoveAt(createdProcessesCount - 1);
                        createdProcessesCount--;
                        _logger.LogInformation("One Task for Background Processes was removed, total count left {Count}", createdProcessesCount);
                    }
                    else
                    {
                        _logger.LogInformation("Task for Background Processes cannot be removed for some reason, total count is {Count}", createdProcessesCount);
                    }
                }
            });

            List <Task> processingTask = completingTasksProcesses.Select(t => t.ProcessingTask).ToList();

            await Task.WhenAll(processingTask);

            _logger.LogInformation("All Background Processes were finished, total count was {Count}", processingTask.Count);
        }