0Pricing
Advanced Spring Boot 4: Event-Driven Architecture (Kafka) · Lección

Envío de mensajes con KafkaTemplate

Utilice KafkaTemplate de Spring para enviar mensajes de forma programática a topics de Kafka, tanto de manera síncrona como asíncrona.

Envío de mensajes con KafkaTemplate es una lección gratuita de Advanced Spring Boot 4: Event-Driven Architecture (Kafka) en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Advanced Spring Boot 4: Event-Driven Architecture (Kafka), y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Advanced Spring Boot 4: Event-Driven Architecture (Kafka) incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Meet Spring's KafkaTemplate

Welcome to sending messages with Spring Boot and Kafka! At the heart of sending messages is Spring's KafkaTemplate.

  • It simplifies interacting with Kafka.
  • It handles connection management and serialization.
  • It lets you send messages to any Kafka topic easily.

Think of it as your primary tool for producing events.

Injecting KafkaTemplate in Spring

To use KafkaTemplate, you simply inject it into your Spring component (like a service or controller). Spring Boot auto-configures it for you, provided you have the spring-kafka dependency.

You just need to declare it, and Spring handles the rest!

import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

@Service
public class MyProducerService {
  private final KafkaTemplate<String, String> kafkaTemplate;

  public MyProducerService(KafkaTemplate<String, String> kafkaTemplate) {
    this.kafkaTemplate = kafkaTemplate;
  }
}

Sending Your First Message

The simplest way to send a message is using the send() method. You specify the topic name and the message payload.

A topic is a category or feed name where records are stored and published. The payload is the actual data you want to send.

Basic KafkaTemplate Send Example

Here's a complete, runnable Spring Boot application that sends a simple string message to a topic named my-topic. Make sure a Kafka broker is running (e.g., on localhost:9092) for this to work.

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class KafkaProducerApp {

  public static void main(String[] args) {
    SpringApplication.run(KafkaProducerApp.class, args);
  }

  @Component
  public class MyMessageSender implements CommandLineRunner {
    private final KafkaTemplate<String, String> kafkaTemplate;

    public MyMessageSender(KafkaTemplate<String, String> kafkaTemplate) {
      this.kafkaTemplate = kafkaTemplate;
    }

    @Override
    public void run(String... args) throws Exception {
      String topic = "my-topic";
      String message = "Hello from CoddyKit!";
      kafkaTemplate.send(topic, message);
      System.out.println("Sent message: " + message + " to topic: " + topic);
    }
  }
}

Synchronous Message Sending

By default, kafkaTemplate.send() is asynchronous. However, you can make it synchronous by calling .get() on the returned ListenableFuture.

  • This blocks the current thread until the message is sent and acknowledged by Kafka.
  • Useful when you need immediate confirmation that a message was processed.
  • Can impact performance due to blocking, so use wisely.
import org.springframework.kafka.support.SendResult;
import java.util.concurrent.ExecutionException;

// ... in a service method
try {
  SendResult<String, String> result = 
    kafkaTemplate.send("sync-topic", "Sync message").get();
  System.out.println("Message sent synchronously: " + 
    result.getProducerRecord().value());
} catch (InterruptedException | ExecutionException e) {
  System.err.println("Failed to send message: " + e.getMessage());
}

Asynchronous Sending: The Preferred Way

For most applications, asynchronous sending is preferred. It allows your application to continue processing without waiting for Kafka's acknowledgment, improving throughput.

  • send() returns a ListenableFuture (or CompletableFuture in newer Spring versions).
  • You attach callbacks to this future to handle success or failure.
  • This non-blocking approach is key for scalable microservices.

Handling Asynchronous Success

To process the result of an asynchronous send, you use callbacks. The success callback receives a SendResult object, which contains details about the sent record.

This is where you'd log successful sends or update application state.

kafkaTemplate.send("async-topic", "Async message")
  .addCallback(
    result -> System.out.println("Sent successfully: " + 
      result.getProducerRecord().value()),
    ex -> System.err.println("Failed to send: " + 
      ex.getMessage())
  );

Handling Asynchronous Failure

The failure callback is crucial for robust applications. It's invoked if the message cannot be sent after retries, or if an immediate error occurs.

In this callback, you should:

  • Log the error details.
  • Implement retry logic (if not handled by Kafka config).
  • Move the message to a Dead Letter Topic (DLT) for later inspection.

Async Send with Callbacks Example

Let's update our previous example to use asynchronous sending with success and failure callbacks. This demonstrates a more robust way to send messages.

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class KafkaAsyncProducerApp {

  public static void main(String[] args) {
    SpringApplication.run(KafkaAsyncProducerApp.class, args);
  }

  @Component
  public class MyAsyncMessageSender implements CommandLineRunner {
    private final KafkaTemplate<String, String> kafkaTemplate;

    public MyAsyncMessageSender(KafkaTemplate<String, String> kafkaTemplate) {
      this.kafkaTemplate = kafkaTemplate;
    }

    @Override
    public void run(String... args) throws Exception {
      String topic = "my-async-topic";
      String message = "Hello async from CoddyKit!";

      kafkaTemplate.send(topic, message)
        .addCallback(
          result -> System.out.println("Async success: " + result.getProducerRecord().value()),
          ex -> System.err.println("Async failure: " + ex.getMessage())
        );
      System.out.println("Attempted to send async message.");
    }
  }
}

Sending with Keys for Ordering

Kafka allows you to send messages with a key. The key is used to determine which partition a message goes to.

  • Messages with the same key always go to the same partition.
  • This ensures ordering for related messages (e.g., all updates for a specific user).
  • Use kafkaTemplate.send(topic, key, message).
kafkaTemplate.send("user-events", "user-123", "User 123 updated profile");
kafkaTemplate.send("user-events", "user-456", "User 456 logged in");

KafkaTemplate Question

Which of the following statements about KafkaTemplate.send() and its return type is TRUE?

Recap: Sending Messages

Great job! You've learned the essentials of sending messages with Spring Boot's KafkaTemplate:

  • Injection: How to get KafkaTemplate in your services.
  • Basic Send: Using send(topic, message).
  • Synchronous: Blocking with .get() for immediate confirmation.
  • Asynchronous: The preferred method using ListenableFuture and callbacks for efficiency.
  • Keys: How to use message keys for ordering and partitioning.

Next, we'll dive into customizing producer configurations for optimized performance and reliability!

Preguntas frecuentes

¿La lección «Envío de mensajes con KafkaTemplate» es gratis?

Sí — el texto completo de «Envío de mensajes con KafkaTemplate» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Advanced Spring Boot 4: Event-Driven Architecture (Kafka), actualiza a CoddyKit PRO. El curso de Advanced Spring Boot 4: Event-Driven Architecture (Kafka) incluye 4 lecciones en total.

¿Qué aprenderé en «Envío de mensajes con KafkaTemplate»?

Utilice KafkaTemplate de Spring para enviar mensajes de forma programática a topics de Kafka, tanto de manera síncrona como asíncrona. Practicas Advanced Spring Boot 4: Event-Driven Architecture (Kafka) con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Advanced Spring Boot 4: Event-Driven Architecture (Kafka)?

No se requiere experiencia previa. Advanced Spring Boot 4: Event-Driven Architecture (Kafka) en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.

¿Cuánto tiempo toma la lección «Envío de mensajes con KafkaTemplate»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Advanced Spring Boot 4: Event-Driven Architecture (Kafka)?

Sí. Cada lección de Advanced Spring Boot 4: Event-Driven Architecture (Kafka) incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Integración de Spring Kafka Starter
  2. Envío de mensajes con KafkaTemplate
  3. Personalización de la configuración de productores
  4. Gestión de callbacks de envío y confirmaciones del productor
← Volver a Advanced Spring Boot 4: Event-Driven Architecture (Kafka)