Created
April 6, 2020 01:43
-
-
Save xximjasonxx/dc6ad702e3e1d96f09897aa8d5470f27 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading; | |
using Confluent.Kafka; | |
namespace KafkaConsumer | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var config = new ConsumerConfig | |
{ | |
GroupId = "test-consumer-group", | |
BootstrapServers = "kafka-release.kube-kafka.svc.cluster.local:9092", | |
AutoOffsetReset = AutoOffsetReset.Earliest | |
}; | |
using (var consumer = new ConsumerBuilder<Ignore, string>(config).Build()) | |
{ | |
consumer.Subscribe("increment-topic"); | |
CancellationTokenSource cts = new CancellationTokenSource(); | |
Console.CancelKeyPress += (_, e) => | |
{ | |
e.Cancel = true; // prevent the process from terminating. | |
cts.Cancel(); | |
}; | |
try | |
{ | |
while (true) | |
{ | |
try | |
{ | |
var consumeResult = consumer.Consume(cts.Token); | |
Console.WriteLine($"Message: {consumeResult.Message.Value}"); | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine($"Error: {ex.Message}"); | |
} | |
Thread.Sleep(100); | |
} | |
} | |
catch (OperationCanceledException) | |
{ | |
consumer.Close(); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment