概述
Spark Streaming是核心Spark API的扩展,支持可伸缩、高吞吐量、容错的实时数据流处理。数据可以从Kafka、Flume、Kinesis或TCP套接字等多种来源获取,并且可以使用复杂的算法处理数据,这些算法由map、reduce、join和window等高级函数表示。最后,处理后的数据可以推送到文件系统、数据库和活动仪表板。事实上,您可以将Spark的机器学习和图形处理算法应用于数据流。
SparkStreaming工作原理
Spark streams接收实时输入的数据流,并将数据分成批次,然后由Spark引擎对这些数据进行处理,以批量生成最终的结果流。
DStream
Spark流提供了一个高级抽象,称为离散流或DStream,它表示连续的数据流。DStreams可以从Kafka、Flume和Kinesis等源的输入数据流创建,也可以通过对其他DStreams应用高级操作创建。在内部,DStream表示为RDDs序列。
Example
import org.apache.spark._
import org.apache.spark.streaming._
import org.apache.spark.streaming.StreamingContext._ // not necessary since Spark 1.3
// Create a local StreamingContext with two working thread and batch interval of 1 second.
// The master requires 2 cores to prevent a starvation scenario.
val conf = new SparkConf().setMaster("local[2]").setAppName("NetworkWordCount")
val ssc = new StreamingContext(conf, Seconds(1))
val lines = ssc.socketTextStream("localhost", 9999)
// Split each line into words
val words = lines.flatMap(_.split(" "))
import org.apache.spark.streaming.StreamingContext._ // not necessary since Spark 1.3
// Count each word in each batch
val pairs = words.map(word => (word, 1))
val wordCounts = pairs.reduceByKey(_ + _)
// Print the first ten elements of each RDD generated in this DStream to the console
wordCounts.print()
ssc.start() // Start the computation
ssc.awaitTermination() // Wait for the computation to terminate