Java Kafka Producer Example: Send Messages to a Topic
To send a message to Kafka in Java, you can use the 'KafkaProducer' class from the Kafka Clients library. Here is an example code snippet:
import org.apache.kafka.clients.producer.*;
import java.util.Properties;
public class KafkaProducerExample {
public static void main(String[] args) {
// set up the producer properties
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');
// create a KafkaProducer instance
Producer<String, String> producer = new KafkaProducer<>(props);
// create a message to send
String topic = 'my-topic';
String key = 'my-key';
String value = 'Hello, Kafka!';
// create a ProducerRecord instance with the topic, key, and value
ProducerRecord<String, String> record = new ProducerRecord<>(topic, key, value);
// send the message
producer.send(record);
// close the producer
producer.close();
}
}
In this example, we first set up the producer properties, including the Kafka broker address, key and value serializers. Then, we create a 'KafkaProducer' instance with these properties. Next, we create a message to send, consisting of a topic, key, and value. We use these to create a 'ProducerRecord' instance. Finally, we call the 'send()' method on the producer instance to send the message, and close the producer.
原文地址: https://www.cveoy.top/t/topic/nEFE 著作权归作者所有。请勿转载和采集!