Sobes.tech
Junior — Middle

What methods do you know to implement message transmission in Kafka, and what are their features?

sobes.tech AI

Answer from AI

In Java, KafkaProducer is commonly used for message transmission in Kafka. Main methods for sending messages:

  1. send(ProducerRecord<K, V> record) — asynchronous message sending. Returns a Future with the send result. Allows non-blocking, but errors should be handled via callback.

  2. send(ProducerRecord<K, V> record, Callback callback) — asynchronous sending with a callback that is invoked upon completion (success or failure).

  3. flush() — forcibly sends all accumulated messages, waiting for their acknowledgment.

  4. close() — closes the producer, sending all remaining messages.

Features:

  • Asynchronous sending increases performance but requires error handling in the callback.
  • Delivery confirmation parameters (acks) can be configured to control reliability.
  • For synchronous sending, you can call get() on the Future, but this blocks the thread.

Example of sending with a callback:

KafkaProducer<String, String> producer = new KafkaProducer<>(props);
ProducerRecord<String, String> record = new ProducerRecord<>("topic", "key", "value");

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

producer.flush();
producer.close();