Создание простого потокового приложения
Разработайте базовое приложение Spring Boot, использующее Kafka Streams для обработки и преобразования событий в реальном времени.
«Создание простого потокового приложения» — бесплатный урок Advanced Spring Boot 4: Event-Driven Architecture (Kafka) на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Advanced Spring Boot 4: Event-Driven Architecture (Kafka), и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Advanced Spring Boot 4: Event-Driven Architecture (Kafka) содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Your First Stream App
Welcome! In this lesson, we'll build a basic Spring Boot application that uses Kafka Streams to process events in real-time.
Our goal is simple: read messages from one Kafka topic, transform them, and write the results to another topic.
Spring Boot Project Setup
To begin, create a new Spring Boot project using Spring Initializr (start.spring.io).
Make sure to include these dependencies:
- Spring Web (for a web context, though not strictly needed for streams)
- Spring for Apache Kafka
- Kafka Streams
Essential Stream Properties
Kafka Streams applications need some core properties to function. These are typically set in your application.properties or as a @Bean.
Key properties include:
application.id: A unique ID for your stream application.bootstrap.servers: The Kafka broker addresses.default.key.serde: Serializer/Deserializer for message keys.default.value.serde: Serializer/Deserializer for message values.
Activating Stream Processing
For Spring Boot to recognize and manage your Kafka Streams application, you need to annotate your main application class with @EnableKafkaStreams.
This annotation tells Spring to look for stream topology definitions and manage their lifecycle.
package com.coddykit.kafka.streams;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.kafka.annotation.EnableKafkaStreams;
@SpringBootApplication
@EnableKafkaStreams // This enables Kafka Streams
public class SimpleStreamApplication {
public static void main(String[] args) {
SpringApplication.run(SimpleStreamApplication.class, args);
}
}Kafka Streams Configuration Bean
You can define a @Bean of type KafkaStreamsConfiguration to configure your stream application. This is often preferred over application.properties for more complex setups.
Here, we set essential properties like the application ID and Kafka broker address:
package com.coddykit.kafka.streams;
import org.apache.kafka.common.serialization.Serdes;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.KafkaStreamsDefaultConfiguration;
import org.springframework.kafka.config.KafkaStreamsConfiguration;
import java.util.HashMap;
import java.util.Map;
import static org.apache.kafka.streams.StreamsConfig.*;
@Configuration
public class KafkaStreamsConfig {
@Bean(name = KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME)
public KafkaStreamsConfiguration kStreamsConfigs() {
Map<String, Object> props = new HashMap<>();
props.put(APPLICATION_ID_CONFIG, "my-uppercase-app");
props.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
props.put(DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
return new KafkaStreamsConfiguration(props);
}
}Building Your Stream Topology
The StreamsBuilder is your primary tool for defining the processing logic, or 'topology', of your Kafka Streams application.
Spring automatically injects an instance of StreamsBuilder into any @Bean method that defines your stream topology.
Defining the Stream Source
To start processing, you need to define where your stream gets its data. This is done by creating a KStream from an input topic.
The stream() method of StreamsBuilder does exactly this:
KStream<String, String> stream = kStreamBuilder.stream("input-topic");Here, we're reading messages with String keys and String values from input-topic.
Transforming and Sending Data
Once you have a KStream, you can apply various transformations. For our simple app, we'll convert message values to uppercase using mapValues().
Finally, we'll send the transformed messages to an output-topic using the to() method. Try running this example!
package com.coddykit.kafka.streams;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.KStream;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.EnableKafkaStreams;
import org.springframework.kafka.annotation.KafkaStreamsDefaultConfiguration;
import org.springframework.kafka.config.KafkaStreamsConfiguration;
import java.util.HashMap;
import java.util.Map;
import static org.apache.kafka.streams.StreamsConfig.*;
@SpringBootApplication
@EnableKafkaStreams
public class SimpleStreamApplication {
public static void main(String[] args) {
System.out.println("Starting SimpleStreamApplication...");
SpringApplication.run(SimpleStreamApplication.class, args);
}
@Bean(name = KafkaStreamsDefaultConfiguration.DEFAULT_STREAMS_CONFIG_BEAN_NAME)
public KafkaStreamsConfiguration kStreamsConfigs() {
Map<String, Object> props = new HashMap<>();
props.put(APPLICATION_ID_CONFIG, "uppercase-stream-app");
props.put(BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
props.put(DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
return new KafkaStreamsConfiguration(props);
}
@Bean
public KStream<String, String> kStream(StreamsBuilder kStreamBuilder) {
KStream<String, String> stream = kStreamBuilder.stream("input-topic");
stream.mapValues(String::toUpperCase)
.to("output-topic");
System.out.println("Kafka Stream 'uppercase-stream-app' topology built!");
return stream;
}
}Testing Your Stream App
To see your application in action:
- Ensure a Kafka broker is running (e.g., via Docker).
- Run this Spring Boot application.
- Use a Kafka console producer to send messages to
input-topic. - Use a Kafka console consumer to read messages from
output-topicand observe the uppercase transformation.
Stream Concepts Quick Check
Which of the following is the primary purpose of the application.id configuration in a Kafka Streams application?
Recap: Building Stream Apps
Great job! You've learned how to build a basic Kafka Streams application with Spring Boot:
- Configured essential Kafka Streams properties.
- Used
@EnableKafkaStreamsto activate stream processing. - Defined a stream topology using
StreamsBuilder, including reading from a source topic, applying transformations, and writing to a sink topic.
This foundation will help you build more complex real-time data processing pipelines!
Часто задаваемые вопросы
Урок «Создание простого потокового приложения» бесплатный?
Да — полный текст урока «Создание простого потокового приложения» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Advanced Spring Boot 4: Event-Driven Architecture (Kafka), подпишись на CoddyKit PRO. Курс Advanced Spring Boot 4: Event-Driven Architecture (Kafka) содержит 4 уроков всего.
Чему я научусь в уроке «Создание простого потокового приложения»?
Разработайте базовое приложение Spring Boot, использующее Kafka Streams для обработки и преобразования событий в реальном времени. Ты практикуешь Advanced Spring Boot 4: Event-Driven Architecture (Kafka) с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Advanced Spring Boot 4: Event-Driven Architecture (Kafka)?
Предыдущий опыт не требуется. Advanced Spring Boot 4: Event-Driven Architecture (Kafka) на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Создание простого потокового приложения»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Advanced Spring Boot 4: Event-Driven Architecture (Kafka)?
Да. Каждый урок Advanced Spring Boot 4: Event-Driven Architecture (Kafka) включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Введение в Kafka Streams
- Обработка потоков с KStream и KTable
- Создание простого потокового приложения
- Оконные и агрегатные операции с состоянием в Kafka Streams