Sobes.tech
Junior — Middle

Have you ever dealt with writing a Kafka Producer or created one yourself?

sobes.tech AI

Answer from AI

Yes, I have created a Kafka Producer in Java. The main task of the producer is to send messages to Kafka topics.

Here's an example of a simple Kafka Producer in Java using the org.apache.kafka.clients.producer library:

import org.apache.kafka.clients.producer.*;
import java.util.Properties;

public class SimpleProducer {
    public static void main(String[] args) {
        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<>("my-topic", "key1", "Hello Kafka");

        producer.send(record, (metadata, exception) -> {
            if (exception == null) {
                System.out.println("Message sent to partition " + metadata.partition() + " with offset " + metadata.offset());
            } else {
                exception.printStackTrace();
            }
        });

        producer.close();
    }
}

This code creates a producer, sends a single message, and closes the connection.

Have you ever dealt with writing a Kafka Producer or… - sobes.tech