0Pricing
Advanced Spring Boot 4: Event-Driven Architecture (Kafka) · Lekcja

Obsługa callbacków wysyłania producenta i potwierdzeń

Nauczą się Państwo reagować na wynik asynchronicznego wysyłania do Kafka za pomocą callbacków, CompletableFuture i konfiguracji acks, aby zagwarantować niezawodność dostarczania.

Obsługa callbacków wysyłania producenta i potwierdzeń to bezpłatna lekcja Advanced Spring Boot 4: Event-Driven Architecture (Kafka) na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Advanced Spring Boot 4: Event-Driven Architecture (Kafka), a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Advanced Spring Boot 4: Event-Driven Architecture (Kafka) zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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.

Często zadawane pytania

Czy lekcja „Obsługa callbacków wysyłania producenta i potwierdzeń” jest bezpłatna?

Tak — pełny tekst „Obsługa callbacków wysyłania producenta i potwierdzeń” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Advanced Spring Boot 4: Event-Driven Architecture (Kafka), przejdź na CoddyKit PRO. Kurs Advanced Spring Boot 4: Event-Driven Architecture (Kafka) zawiera 4 lekcji w sumie.

Co nauczysz się w „Obsługa callbacków wysyłania producenta i potwierdzeń”?

Nauczą się Państwo reagować na wynik asynchronicznego wysyłania do Kafka za pomocą callbacków, CompletableFuture i konfiguracji acks, aby zagwarantować niezawodność dostarczania. Ćwiczysz Advanced Spring Boot 4: Event-Driven Architecture (Kafka) z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Advanced Spring Boot 4: Event-Driven Architecture (Kafka)?

Nie wymagamy żadnego doświadczenia. Advanced Spring Boot 4: Event-Driven Architecture (Kafka) w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.

Ile czasu zajmuje lekcja „Obsługa callbacków wysyłania producenta i potwierdzeń”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Advanced Spring Boot 4: Event-Driven Architecture (Kafka)?

Tak. Każda lekcja Advanced Spring Boot 4: Event-Driven Architecture (Kafka) zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Integracja Spring Kafka Starter
  2. Wysyłanie wiadomości za pomocą KafkaTemplate
  3. Dostosowywanie konfiguracji producenta
  4. Obsługa callbacków wysyłania producenta i potwierdzeń
← Powrót do Advanced Spring Boot 4: Event-Driven Architecture (Kafka)