How do you send data to a topic in Kafka?

Kafka offers multiple ways to send data to a topic, here are two common methods:

  1. Use the command line tool kafka-console-producer.sh (or kafka-console-producer.bat):
kafka-console-producer.sh --broker-list localhost:9092 --topic <topic-name>

This command will launch an interactive console where you can input the message you want to send and press Enter to send it.

  1. Send data using the Kafka client API.
import org.apache.kafka.clients.producer.*;

import java.util.Properties;

public class KafkaProducerExample {

    public static void main(String[] args) {

        String topicName = "<topic-name>";
        String key = "key1";
        String value = "value1";

        Properties props = new Properties();
        props.put("bootstrap.servers", "localhost:9092");
        props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

        Producer<String, String> producer = new KafkaProducer<>(props);

        ProducerRecord<String, String> record = new ProducerRecord<>(topicName, key, value);
        producer.send(record);

        producer.close();
    }
}

Please make sure that the address and port of Kafka match your actual environment, and replace ‘key’ and ‘value’ with the data you want to send.

This is a simple example code by Kafka, where you can customize more configurations and sending logic based on your needs.

bannerAds