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

KafkaTemplate으로 메시지 전송

Spring의 KafkaTemplate을 사용하여 Kafka 토픽으로 메시지를 프로그래밍 방식으로 전송합니다. 동기 방식과 비동기 방식 모두 다룹니다.

KafkaTemplate으로 메시지 전송은(는) CoddyKit의 무료 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

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!

자주 묻는 질문

“KafkaTemplate으로 메시지 전송” 강의는 무료인가요?

네 — “KafkaTemplate으로 메시지 전송” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 강의 전체를 잠금 해제할 수 있습니다. Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 강의에는 총 4개의 강의가 포함되어 있습니다.

“KafkaTemplate으로 메시지 전송”에서 뭘 배우나요?

Spring의 KafkaTemplate을 사용하여 Kafka 토픽으로 메시지를 프로그래밍 방식으로 전송합니다. 동기 방식과 비동기 방식 모두 다룹니다. 브라우저에서 직접 실행하는 실습 코드로 Advanced Spring Boot 4: Event-Driven Architecture (Kafka)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Advanced Spring Boot 4: Event-Driven Architecture (Kafka)을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Advanced Spring Boot 4: Event-Driven Architecture (Kafka)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“KafkaTemplate으로 메시지 전송” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Advanced Spring Boot 4: Event-Driven Architecture (Kafka) 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Spring Kafka Starter 통합
  2. KafkaTemplate으로 메시지 전송
  3. 생산자 구성 사용자 지정
  4. 생산자 전송 콜백과 승인 처리
← Advanced Spring Boot 4: Event-Driven Architecture (Kafka)(으)로 돌아가기