Spark Streaming 基础:DStream 转换与行动算子

知识点:
DStream 转换算子:与 RDD 算子类似,支持map、filter、reduceByKey等
有状态转换算子:updateStateByKey(维护全局状态)、window(窗口计算)
DStream 行动算子:pprint、saveAsTextFiles、foreachRDD
练习:
实现带状态的实时词频统计(记录从启动到当前的总词频):

定义状态更新函数

def update_func(new_values, last_state):
if last_state is None:
last_state = 0
return sum(new_values) + last_state

启用检查点(有状态计算必须)

ssc.checkpoint("./checkpoint")

有状态词频统计

word_counts = words.map(lambda word: (word, 1)).updateStateByKey(update_func)
word_counts.pprint()
实现窗口长度 10 秒、滑动间隔 5 秒的窗口词频统计
易错:
有状态计算必须配置检查点,用于持久化状态数据
窗口计算的核心参数 —— 窗口长度(windowDuration)、滑动间隔(slideDuration)

posted @ 2026-01-24 09:51  再报错就堵桥0  阅读(2)  评论(0)    收藏  举报