KStream 및 KTable 개념
Kafka Streams에서 레코드 단위 스트림인 KStream과 구체화된 뷰를 나타내는 변경 로그 스트림인 KTable의 차이를 구분합니다.
KStream 및 KTable 개념은(는) CoddyKit의 무료 Apache Kafka & Stream Processing Fundamentals 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Apache Kafka & Stream Processing Fundamentals 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Apache Kafka & Stream Processing Fundamentals 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
KStream & KTable Unveiled
In Kafka Streams, KStream and KTable are fundamental data abstractions. They represent different ways to view and process your data.
Understanding their differences is key to building powerful, real-time stream processing applications.
KStream: A Stream of Events
A KStream represents an unbounded, immutable sequence of data records. Think of it like a traditional log or event stream.
- Each record is treated as a distinct, independent event.
- Records are processed one by one, in the order they arrive.
- It never "updates" a previous record; new records are always additions.
It's perfect for handling events like clicks, sensor readings, or financial transactions.
KStream in Action: Filtering
Here's a simple Kafka Streams application that uses a KStream to filter messages. It processes each record individually.
This example will filter a stream of text messages, keeping only those that contain the word "event".
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 KStreamFilter {
public static void main(String[] args) {
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "kstream-filter-app");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_BY_KEY_CLASS_CONFIG, Serdes.String().getClass());
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_BY_KEY_CLASS_CONFIG, 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("event"));
filteredStream.to("output-topic");
KafkaStreams streams = new KafkaStreams(builder.build(), props);
System.out.println("KStream filter topology created.");
System.out.println("It filters messages containing 'event'.");
// In a real application, you would call streams.start();
// and manage its lifecycle, e.g., using a shutdown hook.
}
}KTable: A Dynamic View
A KTable represents a changelog stream, where each record signifies an update or deletion to a row in a table. It's like a database table that's constantly being updated.
- Each record's value is considered the "latest" value for its key.
- When a new record arrives with an existing key, it overwrites the previous value.
- Perfect for maintaining the current state of data.
Think of user profiles, stock prices, or current inventory levels.
KTable in Action: Latest State
This example demonstrates a KTable maintaining the latest value for each key. Imagine tracking the most recent status for various sensors.
When a new message arrives for a sensor, its status in the KTable is updated to the new value.
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.KTable;
import org.apache.kafka.streams.kstream.Materialized;
import java.util.Properties;
public class KTableLatestState {
public static void main(String[] args) {
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "ktable-latest-state-app");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_BY_KEY_CLASS_CONFIG, Serdes.String().getClass());
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_BY_KEY_CLASS_CONFIG, Serdes.String().getClass());
StreamsBuilder builder = new StreamsBuilder();
KTable<String, String> latestStatusTable = builder
.table("sensor-updates", Materialized.as("latest-sensor-status"));
// The KTable is defined. In a real app, you might print
// its contents to another topic or join it with a KStream.
// latestStatusTable.toStream().to("latest-status-output-topic");
KafkaStreams streams = new KafkaStreams(builder.build(), props);
System.out.println("KTable latest state topology created.");
System.out.println("It tracks the most recent status for each sensor.");
}
}KStream vs. KTable: Key Differences
While both process data, their fundamental nature differs significantly:
- KStream: Each record is an event. It's a sequence of facts. "Something happened."
- KTable: Each record is an update. It represents the current state. "This is the current value."
Think of KStream as a transaction log and KTable as the current balance sheet.
When to Use KStream
KStreams are ideal when you need to react to individual events or process data without maintaining a long-term state based on keys.
- Event logging: Storing every user action.
- Real-time alerts: Notifying immediately when a specific event occurs.
- Data enrichment (stateless): Adding information to each event based on its content.
- Filtering and mapping: Transforming events one by one.
When to Use KTable
KTables are perfect for applications that need to maintain and query the latest state of data, often for aggregations or joins.
- Current inventory: Tracking stock levels for products.
- User profiles: Storing the most recent profile details.
- Aggregations: Counting unique users, summing sales over time (when aggregated results are stored as a KTable).
- Joining streams with tables: Enriching a KStream with current KTable data.
From Stream to Table: Aggregation
You can transform a KStream into a KTable using stateful operations like aggregation. This converts a series of events into a continuously updated state.
For example, counting occurrences of words from a stream of sentences will result in a KTable where the key is the word and the value is its current count.
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 org.apache.kafka.streams.kstream.Produced;
import java.util.Arrays;
import java.util.Properties;
public class KStreamToKTable {
public static void main(String[] args) {
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "word-count-app");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_BY_KEY_CLASS_CONFIG, Serdes.String().getClass());
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_BY_KEY_CLASS_CONFIG, Serdes.String().getClass());
StreamsBuilder builder = new StreamsBuilder();
KStream<String, String> textLines = builder.stream("text-input");
KTable<String, Long> wordCounts = textLines
.flatMapValues(value -> Arrays.asList(value.toLowerCase().split("\\W+")))
.groupBy((key, word) -> word)
.count(Materialized.as("counts-store"));
wordCounts.toStream().to("word-counts-output", Produced.with(Serdes.String(), Serdes.Long()));
KafkaStreams streams = new KafkaStreams(builder.build(), props);
System.out.println("KStream to KTable topology created (Word Count).");
System.out.println("Counts words from 'text-input' and stores counts in a KTable.");
}
}KStream vs. KTable Quiz
Which of the following statements accurately describe a KTable?
KStream & KTable Recap
You've learned the core differences between KStream and KTable in Kafka Streams!
- KStream: An event stream, processing individual, immutable records.
- KTable: A changelog stream representing a materialized, updatable view of data.
Choosing the right abstraction is crucial for efficient and meaningful real-time data processing. Next, we'll explore stateless vs. stateful operations in Kafka Streams.
자주 묻는 질문
“KStream 및 KTable 개념” 강의는 무료인가요?
네 — “KStream 및 KTable 개념” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Apache Kafka & Stream Processing Fundamentals 강의 전체를 잠금 해제할 수 있습니다. Apache Kafka & Stream Processing Fundamentals 강의에는 총 4개의 강의가 포함되어 있습니다.
“KStream 및 KTable 개념”에서 뭘 배우나요?
Kafka Streams에서 레코드 단위 스트림인 KStream과 구체화된 뷰를 나타내는 변경 로그 스트림인 KTable의 차이를 구분합니다. 브라우저에서 직접 실행하는 실습 코드로 Apache Kafka & Stream Processing Fundamentals을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Apache Kafka & Stream Processing Fundamentals을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Apache Kafka & Stream Processing Fundamentals은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“KStream 및 KTable 개념” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Apache Kafka & Stream Processing Fundamentals 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Apache Kafka & Stream Processing Fundamentals 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 간단한 Kafka Streams 앱 구축
- KStream 및 KTable 개념
- 무상태 연산과 상태 유지 연산
- Kafka Streams의 Serdes와 데이터 직렬화