0Pricing
Apache Kafka & Stream Processing Fundamentals · レッスン

シンプルなKafka Streamsアプリの構築

Kafkaのトピックからデータをリアルタイムに処理する、最初のKafka Streamsアプリケーションを作成します。

「シンプルなKafka Streamsアプリの構築」はCoddyKit上の無料Apache Kafka & Stream Processing Fundamentalsレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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 StreamsBuilder to define your processing topology.
  • Create a KStream from 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時間対応のAIチューター)、Apache Kafka & Stream Processing Fundamentalsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Apache Kafka & Stream Processing Fundamentalsコースには全4レッスンが含まれています。

「シンプルなKafka Streamsアプリの構築」で何を学びますか?

Kafkaのトピックからデータをリアルタイムに処理する、最初のKafka Streamsアプリケーションを作成します。 ブラウザで直接実行するハンズオンコードでApache Kafka & Stream Processing Fundamentalsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Apache Kafka & Stream Processing Fundamentalsを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのApache Kafka & Stream Processing Fundamentalsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。

「シンプルなKafka Streamsアプリの構築」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このApache Kafka & Stream Processing Fundamentalsレッスンでコードを書いて実行できますか?

はい。すべてのApache Kafka & Stream Processing Fundamentalsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. シンプルなKafka Streamsアプリの構築
  2. KStreamとKTableの概念
  3. ステートレス処理とステートフル処理
  4. Kafka StreamsのSerdesとデータシリアライゼーション
← Apache Kafka & Stream Processing Fundamentalsに戻る