窗口算子,说白了就是每隔多长(S)时间,统计过去多长时间(W)内产生的数据。
Spark Streaming提供了滑动窗口操作的支持,从而让我们可以对一个滑动窗口内的数据执行计算操作。每次掉落在窗口内的RDD的数据,会被聚合起来执行计算操作,然后生成的RDD,会作为window DStream的一个RDD。比如下图中,就是对每三秒钟的数据执行一次滑动窗口计算,这3秒内的3个RDD会被聚合起来进行处理,然后过了两秒钟,又会对最近三秒内的数据执行滑动窗口计算。所以每个滑动窗口操作,都必须指定两个参数,窗口长度以及滑动间隔,而且这两个参数值都必须是batch间隔的整数倍。
1、红色的矩形就是一个窗口,窗口hold的是一段时间内的数据流。
2、这里面每一个time都是时间单元,在官方的例子中,每隔window size是3 time unit, 而且每隔2个单位时间,窗口会slide一次。
所以基于窗口的操作,需要指定2个参数:
window length - The duration of the window (3 in the figure) 窗口大小,个人感觉是一段时间内数据的容器。
slide interval - The interval at which the window-based operation is performed (2 in the figure). 滑动间隔,就是我们可以理解的cron表达式吧。
滑动窗口的操作:
window 对每个滑动窗口的数据执行自定义的计算
countByWindow 对每个滑动窗口的数据执行count操作
reduceByWindow 对每个滑动窗口的数据执行reduce操作
reduceByKeyAndWindow 对每个滑动窗口的数据执行reduceByKey操作
countByValueAndWindow 对每个滑动窗口的数据执行countByValue操作
?:
/**
* window窗口函数操作
* batchInterval为2秒
*
* 每隔4秒,统计过去6秒内产生的数据
*/
object WindowOps {
def main(args: Array[String]): Unit = {
val conf = new SparkConf()
.setAppName("WindowOps")
.setMaster("local[*]")
val batchInterval = 2L
val windowLength = Seconds(batchInterval * 3)
val slideInterval = Seconds(2 * batchInterval)
val ssc = new StreamingContext(conf, Seconds(batchInterval))
val lines:DStream[String] = ssc.socketTextStream("bigdata01", 9999)
//计算的是当前批次的数据
val pairs:DStream[(String, Int)] = lines.flatMap(_.split("\\s+")).map((_, 1))
val retWindow:DStream[(String, Int)] = pairs.reduceByKeyAndWindow((v1:Int, v2:Int) => v1 + v2, windowLength, slideInterval)
retWindow.print()
ssc.start()
ssc.awaitTermination()
}
}