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

Kafka 리스너 컨테이너 구축

@KafkaListener 메서드를 생성하여 지정된 토픽의 메시지를 자동으로 소비하고 해당 속성을 구성합니다.

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

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

Welcome to Kafka Consumers!

In event-driven systems, producers send events, and consumers react to them. Spring Boot makes it easy to build Kafka consumers.

We'll learn how to create methods that automatically listen for and process messages from Kafka topics using the @KafkaListener annotation.

The @KafkaListener Annotation

The @KafkaListener annotation is the core of consuming messages in Spring Boot. You place it on a method, telling Spring which Kafka topic(s) to listen to.

  • It automatically sets up the necessary infrastructure.
  • The method parameter receives the message payload.
  • You must specify a topics and groupId.

Basic Listener: String Messages

Let's create a simple Kafka listener that consumes plain string messages. Remember, you'd typically have Kafka dependencies and configuration in your Spring Boot project.

Here, my-topic is the Kafka topic, and my-group is the consumer group ID.

package com.example.kafkaconsumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

@SpringBootApplication
@EnableKafka
public class KafkaConsumerApplication {
  public static void main(String[] args) {
    // In a real app, SpringApplication.run() starts the context
    // and registers the @KafkaListener methods.
    System.out.println("Spring Boot Kafka Consumer App Started (simulated)");
    // For a runnable snippet, we just show the listener logic.
    // In a full app, this would run indefinitely, waiting for messages.
  }
}

@Component
class MyStringListener {
  @KafkaListener(topics = "my-topic", groupId = "my-group")
  public void listen(String message) {
    System.out.println("Received String: " + message);
  }
}

Understanding Consumer Groups

The groupId property is crucial for Kafka consumers. It defines a group of consumers that work together to process messages from one or more topics.

  • Load Balancing: Messages from a topic are distributed among consumers in the same group.
  • Fault Tolerance: If a consumer fails, another in the group takes over its partitions.
  • Unique Processing: Each message is processed by only one consumer within a group.

Listening to Multiple Topics

A single @KafkaListener method can listen to multiple topics. You can specify them as an array of strings in the topics attribute.

This is useful when different topics carry related types of messages that can be handled by the same logic.

package com.example.kafkaconsumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

@SpringBootApplication
@EnableKafka
public class KafkaConsumerApplication {
  public static void main(String[] args) {
    System.out.println("Spring Boot Kafka Consumer App Started (simulated)");
  }
}

@Component
class MultiTopicListener {
  @KafkaListener(topics = {"topic-a", "topic-b"}, groupId = "multi-group")
  public void listenMultipleTopics(String message) {
    System.out.println("Received from multiple topics: " + message);
  }
}

Receiving Custom Objects

Kafka messages often contain structured data, not just strings. Spring Kafka can automatically convert JSON or Avro messages into Java objects (POJOs).

You just need to define a POJO that matches the structure of your Kafka messages and use it as the method parameter.

Code: Custom Object Listener

Here's how to set up a listener for a custom MyEvent object. Spring Boot handles the deserialization, assuming you have the correct deserializer configured (e.g., JSON deserializer).

package com.example.kafkaconsumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

// A simple data class representing an event
class MyEvent {
  private String id;
  private String description;

  // Getters and setters are essential for deserialization
  public String getId() { return id; }
  public void setId(String id) { this.id = id; }
  public String getDescription() { return description; }
  public void setDescription(String description) { this.description = description; }

  @Override
  public String toString() {
    return "MyEvent{id='" + id + "', description='" + description + "'}";
  }
}

@SpringBootApplication
@EnableKafka
public class KafkaConsumerApplication {
  public static void main(String[] args) {
    System.out.println("Spring Boot Kafka Consumer App Started (simulated)");
  }
}

@Component
class MyObjectListener {
  @KafkaListener(topics = "object-topic", groupId = "object-group")
  public void listenObject(MyEvent event) {
    System.out.println("Received object: " + event);
  }
}

Accessing Message Metadata

Beyond the message payload, Kafka messages carry useful metadata like topic, partition, offset, and headers. You can access these in your listener method:

  • @Payload: The message body (default).
  • @Header: Access specific Kafka headers.
  • ConsumerRecord: The raw Kafka record, giving access to all metadata.
package com.example.kafkaconsumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

@SpringBootApplication
@EnableKafka
public class KafkaConsumerApplication {
  public static void main(String[] args) {
    System.out.println("Spring Boot Kafka Consumer App Started (simulated)");
  }
}

@Component
class MyMetadataListener {
  @KafkaListener(topics = "metadata-topic", groupId = "meta-group")
  public void listenWithMetadata(
      @Payload String message,
      @Header("kafka_receivedTopic") String topic,
      @Header("kafka_receivedPartitionId") int partition,
      @Header("kafka_offset") long offset) {
    System.out.println("Topic: " + topic + ", Partition: " + partition + ", Offset: " + offset);
    System.out.println("Message: " + message);
  }
}

Configuring Listener Properties

While @KafkaListener handles many defaults, you can customize consumer behavior. Properties like bootstrap.servers, auto.offset.reset, and key.deserializer are typically set in your application.properties or application.yml file.

  • Spring Boot automatically picks up these configurations.
  • They apply to all @KafkaListeners unless overridden.

Test Your Kafka Listener Knowledge!

Which of the following statements about Spring Boot's @KafkaListener annotation is TRUE?

Recap: Building Kafka Listeners

You've taken the first step into consuming Kafka messages with Spring Boot!

  • The @KafkaListener annotation simplifies consumer creation.
  • You specify topics and a groupId to organize consumers.
  • Listeners can handle String messages, custom objects, and access metadata.
  • Configuration is often managed through application.properties.

Next, we'll explore how consumer groups work in more detail to achieve scalable and fault-tolerant message processing!

자주 묻는 질문

“Kafka 리스너 컨테이너 구축” 강의는 무료인가요?

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

“Kafka 리스너 컨테이너 구축”에서 뭘 배우나요?

@KafkaListener 메서드를 생성하여 지정된 토픽의 메시지를 자동으로 소비하고 해당 속성을 구성합니다. 브라우저에서 직접 실행하는 실습 코드로 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개 중 1번째 강의입니다.

“Kafka 리스너 컨테이너 구축” 강의는 얼마나 걸리나요?

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

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

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

이 강의의 모든 강의

  1. Kafka 리스너 컨테이너 구축
  2. 소비자 그룹 관리
  3. 역직렬화와 메시지 변환
  4. 일괄 소비와 승인 모드
← Advanced Spring Boot 4: Event-Driven Architecture (Kafka)(으)로 돌아가기