sparkstreaming checkpoint
checkpoint
checkpoint用来保存以下两部分信息:
- 之前运算结果中的数据
- driver端的元数据信息,即程序的执行逻辑。也就是说可以通过
checkpoint
来实现driver
端程序的高可用- 注意
- 如果程序中断之后,对代码进行了修改变更,此时checkpoint目录也就没有意义。还会按照之前的代码逻辑走
import org.apache.spark.SparkConf
import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.streaming.{Seconds, StreamingContext}
object checkpoint {
val chekPointDir = "hdfs://node01:8020/ckD"
def main(args: Array[String]): Unit = {
val sc: StreamingContext = StreamingContext.getOrCreate(chekPointDir,createFunc _)
sc.start()
sc.awaitTermination()
}
def createFunc():StreamingContext = {
val conf: SparkConf = new SparkConf().setAppName("ckWorldCount").setMaster("local[2]")
val sc = new StreamingContext(conf,Seconds(5))
//set checkpoint path
//1.保存DStream之前批次的数据
//2.保存driver端的一些元数据信息(程序的执行逻辑)
sc.checkpoint(chekPointDir)
val socketDS: ReceiverInputDStream[String] = sc.socketTextStream("node01",9999)
val result: DStream[(String, Int)] = socketDS.flatMap(_.split(" ")).map((_,1)).reduceByKey(_+_).updateStateByKey(updateFunc)
result.print()
sc
}
//currentValue:当前批次中每一个单词出现的所有的1
//historyValues:之前批次中每个单词出现的总次数,Option类型表示存在或者不存在。 Some表示存在有值,None表示没有
def updateFunc(currentValue:Seq[Int],historyValues:Option[Int]):Option[Int]={
val newValue: Int = currentValue.sum + historyValues.getOrElse(0)
Some(newValue)
}
}