示例#1
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            using (var scope = _serviceScopeFactory.CreateScope())
            {
                _handler = scope.ServiceProvider.GetRequiredService <IKafkaHandler <TK, TV> >();

                var builder = new ConsumerBuilder <TK, TV>(_config).SetValueDeserializer(new KafkaDeserializer <TV>());

                using (IConsumer <TK, TV> consumer = builder.Build())
                {
                    consumer.Subscribe(_config.Topic);

                    while (!stoppingToken.IsCancellationRequested)
                    {
                        var result = consumer.Consume(TimeSpan.FromMilliseconds(1000));

                        if (result != null)
                        {
                            await _handler.HandleAsync(result.Message.Key, result.Message.Value);

                            consumer.Commit(result);

                            consumer.StoreOffset(result);
                        }
                    }
                }
            }
        }
        public void ExecuteCore(CancellationToken stoppingToken)
        {
            ConsumerBuilder <TK, TV> builder = new ConsumerBuilder <TK, TV>(_config).SetValueDeserializer(new KafkaDeserializer <TV>());

            using (IConsumer <TK, TV> consumer = builder.Build())
            {
                if (_config.Active)
                {
                    consumer.Subscribe(_config.Topic);

                    while (!stoppingToken.IsCancellationRequested)
                    {
                        ConsumeResult <TK, TV> result = consumer.Consume(TimeSpan.FromMilliseconds(1000));

                        if (result != null)
                        {
                            _handler.HandleAsync(result.Key, result.Value).GetAwaiter().GetResult();
                            consumer.Commit(result);
                            consumer.StoreOffset(result);
                        }
                    }
                }
            }
        }