การสร้างคอนเทนเนอร์ตัวรับฟัง Kafka
สร้างเมธอด @KafkaListener เพื่อรับข้อความจากท็อปปิกที่ระบุโดยอัตโนมัติ และกำหนดค่าคุณสมบัติของเมธอด
การสร้างคอนเทนเนอร์ตัวรับฟัง Kafka เป็นบทเรียน Advanced Spring Boot 4: Event-Driven Architecture (Kafka) ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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
topicsandgroupId.
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
@KafkaListenerannotation simplifies consumer creation. - You specify topics and a
groupIdto 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” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Advanced Spring Boot 4: Event-Driven Architecture (Kafka) ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Advanced Spring Boot 4: Event-Driven Architecture (Kafka) มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การสร้างคอนเทนเนอร์ตัวรับฟัง Kafka”
สร้างเมธอด @KafkaListener เพื่อรับข้อความจากท็อปปิกที่ระบุโดยอัตโนมัติ และกำหนดค่าคุณสมบัติของเมธอด คุณปฏิบัติ Advanced Spring Boot 4: Event-Driven Architecture (Kafka) ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Advanced Spring Boot 4: Event-Driven Architecture (Kafka) หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Advanced Spring Boot 4: Event-Driven Architecture (Kafka) บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “การสร้างคอนเทนเนอร์ตัวรับฟัง Kafka” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Advanced Spring Boot 4: Event-Driven Architecture (Kafka) นี้ได้ไหม
ได้ บทเรียน Advanced Spring Boot 4: Event-Driven Architecture (Kafka) ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การสร้างคอนเทนเนอร์ตัวรับฟัง Kafka
- การจัดการกลุ่มผู้บริโภค
- การแปลงข้อมูลกลับและการแปลงข้อความ
- การรับข้อมูลเป็นชุดและโหมดการยืนยัน