Command Line Interface Producer for Kafka in C#

I recently wrote a post about using a simple Command Line Interface (CLI) consumer for Kafka in C#. You can find that post here.

Here is a simple CLI producer in C#. Again, it uses the dotnet run app.cs approach.

Here is the code -

 1#!/usr/bin/dotnet run
 2#:package Confluent.Kafka@2.5.0
 3using Confluent.Kafka;
 4
 5if (args.Length != 2 )
 6{
 7    Console.WriteLine("Usage: url topic");
 8    return;
 9}
10
11string url = args[0];
12string topic = args[1];
13
14ProducerConfig _producerConfig = new ProducerConfig
15{
16    BootstrapServers = url
17};
18var producer = new ProducerBuilder<string, string>(_producerConfig).Build();
19Console.WriteLine($"Enter text to send to topic: {topic}. Ctrl+C to exit.");
20
21while(true)
22{
23    var text = Console.ReadLine();
24    if (string.IsNullOrWhiteSpace(text))
25        continue;
26    SendMessage(text);
27}
28
29void SendMessage(string text)
30{
31    var message = new Message<string, string>
32    {
33        Key = Guid.NewGuid().ToString(),
34        Value = $"{text}"
35    };
36    producer.Produce(topic, message);
37}

This can be executed like a script after it is made executable with chmod +x producer.cs.

comments powered by Disqus

Related