SpringSpring Kafka Basics
How do you produce messages with KafkaTemplate?
Reference answer
Inject KafkaTemplate<K,V> into your bean; Spring Boot auto-configures it. Methods: send(topic, data) sends without a key; send(topic, key, data) sends with a key; send(topic, partition, key, data) picks the partition; send(new ProducerRecord<>(...)) gives full control, including headers; send(Message) takes the topic, key and partition from message headers; the sendDefault variants use the template's default topic. Since Spring Kafka 3.0, send() returns CompletableFuture<SendResult<K,V>> (earlier versions returned ListenableFuture). Handle the result asynchronously with whenComplete((result, ex) -> ...), or block with get(timeout, unit); on failure the Throwable is a KafkaProducerException whose producerRecord property holds the failed record. SendResult holds the ProducerRecord and the RecordMetadata. By default DefaultKafkaProducerFactory creates one producer shared by all users of the factory. For JSON set spring.kafka.producer.value-serializer to JacksonJsonSerializer (JsonSerializer before Spring Kafka 4.0).
Expected key concepts: KafkaTemplate, send, ProducerRecord, CompletableFuture, SendResult, whenComplete, KafkaProducerException, JacksonJsonSerializer, auto-configures, partition, key
How did that feel?
Your own verdict, not the score. It shows up next to this question in the list, so you can come back to the shaky ones.