publish a message to a kafka topic in csharp

To publish a message to a Kafka topic in C#, you will need to use a Kafka producer. Here's an example code snippet that demonstrates how to create a producer and send a message:

main.cs
using Confluent.Kafka; // make sure to install the Confluent.Kafka package

string topicName = "my-topic";
string bootstrapServers = "localhost:9092"; // replace with the address of your Kafka broker(s)

var config = new ProducerConfig { BootstrapServers = bootstrapServers };

using (var producer = new ProducerBuilder<Null, string>(config).Build())
{
    string message = "Hello, Kafka!"; // replace with your message

    var result = await producer.ProduceAsync(topicName, new Message<Null, string> { Value = message });

    Console.WriteLine($"Message sent (value: {result.Value}, partition: {result.Partition}, offset: {result.Offset})");
}
648 chars
16 lines

This code creates a producer using the ProducerBuilder class and then sends a message to the specified topic using the ProduceAsync method. The resulting DeliveryResult contains information about the sent message, such as its partition and offset.

Note that to use this code, you will need to install the Confluent.Kafka package.

gistlibby LogSnag