林子雨-Spark编程基础-厦门大学数据库试验室.PPT

林子雨-Spark编程基础-厦门大学数据库试验室.PPT

7.6.2 DStream有状态转换操作 新打开一个窗口作为nc窗口,启动nc程序: $ nc -lk 9999 //在这个窗口中手动输入一些单词 hadoop spark hadoop spark hadoop spark 切换到刚才的监听窗口,会发现,已经输出了词频统计信息: ------------------------------------------- Time: 1479890485000 ms ------------------------------------------- (spark,1) (hadoop,1) ------------------------------------------- Time: 1479890490000 ms ------------------------------------------- (spark,2) (hadoop,3) 7.7 输出操作 在Spark应用中,外部系统经常需要使用到Spark DStream处理后的数据,因此,需要采用输出操作把DStream的数据输出到数据库或者文件系统中 7.7.1 把DStream输出到文本文件中 7.7.2 把DStream写入到MySQL数据库中 7.7.1 把DStream输出到文本文件中 package org.apache.spark.examples.streaming import org.apache.spark._ import org.apache.spark.streaming._ import org.apache.spark.storage.StorageLevel object NetworkWordCountStateful { def main(args: Array[String]) { //定义状态更新函数 val updateFunc = (values: Seq[Int], state: Option[Int]) = { val currentCount = values.foldLeft(0)(_ + _) val previousCount = state.getOrElse(0) Some(currentCount + previousCount) } StreamingExamples.setStreamingLogLevels() //设置log4j日志级别 请在NetworkWordCountStateful.scala代码文件中输入以下内容: 剩余代码见下一页 7.7.1 把DStream输出到文本文件中 val conf = new SparkConf().setMaster(local[2]).setAppName(NetworkWordCountStateful) val sc = new StreamingContext(conf, Seconds(5)) sc.checkpoint(file:///usr/local/spark/mycode/streaming/dstreamoutput/) //设置检查点,检查点具有容错机制 val lines = sc.socketTextStream(localhost, 9999) val words = lines.flatMap(_.split( )) val wordDstream = words.map(x = (x, 1)) val stateDstream = wordDstream.updateStateByKey[Int](updateFunc) stateDstream.print() //下面是新增的语句,把DStream保存到文本文件中 stateDstream.saveAsTextFiles(file:///usr/local/spark/mycode/streaming/dstreamoutput/output.txt) sc.start() sc.awaitTermination() } } 7.7.1 把DStream输出到文本文件中 sbt打包编译后,使用如下命令运行程序: $ /usr/local/spark/bin/spark-submit --class org.apache.spark.examples.streaming.NetworkWordCountStateful /usr/local/spark/mycode/streaming/dstreamoutput/

文档评论(0)

1亿VIP精品文档

相关文档