0Pricing
Advanced Spring Boot 4: Event-Driven Architecture (Kafka) · บทเรียน

การประมวลผลสตรีมด้วย KStream และ KTable

เรียนรู้การใช้ KStream สำหรับสตรีมเหตุการณ์ที่เปลี่ยนแปลงไม่ได้ และ KTable สำหรับมุมมองข้อมูลที่มีสถานะและอัปเดตได้ พร้อมดำเนินการต่าง ๆ เช่น การกรองและการแมปข้อมูล

การประมวลผลสตรีมด้วย KStream และ KTable เป็นบทเรียน Advanced Spring Boot 4: Event-Driven Architecture (Kafka) ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Advanced Spring Boot 4: Event-Driven Architecture (Kafka) และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Advanced Spring Boot 4: Event-Driven Architecture (Kafka) มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

KStream & KTable Unveiled

Welcome! In Kafka Streams, KStream and KTable are your primary tools for processing data. They represent different views of your data in motion.

Think of them as two sides of the same coin, each suited for distinct stream processing tasks. Understanding their differences is key to building powerful stream applications.

KStream: Immutable Events

A KStream represents an infinite, immutable sequence of events. Each record in a KStream is a self-contained fact, an independent event that happened at a specific point in time.

  • It's like a transaction log: once an event is added, it's never changed.
  • Operations on a KStream produce new KStreams, leaving the original untouched.
  • It's ideal for processing individual events like clicks, sensor readings, or log entries.

Filtering KStream Events

One common KStream operation is filtering. You can selectively keep records that match certain criteria, creating a new KStream with only the relevant events.

Here's a simple example filtering messages that contain 'hello'.

import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStream;

import java.util.Properties;

public class Main {
    public static void main(String[] args) {
        Properties props = new Properties();
        props.put(StreamsConfig.APPLICATION_ID_CONFIG, "filter-app");
        props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_BY_DEFAULT, Serdes.String().getClass());
        props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_BY_DEFAULT, Serdes.String().getClass());

        StreamsBuilder builder = new StreamsBuilder();
        KStream<String, String> sourceStream = builder.stream("input-topic");

        KStream<String, String> filteredStream = sourceStream.filter(
            (key, value) -> value.contains("hello")
        );

        filteredStream.to("output-topic");

        KafkaStreams streams = new KafkaStreams(builder.build(), props);
        // In a real app, you'd start and manage this lifecycle:
        // streams.start();
        // Runtime.getRuntime().addShutdownHook(new Thread(streams::close));
        System.out.println("KStream filter setup complete. Send 'hello world' to input-topic!");
    }
}

Transforming KStream Values

The mapValues operation transforms the value of each record in a KStream, producing a new KStream with the modified values. The key remains unchanged.

This is useful for cleaning data, changing formats, or enriching information without altering the message's key.

import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStream;

import java.util.Properties;

public class Main {
    public static void main(String[] args) {
        Properties props = new Properties();
        props.put(StreamsConfig.APPLICATION_ID_CONFIG, "mapvalues-app");
        props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_BY_DEFAULT, Serdes.String().getClass());
        props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_BY_DEFAULT, Serdes.String().getClass());

        StreamsBuilder builder = new StreamsBuilder();
        KStream<String, String> sourceStream = builder.stream("input-topic");

        KStream<String, String> uppercasedStream = sourceStream.mapValues(
            value -> value.toUpperCase()
        );

        uppercasedStream.to("output-topic");

        KafkaStreams streams = new KafkaStreams(builder.build(), props);
        System.out.println("KStream mapValues setup complete. Send 'test' to input-topic!");
    }
}

KTable: A Materialized View

A KTable represents a changelog stream, where each record is an update to a specific key. It's essentially a materialized view of a table, reflecting the latest state for each key.

  • It's like a database table: keys have associated values, and new records for a key overwrite previous ones.
  • KTable is stateful, maintaining the latest value for each key over time.
  • It's perfect for aggregating data, maintaining counts, or storing user profiles.

KTable's Stateful Nature

The core idea behind a KTable is that it keeps track of the latest value for each unique key. When a new record with an existing key arrives, the KTable updates its internal state.

This makes KTable ideal for scenarios where you care about the current state of an entity, rather than every single event that led to that state.

KStream to KTable: Counting

You can transform a KStream into a KTable, typically to perform aggregations. A common example is counting occurrences of keys using groupByKey().count().

Each time a message arrives, the count for its key is updated, and the KTable emits the new total.

import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.KTable;
import org.apache.kafka.streams.kstream.Materialized;

import java.util.Properties;

public class Main {
    public static void main(String[] args) {
        Properties props = new Properties();
        props.put(StreamsConfig.APPLICATION_ID_CONFIG, "kstream-to-ktable-app");
        props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_BY_DEFAULT, Serdes.String().getClass());
        props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_BY_DEFAULT, Serdes.String().getClass());

        StreamsBuilder builder = new StreamsBuilder();
        KStream<String, String> sourceStream = builder.stream("input-topic");

        KTable<String, Long> wordCounts = sourceStream
            .groupByKey() // Group by the existing key
            .count(Materialized.as("counts-store")); // Count occurrences, store in state

        wordCounts.toStream().to("output-topic"); // Convert back to stream to send out

        KafkaStreams streams = new KafkaStreams(builder.build(), props);
        System.out.println("KStream to KTable count setup. Send 'word' with key 'A' to input-topic!");
    }
}

KTable for Aggregation

KTables are excellent for continuous aggregation. Beyond simple counts, you can use operations like aggregate to maintain sums, averages, or custom aggregates over time.

This allows your application to always have an up-to-date summary of data for specific keys.

When to Use Which?

The choice between KStream and KTable depends on your processing needs:

  • Use KStream when you need to process individual events, react to every occurrence, or build a pipeline of transformations that don't depend on historical state. Think real-time alerts or event logging.
  • Use KTable when you need to maintain a current state, aggregate data over time, or join with other data sources based on the latest value. Think user profiles, stock prices, or aggregated metrics.

KStream vs. KTable Check

You've learned about KStream and KTable. Let's test your understanding.

KStream & KTable Recap

Great job! You've explored the core differences and uses of KStream and KTable.

  • KStream handles individual, immutable events, perfect for event-by-event processing.
  • KTable maintains a materialized view, tracking the latest state for each key, ideal for aggregations and stateful processing.

These two primitives are the foundation for building powerful and flexible stream processing applications with Kafka Streams.

คำถามที่พบบ่อย

บทเรียน “การประมวลผลสตรีมด้วย KStream และ KTable” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การประมวลผลสตรีมด้วย KStream และ KTable” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Advanced Spring Boot 4: Event-Driven Architecture (Kafka) ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Advanced Spring Boot 4: Event-Driven Architecture (Kafka) มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การประมวลผลสตรีมด้วย KStream และ KTable”

เรียนรู้การใช้ KStream สำหรับสตรีมเหตุการณ์ที่เปลี่ยนแปลงไม่ได้ และ KTable สำหรับมุมมองข้อมูลที่มีสถานะและอัปเดตได้ พร้อมดำเนินการต่าง ๆ เช่น การกรองและการแมปข้อมูล คุณปฏิบัติ 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 ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “การประมวลผลสตรีมด้วย KStream และ KTable” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Advanced Spring Boot 4: Event-Driven Architecture (Kafka) นี้ได้ไหม

ได้ บทเรียน Advanced Spring Boot 4: Event-Driven Architecture (Kafka) ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. บทนำสู่ Kafka Streams
  2. การประมวลผลสตรีมด้วย KStream และ KTable
  3. การสร้างแอปพลิเคชันสตรีมอย่างง่าย
  4. การแบ่งช่วงเวลาและการรวมข้อมูลแบบมีสถานะใน Kafka Streams
← กลับไปที่ Advanced Spring Boot 4: Event-Driven Architecture (Kafka)