How can messages be sent to a Kafka topic?
The Producer API of Kafka allows sending messages to one or multiple topics.
Firstly, you need to create a Producer instance and pass the address of the Kafka cluster to it. You can specify the address of the Kafka cluster by specifying one or more bootstrap.servers properties.
Properties props = new Properties();
props.put("bootstrap.servers", "kafka1:9092,kafka2: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);
Next, you can use the send method of the Producer to send a message to the Topic. You will need to create a ProducerRecord instance and specify the Topic, key, and value of the message to be sent.
String topic = "my-topic";
String key = "my-key";
String value = "Hello, Kafka!";
ProducerRecord<String, String> record = new ProducerRecord<>(topic, key, value);
producer.send(record);
Finally, you need to call the close method after using the Producer to shut it down and release any related resources.
producer.close();
The code snippet above demonstrates how to send a message to a Topic. It can be customized as needed, such as sending multiple messages, specifying the partition for a message, adding a callback function for messages, etc.