60 lines
2.2 KiB
C#
60 lines
2.2 KiB
C#
|
|
using Confluent.Kafka;
|
|||
|
|
|
|||
|
|
namespace ConsoleAppConsume
|
|||
|
|
{
|
|||
|
|
internal class Program
|
|||
|
|
{
|
|||
|
|
static void Main(string[] args)
|
|||
|
|
{
|
|||
|
|
var conf = new ConsumerConfig
|
|||
|
|
{
|
|||
|
|
GroupId = "test-consumer-group",
|
|||
|
|
BootstrapServers = "localhost:9092",
|
|||
|
|
// 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("test-topic");
|
|||
|
|
|
|||
|
|
CancellationTokenSource cts = new CancellationTokenSource();
|
|||
|
|
Console.CancelKeyPress += (_, e) =>
|
|||
|
|
{
|
|||
|
|
// Prevent the process from terminating.
|
|||
|
|
e.Cancel = true;
|
|||
|
|
cts.Cancel();
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
try
|
|||
|
|
{
|
|||
|
|
while (true)
|
|||
|
|
{
|
|||
|
|
try
|
|||
|
|
{
|
|||
|
|
var cr = c.Consume(cts.Token);
|
|||
|
|
var v= cr.Message.Value;
|
|||
|
|
var k=cr.Message.Key;
|
|||
|
|
Console.WriteLine($"Consumed message '{k} {v}' 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();
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
Console.WriteLine("Hello, World!");
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|