Producer-Send-Callbacks und Acknowledgments verarbeiten
Lernen Sie, mithilfe von Callbacks, CompletableFuture und der acks-Konfiguration auf das Ergebnis asynchroner Kafka-Sends zu reagieren und eine zuverlässige Zustellung sicherzustellen.
Producer-Send-Callbacks und Acknowledgments verarbeiten ist eine kostenlose Advanced Spring Boot 4: Event-Driven Architecture (Kafka)-Lektion auf CoddyKit. Dies ist Lektion 4 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Advanced Spring Boot 4: Event-Driven Architecture (Kafka)-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Advanced Spring Boot 4: Event-Driven Architecture (Kafka)-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
Why Send Results Matter
When you call KafkaTemplate.send(), the message is dispatched asynchronously. The call returns immediately, but the broker may not have stored the record yet.
To build reliable producers you must inspect the result of each send so you can log, retry, or alert on failures.
The CompletableFuture Result
In Spring Kafka, send() returns a CompletableFuture<SendResult<K,V>>.
SendResultholds theRecordMetadata(partition, offset, timestamp).- You attach a continuation to handle success or failure.
CompletableFuture<SendResult<String,String>> future =
kafkaTemplate.send("orders", order.getId(), payload);Attaching whenComplete
Use whenComplete to handle both outcomes in one place. The first argument is the result, the second is the exception (null on success).
future.whenComplete((result, ex) -> {
if (ex == null) {
var md = result.getRecordMetadata();
log.info("Sent to partition {} offset {}", md.partition(), md.offset());
} else {
log.error("Send failed", ex);
}
});Reading RecordMetadata
On success, RecordMetadata tells you exactly where the record landed.
partition()— which partition received it.offset()— its position in that partition.timestamp()— broker-assigned timestamp.
RecordMetadata md = result.getRecordMetadata();
String location = md.topic() + "-" + md.partition() + "@" + md.offset();Blocking for the Result
Sometimes you need a synchronous guarantee. Call get() with a timeout to block until the broker acknowledges.
Use this sparingly — it kills throughput, but it is useful in tests or critical writes.
SendResult<String,String> result =
kafkaTemplate.send("orders", payload).get(10, TimeUnit.SECONDS);The acks Configuration
Acknowledgment durability is controlled by the producer acks setting:
acks=0— fire and forget, no guarantee.acks=1— leader writes, then acknowledges.acks=all— leader plus all in-sync replicas acknowledge.
Configuring acks in Spring Boot
Set the strongest durability with acks=all in your application.yml.
spring:
kafka:
producer:
acks: all
properties:
min.insync.replicas: 2Trade-off: Latency vs Durability
Stronger acks mean higher latency.
acks=0is fastest but loses data on broker failure.acks=allis safest but waits for replica confirmation.
For financial events choose all; for high-volume metrics 1 may suffice.
Centralizing Callback Logic
Avoid duplicating callback code. Wrap sends in a helper method that always logs metadata and failures consistently.
public void sendTracked(String topic, String key, String value) {
kafkaTemplate.send(topic, key, value)
.whenComplete((res, ex) -> {
if (ex != null) metrics.incrementFailures();
else metrics.incrementSuccess();
});
}Handling Failures Gracefully
In the failure branch you can:
- Persist the failed payload to a fallback store.
- Increment a failure metric for alerting.
- Schedule a retry on a separate executor.
Never swallow the exception silently.
Putting It Together
A robust producer combines acks=all, callback inspection, and failure handling. This gives you observability and delivery guarantees without blocking your main flow.
future.whenComplete((res, ex) -> {
if (ex != null) deadLetterStore.save(payload);
});Quick Check
Test your understanding of producer acknowledgments.
Recap
You learned to handle the asynchronous result of Kafka sends.
send()returns aCompletableFuture<SendResult>.- Use
whenCompleteto inspect metadata or failures. ackscontrols the durability vs latency trade-off.- Centralize callbacks for consistent reliability handling.
Lerne Advanced Spring Boot 4: Event-Driven Architecture (Kafka) mit einem KI-Tutor — kostenlos
Schreibe und führe echten Code in deinem Browser aus, bekomme sofortige Hilfe von einem 24/7 KI-Tutor und setze dein Lernen im Web oder in der App fort.
- Kurse
- 12
- Lektionen
- 48
Häufig gestellte Fragen
Ist die Lektion „Producer-Send-Callbacks und Acknowledgments verarbeiten“ kostenlos?
Ja — der vollständige Text von „Producer-Send-Callbacks und Acknowledgments verarbeiten“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Advanced Spring Boot 4: Event-Driven Architecture (Kafka)-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Advanced Spring Boot 4: Event-Driven Architecture (Kafka)-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Producer-Send-Callbacks und Acknowledgments verarbeiten“?
Lernen Sie, mithilfe von Callbacks, CompletableFuture und der acks-Konfiguration auf das Ergebnis asynchroner Kafka-Sends zu reagieren und eine zuverlässige Zustellung sicherzustellen. Du übst Advanced Spring Boot 4: Event-Driven Architecture (Kafka) mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Advanced Spring Boot 4: Event-Driven Architecture (Kafka) zu starten?
Keine Vorkenntnisse erforderlich. Advanced Spring Boot 4: Event-Driven Architecture (Kafka) auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 4 von 4.
Wie lange dauert die Lektion „Producer-Send-Callbacks und Acknowledgments verarbeiten“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Advanced Spring Boot 4: Event-Driven Architecture (Kafka)-Lektion Code schreiben und ausführen?
Ja. Jede Advanced Spring Boot 4: Event-Driven Architecture (Kafka)-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Spring Kafka Starter integrieren
- Nachrichten mit KafkaTemplate senden
- Producer-Konfigurationen anpassen
- Producer-Send-Callbacks und Acknowledgments verarbeiten