간단한 Kafka Streams 앱 구축
Kafka 토픽의 데이터를 실시간으로 처리하는 첫 Kafka Streams 애플리케이션을 만듭니다.
간단한 Kafka Streams 앱 구축은(는) CoddyKit의 무료 Apache Kafka & Stream Processing Fundamentals 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Apache Kafka & Stream Processing Fundamentals 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Apache Kafka & Stream Processing Fundamentals 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Welcome to Kafka Streams!
Ready to build real-time data processing apps? Kafka Streams is a client library for building applications and microservices that process data stored in Kafka.
It lets you write standard Java/Scala applications that leverage Kafka's power for stream processing. Think of it as a toolkit to transform, filter, and analyze data as it flows through Kafka.
The Power of Kafka Streams
Kafka Streams offers several key advantages for your real-time applications:
- Lightweight: It's just a library, no separate cluster needed.
- Fault-Tolerant: Automatically handles failures and data recovery.
- Scalable: Easily scales by adding more instances of your application.
- Exactly-Once Processing: Guarantees data is processed once, even with failures.
It's great for real-time analytics, data transformations, and event-driven microservices.
Setting Up Your Project
To start, you'll need to add the Kafka Streams library to your project. If you're using Maven, add this dependency to your pom.xml:
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-streams</artifactId>
<version>3.5.1</version>
</dependency>Core Component: StreamsBuilder
The StreamsBuilder is your main entry point for defining the stream processing topology. Think of it as the architect for your data flow.
You use it to create source streams, apply transformations, and define where the processed data should go. Here's how you'd create one:
import org.apache.kafka.streams.StreamsBuilder;
public class Main {
public static void main(String[] args) {
StreamsBuilder builder = new StreamsBuilder();
// Your stream processing logic will go here
System.out.println("StreamsBuilder created!");
}
}KStream: Records in Motion
A KStream represents an unbounded, continuously updating stream of key-value records. Each record is processed independently as it arrives.
You can create a KStream from a Kafka topic using the stream() method of your StreamsBuilder. This tells your app to start consuming messages from that topic.
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.KStream;
public class Main {
public static void main(String[] args) {
StreamsBuilder builder = new StreamsBuilder();
KStream<String, String> sourceStream =
builder.stream("input-topic");
System.out.println("KStream created from input-topic!");
}
}Simple Transformation: mapValues
One common operation is to transform the value of each record in a KStream. The mapValues() method is perfect for this.
It applies a function to each record's value, keeping the key unchanged. Let's write code to make all text values uppercase!
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.KStream;
public class Main {
public static void main(String[] args) {
StreamsBuilder builder = new StreamsBuilder();
KStream<String, String> sourceStream =
builder.stream("input-topic");
KStream<String, String> transformedStream =
sourceStream.mapValues(value -> value.toUpperCase());
System.out.println("Stream values will be uppercased!");
}
}Essential Stream Configuration
Before running your app, you need to configure it. This is done using a Properties object and StreamsConfig. Key settings include:
APPLICATION_ID_CONFIG: Unique ID for your app (like a consumer group).BOOTSTRAP_SERVERS_CONFIG: Your Kafka broker addresses.DEFAULT_KEY_SERDE_CLASS_CONFIG: How to serialize/deserialize keys.DEFAULT_VALUE_SERDE_CLASS_CONFIG: How to serialize/deserialize values.
Serdes (Serializer/Deserializer) are crucial for converting data to/from bytes.
Your First Kafka Streams App
Let's put everything together! This app will read messages from an 'input-topic', convert their values to uppercase, and then write the results to an 'output-topic'.
Remember to create these topics in your Kafka cluster before running this code!
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 UppercaseStreamApp {
public static void main(String[] args) {
Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "uppercase-app");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
StreamsBuilder builder = new StreamsBuilder();
KStream<String, String> sourceStream = builder.stream("input-topic");
KStream<String, String> transformedStream =
sourceStream.mapValues(value -> value.toUpperCase());
transformedStream.to("output-topic");
KafkaStreams streams = new KafkaStreams(builder.build(), props);
// Clean up local state on shutdown (for development)
streams.cleanUp();
streams.start();
// Add shutdown hook to close Kafka Streams cleanly
Runtime.getRuntime().addShutdownHook(new Thread(streams::close));
System.out.println("UppercaseStreamApp started!");
}
}Managing Your Stream App
After defining your topology and configuration, you create a KafkaStreams instance and call start() to begin processing.
It's crucial to add a shutdown hook (Runtime.getRuntime().addShutdownHook) to ensure your application closes gracefully, flushing any buffered data and releasing resources.
The streams.cleanUp() call is useful during development to clear any local state store data, but should generally be avoided in production.
Test Your Knowledge
Which of the following is NOT a core component or essential configuration for a basic Kafka Streams application?
Recap: Your First Stream App
Great job! You've successfully learned the fundamentals of building a simple Kafka Streams application.
You now understand how to:
- Add the necessary Kafka Streams dependency.
- Use
StreamsBuilderto define your processing topology. - Create a
KStreamfrom an input topic. - Apply simple transformations like
mapValues(). - Configure your application with
StreamsConfig. - Start and gracefully stop your Kafka Streams application.
Next, we'll dive deeper into KStream and KTable concepts!
자주 묻는 질문
“간단한 Kafka Streams 앱 구축” 강의는 무료인가요?
네 — “간단한 Kafka Streams 앱 구축” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Apache Kafka & Stream Processing Fundamentals 강의 전체를 잠금 해제할 수 있습니다. Apache Kafka & Stream Processing Fundamentals 강의에는 총 4개의 강의가 포함되어 있습니다.
“간단한 Kafka Streams 앱 구축”에서 뭘 배우나요?
Kafka 토픽의 데이터를 실시간으로 처리하는 첫 Kafka Streams 애플리케이션을 만듭니다. 브라우저에서 직접 실행하는 실습 코드로 Apache Kafka & Stream Processing Fundamentals을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Apache Kafka & Stream Processing Fundamentals을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Apache Kafka & Stream Processing Fundamentals은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“간단한 Kafka Streams 앱 구축” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Apache Kafka & Stream Processing Fundamentals 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Apache Kafka & Stream Processing Fundamentals 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 간단한 Kafka Streams 앱 구축
- KStream 및 KTable 개념
- 무상태 연산과 상태 유지 연산
- Kafka Streams의 Serdes와 데이터 직렬화