示例#1
0
        public async Task SubscribeAsync <T>(Func <T, Task <bool> > handler, SubscribeOptions subscribeOptions = null, CancellationToken cancellationToken = default) where T : class
        {
            InitProcess();
            string topic = GetTopic(typeof(T));

            var groupId = subscribeOptions?.GroupId;

            groupId = !string.IsNullOrEmpty(groupId) ? groupId : RedisMessageBusOptions.DefaultGroupName;

            ValidateSubscribe(topic, groupId);

            _logger.LogInformation($"RedisMessageBus订阅Topic:{topic},GroupId:{groupId}");

            var groupPosition = !string.IsNullOrEmpty(subscribeOptions?.GroupPosition) ? subscribeOptions.GroupPosition : "$"; //0-0 $
            await _redisStorage.CreateConsumerGroupIfNotExist(topic, groupId, groupPosition);                                  //StreamPosition.NewMessages

#pragma warning disable CS4014
            Task.Run(async() =>
            {
                Func <JobData, Task <bool> > action = async message =>
                {
                    var realObj = _options.Serializer.Deserialize <T>(message.Data);
                    return(await handler(realObj));
                };
                //先处理当前消费者组中的pel数据 上次重启没有执行完成的 一台机器一个consumerName
                var consumerName   = GetConsumerName();
                var process        = new WorkerProcess(_serviceProvider, topic, groupId, consumerName);
                process.OnMessage += action;
                await process.ProcessPel(_backgroundProcessContext);//目前用同一个消费者名称,所以只处理第一个pel就行了
                await _processExecuter.AddProcess(process, $"RedisMessageBus即时任务开始执行:{topic}......");

                _backgroundProcessContext.SubscriberTopics.Add(new SubscriberTopicInfo {
                    Topic = topic, GroupName = groupId
                });                                                                                                            //便于ErrorProcess处理
            });
#pragma warning restore CS4014
        }