处理生产者发送回调与确认
学习如何使用回调、CompletableFuture 和确认配置响应异步 Kafka 发送的结果,确保可靠交付。
处理生产者发送回调与确认 是 CoddyKit 上的免费 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
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.
常见问题解答
「处理生产者发送回调与确认」课时是免费的吗?
是的 — 「处理生产者发送回调与确认」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课程的其余内容,请升级到 CoddyKit PRO。 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课程共包含 4 节课。
「处理生产者发送回调与确认」这节课中我会学到什么?
学习如何使用回调、CompletableFuture 和确认配置响应异步 Kafka 发送的结果,确保可靠交付。 你通过在浏览器中直接运行的动手代码来练习 Advanced Spring Boot 4: Event-Driven Architecture (Kafka),全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「处理生产者发送回调与确认」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课中编写并运行代码吗?
能。每节 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。