Esempio n. 1
0
        public async Task StartConsume(string groupId)
        {
            var conf = new ConsumerConfig
            {
                GroupId          = groupId,
                BootstrapServers = KafkaEndpoint,
                // Note: The AutoOffsetReset property determines the start offset in the event
                // there are not yet any committed offsets for the consumer group for the
                // topic/partitions of interest. By default, offsets are committed
                // automatically, so in this example, consumption will only start from the
                // earliest message in the topic 'my-topic' the first time you run the program.

                AutoOffsetReset = AutoOffsetReset.Earliest
            };

            using (var c = new ConsumerBuilder <string, string>(conf).Build())
            {
                c.Subscribe(_subsManager.GetTopics());

                try
                {
                    while (true)
                    {
                        try
                        {
                            var cr = c.Consume();
                            await ProcessEvent(cr.Key, cr.Value);

                            Console.WriteLine($"Consumed message '{cr.Key}' at: '{cr.TopicPartitionOffset}'.");
                        }
                        catch (ConsumeException e)
                        {
                            Console.WriteLine($"Error occured: {e.Error.Reason}");
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    // Ensure the consumer leaves the group cleanly and final offsets are committed.
                    c.Close();
                }
            }
        }