Install nvm for Running Different Node.js Version Locally

2022/7/92 min read
bookmark this
Responsive image

Login

You can try Kafka for 30 days as free, so just login into Kafka with your email. At GTM, click Triggers > Custom Events, and enter the event name as contact_lead. Get start with Kafka

create a cluster

Once register with new email, you'll receive $400 credit as free trial for 30 days.

Get start with event driven application with C#

Set up a topic

Here, we enter the topic name manually at UI, we'll need to setup cluster key and secret later in order to communicate from c# client. create a kafka topic online

Click the Create Kafka cluster API key to get API key.

Produce Data

Follow is C# version of code to send message to kafka as string key and value

    static void SendKafkaString(string topic, string key, string value)
    {
        IConfiguration configuration = readConfig();
        Message<string, string> message = new Message<string, string> { Key = key, Value = value };
        using (var producer = new ProducerBuilder<string, string>(configuration.AsEnumerable()).Build())
        {
            producer.Produce(topic, message,
              (deliveryReport) =>
              {
                  KafkaResult(deliveryReport, topic);
              }
            );

            producer.Flush(TimeSpan.FromSeconds(10));
        }
    }
SendKafkaString("topic_0", "key_2000", "test12");

This is the actual result shows at Kafka UI. kafka message result

var myJson = @"{
    ""str"": ""a string"",
    ""int"": 1,
    ""obj"": {
    ""key"": ""value""
    }
}";

SendKafkaString("topic_0", "key_2000", myJson);

Since the value type is string, we can also sending as JSON to Kafka. kafka message result

Following is how to use serialize object as JSON to Kafka with C# client.

var objectTest = new ModelClass { Name = "yo" };
SendKafkaBytes("topic_0", "key_2100", System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(objectTest));

This's the content of the code, which take byte array as parameter.

static void SendKafkaBytes(string topic, string key, byte[] value)
{
    IConfiguration configuration = readConfig();
    Message<string, byte[]> message = new() { Key = key, Value = value };
    using var producer = new ProducerBuilder<string, byte[]>(configuration.AsEnumerable()).Build();
    producer.Produce(topic, message,
        (deliveryReport) =>
        {
            KafkaResult(deliveryReport, topic);
        }
    );

    producer.Flush(TimeSpan.FromSeconds(10));
}

This's the result, how to send object to Kafka. kafka message result

Consume Data