Spark教程(2)Spark Streaming 介绍

时间:2022-01-02 20:48:14
问题导读
1、如何利用DStream所提供的api,而在数据流上实时进行操作?
2、你如何理解Spark Streaming启动后的流程?
3、如何创建StreamingContext对象?


Spark教程(2)Spark Streaming 介绍



随着big data的发展,人们对大数据的处理要求也越来越高,传统的MapReduce等批处理框架在某些特定领域(如实时用户推荐,用户行为分析)已经无法满足人们对实时性的需求。因此诞生了一批如 S4Storm这样的流式的、实时的计算框架。本文介绍的 Spark Streaming也正是一个这样的流式计算框架。

What is Spark Streaming
作为UC Berkeley云计算software stack的一部分,Spark Streaming是建立在Spark上的应用框架,利用Spark的底层框架作为其执行基础,并在其上构建了DStream的行为抽象。利用DStream所提供的api,用户可以在数据流上实时进行count,join,aggregate等操作。

  1. A Spark Streaming application is very similar to a Spark application; it consists of a driver program that runs the user’s main function and continuous executes various parallel operations on input streams of data. The main abstraction Spark Streaming provides is a discretized stream (DStream), which is a continuous sequence of RDDs (distributed collections of elements) representing a continuous stream of data. DStreams can be created from live incoming data (such as data from a socket, Kafka, etc.) or can be generated by transformong existing DStreams using parallel operators like map, reduce, and window.
复制代码



How to Use Spark Streaming
作为构建于Spark之上的应用框架,Spark Streaming承袭了Spark的编程风格,对于了解Spark的用户来说能够快速地上手。接下来以word count为例来介绍Spark Streaming的使用方式:
  1. import spark.streaming.{Seconds, StreamingContext}
  2. import spark.streaming.StreamingContext._
  3. ...
  4. // Create the context and set up a network input stream to receive from a host:port
  5. val ssc = new StreamingContext(args(0), "NetworkWordCount", Seconds(1))
  6. val lines = ssc.socketTextStream(args(1), args(2).toInt)
  7. // Split the lines into words, count them, and print some of the counts on the master
  8. val words = lines.flatMap(_.split(" "))
  9. val wordCounts = words.map(x => (x, 1)).reduceByKey(_ + _)
  10. wordCounts.print()
  11. // Start the computation
  12. ssc.start()
复制代码


1、创建StreamingContext对象

同Spark初始需要创建SparkContext对象一样,使用Spark Streaming就需要创建StreamingContext对象。创建StreamingContext对象所需的参数与SparkContext基本一致,包括指明master,设定名称(如NetworkWordCount)。需要注意的是参数Seconds(1),Spark Streaming需要指定处理数据的时间间隔,如上例所示的1s,那么Spark Streaming会以1s为时间窗口进行数据处理。此参数需要根据用户的需求和集群的处理能力进行适当的设置。

2、创建InputDStream

如同Storm的Spout,Spark Streaming需要指明数据源。如上例所示的socketTextStream,Spark Streaming以socket连接作为数据源读取数据。当然Spark Streaming支持多种不同的数据源,包括kafkaStream,flumeStream,fileStream, networkStream等。

3、操作DStream

对于从数据源得到的DStream,用户可以在其基础上进行各种操作,如上例所示的操作就是一个典型的word count执行流程:对于当前时间窗口内从数据源得到的数据首先进行分割,然后利用MapReduce算法映射和计算,当然最后还有print()输出结果。

4、启动Spark Streaming

之前所作的所有步骤只是创建了执行流程,程序没有真正连接上数据源,也没有对数据进行任何操作,只是设定好了所有的执行计划,当ssc.start()启动后程序才真正进行所有预期的操作。

至此对于Spark Streaming的如何使用有了一个大概的印象,接下来我们来探究一下Spark Streaming背后的代码。

Spark Streaming 源码分析
StreamingContext
Spark Streaming使用StreamingContext提供对外接口,用户可以使用StreamingContext提供的api来构建自己的Spark Streaming应用程序。

StreamingContext内部维护SparkContext实例,通过SparkContext进行RDD的操作。
在实例化StreamingContext时需要指定batchDuration,用来指示Spark Streaming recurring job的重复时间。
StreamingContext提供了多种不同的接口,可以从多种数据源创建DStream。
StreamingContext提供了起停streaming job的api。

DStream
Spark Streaming是建立在Spark基础上的,它封装了Spark的RDD并在其上抽象了流式的数据表现形式DStream:
  1. A Discretized Stream (DStream), the basic abstraction in Spark Streaming, is a continuous sequence of RDDs (of the same type) representing a continuous stream of data. DStreams can either be created from live data (such as, data from HDFS, Kafka or Flume) or it can be generated by transformation existing DStreams using operations such as map, window and reduceByKeyAndWindow. While a Spark Streaming program is running, each DStream periodically generates a RDD, either from live data or by transforming the RDD generated by a parent DStream
复制代码
Spark教程(2)Spark Streaming 介绍

1.png (29.73 KB, 下载次数: 0)

下载附件  保存到相册

2014-10-23 21:42 上传





DStream内部主要结构如下所示:
  1. abstract class DStream[T: ClassManifest] (
  2.     @transient protected[streaming] var ssc: StreamingContext
  3.         ) extends Serializable with Logging {

  4.   initLogging()

  5.   // =======================================================================
  6.   // Methods that should be implemented by subclasses of DStream
  7.   // =======================================================================

  8.   /** Time interval after which the DStream generates a RDD */
  9.   def slideDuration: Duration

  10.   /** List of parent DStreams on which this DStream depends on */
  11.   def dependencies: List[DStream[_]]

  12.   /** Method that generates a RDD for the given time */
  13.   /** DStream的核心函数,每一个继承于此的子类都需要实现此compute()函数。而根据不同的
  14.       DStream, compute()函数都需要实现其特定功能,而计算的结果则是返回计算好的RDD*/
  15.   def compute (validTime: Time): Option[RDD[T]]

  16.   // =======================================================================
  17.   // Methods and fields available on all DStreams
  18.   // =======================================================================

  19.   // RDDs generated, marked as protected[streaming] so that testsuites can access it
  20.   /** 每一个DStream内部维护的RDD HashMap,DStream本质上封装了一组以Time为key的RDD,而对于
  21.       DStream的各种操作在内部映射为对RDD的操作 */
  22.   @transient
  23.   protected[streaming] var generatedRDDs = new HashMap[Time, RDD[T]] ()

  24.   // Time zero for the DStream
  25.   protected[streaming] var zeroTime: Time = null

  26.   // Duration for which the DStream will remember each RDD created
  27.   protected[streaming] var rememberDuration: Duration = null

  28.   // Storage level of the RDDs in the stream
  29.   protected[streaming] var storageLevel: StorageLevel = StorageLevel.NONE

  30.   // Checkpoint details
  31.   protected[streaming] val mustCheckpoint = false
  32.   protected[streaming] var checkpointDuration: Duration = null
  33.   protected[streaming] val checkpointData = new DStreamCheckpointData(this)

  34.   // Reference to whole DStream graph
  35.   /** 所有的DStream都注册到DStreamGraph中,调用DStreamGraph来执行所有的DStream和所有的dependencies */
  36.   protected[streaming] var graph: DStreamGraph = null

  37.   protected[streaming] def isInitialized = (zeroTime != null)

  38.   // Duration for which the DStream requires its parent DStream to remember each RDD created
  39.   protected[streaming] def parentRememberDuration = rememberDuration

  40.   ...
复制代码



DStream在内部维护了一组时间序列的RDD,对于DStream的transformation和output在内部都转化为对于RDD的transformation和output。

下面来看一下对于DStream的计算是如何映射到对于RDD的计算上去的。
  1. protected[streaming] def getOrCompute(time: Time): Option[RDD[T]] = {
  2.   // If this DStream was not initialized (i.e., zeroTime not set), then do it
  3.   // If RDD was already generated, then retrieve it from HashMap
  4.   generatedRDDs.get(time) match {

  5.     // If an RDD was already generated and is being reused, then
  6.     // probably all RDDs in this DStream will be reused and hence should be cached
  7.     case Some(oldRDD) => Some(oldRDD)

  8.     // if RDD was not generated, and if the time is valid
  9.     // (based on sliding time of this DStream), then generate the RDD
  10.     case None => {
  11.       if (isTimeValid(time)) {
  12.         /** 对于每一次的计算,DStream会调用子类所实现的compute()函数来计算产生新的RDD */
  13.         compute(time) match {
  14.           case Some(newRDD) =>
  15.             if (storageLevel != StorageLevel.NONE) {
  16.               newRDD.persist(storageLevel)
  17.               logInfo("Persisting RDD " + newRDD.id + " for time " + time + " to " + storageLevel + " at time " + time)
  18.             }
  19.             if (checkpointDuration != null && (time - zeroTime).isMultipleOf (checkpointDuration)) {
  20.               newRDD.checkpoint()
  21.               logInfo("Marking RDD " + newRDD.id + " for time " + time + " for checkpointing at time " + time)
  22.             }
  23.                         /** 新产生的RDD会放入Hash Map中 */
  24.             generatedRDDs.put(time, newRDD)
  25.             Some(newRDD)
  26.           case None =>
  27.             None
  28.         }
  29.       } else {
  30.         None
  31.       }
  32.     }
  33.   }
  34. }
复制代码



通过每次提交的job,调用getOrCompute()来计算:
  1. protected[streaming] def generateJob(time: Time): Option[Job] = {
  2. getOrCompute(time) match {
  3.     case Some(rdd) => {
  4.       val jobFunc = () => {
  5.         val emptyFunc = { (iterator: Iterator[T]) => {} }
  6.         context.sparkContext.runJob(rdd, emptyFunc)
  7.       }
  8.       Some(new Job(time, jobFunc))
  9.     }
  10.     case None => None
  11.   }
  12. }
复制代码



Job & Scheduler
从DStream可知,在调用generateJob()时,DStream会通过getOrCompute()函数来计算或是转换DStream,那么Spark Streaming会在何时调用generateJob()呢?

在实例化StreamingContext时,StreamingContext会要求用户设置batchDuration,而batchDuration则指明了recurring job的重复时间,在每个batchDuration到来时都会产生一个新的job来计算DStream,从Scheduler的代码里可以看到:
  1. val clockClass = System.getProperty("spark.streaming.clock", "spark.streaming.util.SystemClock")
  2. val clock = Class.forName(clockClass).newInstance().asInstanceOf[Clock]

  3. /** Spark streaming在Scheduler内部创建了recurring timer,recurring timer的超时时间
  4.     则是用户设置的batchDuration,在超时后调用Scheduler的generateJob */
  5. val timer = new RecurringTimer(clock, ssc.graph.batchDuration.milliseconds,
  6. longTime => generateJobs(new Time(longTime)))
  7. generateJobs()的代码如下所示,Scheduler的generateJobs()会调用DStreamGraph的generateJobs,并对于每一个job使用JobManager来run job。

  8. def generateJobs(time: Time) {
  9.   SparkEnv.set(ssc.env)
  10.   logInfo("\n-----------------------------------------------------\n")
  11.   graph.generateJobs(time).foreach(jobManager.runJob)
  12.   latestTime = time
  13.   doCheckpoint(time)
  14. }
复制代码



在DStreamGraph中,generateJobs()如下所示:
  1. def generateJobs(time: Time): Seq[Job] = {
  2.   this.synchronized {
  3.     logInfo("Generating jobs for time " + time)
  4.     val jobs = outputStreams.flatMap(outputStream => outputStream.generateJob(time))
  5.     logInfo("Generated " + jobs.length + " jobs for time " + time)
  6.     jobs
  7.   }
  8. }
复制代码



对于每一个outputStream调用generateJob()来转换或计算DStream,output的计算会依赖于dependecy的计算,因此最后会对所有dependency都进行计算,得出最后的outputStream。

而所有的这些操作,都在调用StreamingContext的启动函数后进行执行。
  1. def start() {
  2.   if (checkpointDir != null && checkpointDuration == null && graph != null) {
  3.     checkpointDuration = graph.batchDuration
  4.   }

  5.   validate()

  6.   /** StreamingContext注册和启动所有的input stream */
  7.   val networkInputStreams = graph.getInputStreams().filter(s => s match {
  8.       case n: NetworkInputDStream[_] => true
  9.       case _ => false
  10.     }).map(_.asInstanceOf[NetworkInputDStream[_]]).toArray

  11.   if (networkInputStreams.length > 0) {
  12.     // Start the network input tracker (must start before receivers)
  13.     networkInputTracker = new NetworkInputTracker(this, networkInputStreams)
  14.     networkInputTracker.start()
  15.   }

  16.   Thread.sleep(1000)

  17.   // 启动scheduler进行streaming的操作
  18.   scheduler = new Scheduler(this)
  19.   scheduler.start()
  20. }
复制代码



至此,对于Spark Streaming的使用和内部结构应该有了一个基本的了解,以一副Spark Streaming启动后的流程图来结束这篇文章。

Spark教程(2)Spark Streaming 介绍

1.png (54.47 KB, 下载次数: 1)

下载附件  保存到相册

2014-10-23 21:43 上传




Reference
Spark Streaming Documentation