subscribe to a kafka topic in csharp

To subscribe to a Kafka topic in C#, you can use the Confluent.Kafka library, which is a .NET implementation of the Kafka protocol.

Here is an example of how to subscribe to a Kafka topic:

main.cs
using Confluent.Kafka;

// Set up a consumer configuration
var config = new ConsumerConfig
{
    BootstrapServers = "localhost:9092",
    GroupId = "my-group",
    AutoOffsetReset = AutoOffsetReset.Earliest
};

// Create a consumer instance
using var consumer = new ConsumerBuilder<Ignore, string>(config).Build();

// Subscribe to the topic
consumer.Subscribe("my-topic");

// Start consuming messages
while (true)
{
    var consumeResult = consumer.Consume();
    Console.WriteLine($"Received message: {consumeResult.Message.Value}");
}
539 chars
23 lines

In this example, we first set up a consumer configuration, specifying the Kafka broker(s) to connect to, the consumer group to join, and the starting offset for the consumer.

Next, we create a new consumer instance using the ConsumerBuilder class, passing in our consumer configuration and specifying the message key and value types as Ignore and string, respectively.

We then subscribe to the Kafka topic using the Subscribe method of the consumer instance.

Finally, we enter a loop that continuously consumes messages from the Kafka topic using the Consume method. Each consumed message is printed to the console, but you can process them in any way you like.

gistlibby LogSnag