0Pricing
Advanced Spring Boot 4: Event-Driven Architecture (Kafka) · درس

معالجة دوال استدعاء الإرسال وإقرارات المنتج

تعلّم الاستجابة لنتيجة عمليات إرسال Kafka غير المتزامنة باستخدام دوال الاستدعاء وCompletableFuture وإعداد acks لضمان موثوقية التسليم.

معالجة دوال استدعاء الإرسال وإقرارات المنتج درس مجاني في Advanced Spring Boot 4: Event-Driven Architecture (Kafka) على CoddyKit. هذا هو الدرس 4 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في 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>>.

  • SendResult holds the RecordMetadata (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: 2

Trade-off: Latency vs Durability

Stronger acks mean higher latency.

  • acks=0 is fastest but loses data on broker failure.
  • acks=all is 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 a CompletableFuture<SendResult>.
  • Use whenComplete to inspect metadata or failures.
  • acks controls the durability vs latency trade-off.
  • Centralize callbacks for consistent reliability handling.

الأسئلة الشائعة

هل درس «معالجة دوال استدعاء الإرسال وإقرارات المنتج» مجاني؟

نعم — نص درس «معالجة دوال استدعاء الإرسال وإقرارات المنتج» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Advanced Spring Boot 4: Event-Driven Architecture (Kafka)، انتقل إلى CoddyKit PRO. تتضمن دورة Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 4 دروس في المجموع.

ماذا ستتعلم في «معالجة دوال استدعاء الإرسال وإقرارات المنتج»؟

تعلّم الاستجابة لنتيجة عمليات إرسال Kafka غير المتزامنة باستخدام دوال الاستدعاء وCompletableFuture وإعداد acks لضمان موثوقية التسليم. تتمرن على Advanced Spring Boot 4: Event-Driven Architecture (Kafka) مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Advanced Spring Boot 4: Event-Driven Architecture (Kafka)؟

لا تُشترط خبرة سابقة. Advanced Spring Boot 4: Event-Driven Architecture (Kafka) على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 4 من أصل 4.

كم من الوقت يستغرق درس «معالجة دوال استدعاء الإرسال وإقرارات المنتج»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Advanced Spring Boot 4: Event-Driven Architecture (Kafka) هذا؟

نعم. كل درس في Advanced Spring Boot 4: Event-Driven Architecture (Kafka) يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. دمج Spring Kafka Starter
  2. إرسال الرسائل باستخدام KafkaTemplate
  3. تخصيص إعدادات المنتج
  4. معالجة دوال استدعاء الإرسال وإقرارات المنتج
← العودة إلى Advanced Spring Boot 4: Event-Driven Architecture (Kafka)