๐ Data Engineering
Flink
Apache Flink
A real-time stream processing framework. Strong at event-time processing.
Apache Flink
A real-time stream processing framework. Strong at event-time processing.
Apache Flink is a distributed processing engine for stateful computations over unbounded and bounded data streams. It natively supports Event Time processing and Exactly-Once semantics.
| Item | Flink | Spark Streaming |
|---|---|---|
| Processing Model | True Streaming | Micro-batch |
| Latency | Milliseconds | Seconds |
| Event Time | Native support | Supported in Structured Streaming |
| State Management | Built-in state backend | Limited |
| SQL Support | Flink SQL | Spark SQL |
# PyFlink๋ฅผ ์ฌ์ฉํ ์ค์๊ฐ ์คํธ๋ฆผ ์ฒ๋ฆฌ
from pyflink.datastream import StreamExecutionEnvironment
from pyflink.datastream.connectors.kafka import (
KafkaSource, KafkaOffsetsInitializer, KafkaSink,
KafkaRecordSerializationSchema
)
from pyflink.common import WatermarkStrategy, Types
from pyflink.common.serialization import SimpleStringSchema
from pyflink.datastream.window import TumblingEventTimeWindows
from pyflink.common.time import Time, Duration
from pyflink.datastream.functions import ProcessWindowFunction
import json
# ์คํ ํ๊ฒฝ ์ค์
env = StreamExecutionEnvironment.get_execution_environment()
env.set_parallelism(4)
env.enable_checkpointing(60000) # 1๋ถ๋ง๋ค ์ฒดํฌํฌ์ธํ
# Kafka ์์ค ์ค์
kafka_source = KafkaSource.builder() \
.set_bootstrap_servers("kafka:9092") \
.set_topics("user-events") \
.set_group_id("flink-consumer-group") \
.set_starting_offsets(KafkaOffsetsInitializer.latest()) \
.set_value_only_deserializer(SimpleStringSchema()) \
.build()
# Watermark ์ ๋ต (์ด๋ฒคํธ ์๊ฐ ๊ธฐ๋ฐ)
watermark_strategy = WatermarkStrategy \
.for_bounded_out_of_orderness(Duration.of_seconds(5)) \
.with_timestamp_assigner(
lambda event, timestamp: json.loads(event)['event_time']
)
# ์คํธ๋ฆผ ์์ฑ
stream = env.from_source(
kafka_source,
watermark_strategy,
"Kafka Source"
)
# ์ด๋ฒคํธ ํ์ฑ ๋ฐ ํค ์ถ์ถ
def parse_event(event_str):
event = json.loads(event_str)
return (event['user_id'], event)
parsed_stream = stream.map(
parse_event,
output_type=Types.TUPLE([Types.STRING(), Types.MAP(Types.STRING(), Types.STRING())])
)
# ์๋์ฐ ์ง๊ณ
class EventCountWindowFunction(ProcessWindowFunction):
def process(self, key, context, elements):
count = len(list(elements))
window_start = context.window().start
window_end = context.window().end
yield {
'user_id': key,
'event_count': count,
'window_start': window_start,
'window_end': window_end
}
# 5๋ถ ํ
๋ธ๋ง ์๋์ฐ๋ก ์ฌ์ฉ์๋ณ ์ด๋ฒคํธ ์ง๊ณ
result_stream = parsed_stream \
.key_by(lambda x: x[0]) \
.window(TumblingEventTimeWindows.of(Time.minutes(5))) \
.process(EventCountWindowFunction())
# ๊ฒฐ๊ณผ๋ฅผ Kafka๋ก ์ ์ก
kafka_sink = KafkaSink.builder() \
.set_bootstrap_servers("kafka:9092") \
.set_record_serializer(
KafkaRecordSerializationSchema.builder()
.set_topic("user-event-counts")
.set_value_serialization_schema(SimpleStringSchema())
.build()
) \
.build()
result_stream.map(lambda x: json.dumps(x)).sink_to(kafka_sink)
# ์คํ
env.execute("User Event Aggregation")
-- Flink SQL์ ์ฌ์ฉํ ์ค์๊ฐ ๋ฐ์ดํฐ ์ฒ๋ฆฌ
-- Kafka ์์ค ํ
์ด๋ธ ์์ฑ
CREATE TABLE user_events (
user_id STRING,
event_type STRING,
event_time TIMESTAMP(3),
properties MAP<STRING, STRING>,
WATERMARK FOR event_time AS event_time - INTERVAL '5' SECOND
) WITH (
'connector' = 'kafka',
'topic' = 'user-events',
'properties.bootstrap.servers' = 'kafka:9092',
'properties.group.id' = 'flink-sql-consumer',
'scan.startup.mode' = 'latest-offset',
'format' = 'json'
);
-- ๊ฒฐ๊ณผ ์ฑํฌ ํ
์ด๋ธ (Kafka)
CREATE TABLE user_event_metrics (
user_id STRING,
window_start TIMESTAMP(3),
window_end TIMESTAMP(3),
event_count BIGINT,
unique_event_types BIGINT,
PRIMARY KEY (user_id, window_start) NOT ENFORCED
) WITH (
'connector' = 'upsert-kafka',
'topic' = 'user-metrics',
'properties.bootstrap.servers' = 'kafka:9092',
'key.format' = 'json',
'value.format' = 'json'
);
-- 5๋ถ ํ
๋ธ๋ง ์๋์ฐ ์ง๊ณ ์ฟผ๋ฆฌ
INSERT INTO user_event_metrics
SELECT
user_id,
TUMBLE_START(event_time, INTERVAL '5' MINUTE) AS window_start,
TUMBLE_END(event_time, INTERVAL '5' MINUTE) AS window_end,
COUNT(*) AS event_count,
COUNT(DISTINCT event_type) AS unique_event_types
FROM user_events
GROUP BY
user_id,
TUMBLE(event_time, INTERVAL '5' MINUTE);
-- ์ฌ๋ผ์ด๋ฉ ์๋์ฐ๋ก ์ค์๊ฐ ์ด์ ํ์ง
SELECT
user_id,
HOP_START(event_time, INTERVAL '1' MINUTE, INTERVAL '5' MINUTE) AS window_start,
COUNT(*) AS event_count
FROM user_events
GROUP BY
user_id,
HOP(event_time, INTERVAL '1' MINUTE, INTERVAL '5' MINUTE)
HAVING COUNT(*) > 100; -- 5๋ถ ๋ด 100๊ฐ ์ด์ ์ด๋ฒคํธ๋ ์ด์ ์งํ
// Java๋ฅผ ์ฌ์ฉํ Flink ์คํธ๋ฆผ ์ฒ๋ฆฌ
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
public class UserEventProcessor {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env =
StreamExecutionEnvironment.getExecutionEnvironment();
env.enableCheckpointing(60000);
env.setParallelism(4);
// Kafka ์์ค
KafkaSource<UserEvent> source = KafkaSource.<UserEvent>builder()
.setBootstrapServers("kafka:9092")
.setTopics("user-events")
.setGroupId("flink-java-consumer")
.setValueOnlyDeserializer(new UserEventDeserializer())
.build();
// Watermark ์ ๋ต
WatermarkStrategy<UserEvent> watermarkStrategy =
WatermarkStrategy.<UserEvent>forBoundedOutOfOrderness(
Duration.ofSeconds(5))
.withTimestampAssigner((event, ts) -> event.getEventTime());
// ์คํธ๋ฆผ ์ฒ๋ฆฌ
DataStream<UserEventCount> result = env
.fromSource(source, watermarkStrategy, "Kafka Source")
.keyBy(UserEvent::getUserId)
.window(TumblingEventTimeWindows.of(Time.minutes(5)))
.aggregate(new EventCountAggregator());
result.sinkTo(kafkaSink);
env.execute("User Event Processing");
}
}