Kafka Producer
Creating a kafka producer can be as simple as the code below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
static void Produce(string topic, ClientConfig config)
{
using (var producer = new ProducerBuilder<string, string>(config).Build())
{
int numProduced = 0;
int numMessages = 10;
for (int i=0; i<numMessages; ++i)
{
var key = "alice";
var val = JObject.FromObject(new { count = i }).ToString(Formatting.None);
Console.WriteLine($"Producing record: {key} {val}");
producer.Produce(topic, new Message<string, string> { Key = key, Value = val },
(deliveryReport) =>
{
if (deliveryReport.Error.Code != ErrorCode.NoError)
{
Console.WriteLine($"Failed to deliver message: {deliveryReport.Error.Reason}");
}
else
{
Console.WriteLine($"Produced message to: {deliveryReport.TopicPartitionOffset}");
numProduced += 1;
}
});
}
producer.Flush(TimeSpan.FromSeconds(10));
Console.WriteLine($"{numProduced} messages were produced to topic {topic}");
}
}