Spark修鍊之道(進階篇)——Spark入門到精通:第十三節 Spark Streaming—— Spark SQL、DataFrame與Spark Streaming

來源:互聯網
上載者:User

Spark修鍊之道(進階篇)——Spark入門到精通:第十三節 Spark Streaming—— Spark SQL、DataFrame與Spark Streaming
主要內容Spark SQL、DataFrame與Spark Streaming1. Spark SQL、DataFrame與Spark Streaming

源碼直接參照:https://github.com/apache/spark/blob/master/examples/src/main/scala/org/apache/spark/examples/streaming/SqlNetworkWordCount.scala

import org.apache.spark.SparkConfimport org.apache.spark.SparkContextimport org.apache.spark.rdd.RDDimport org.apache.spark.streaming.{Time, Seconds, StreamingContext}import org.apache.spark.util.IntParamimport org.apache.spark.sql.SQLContextimport org.apache.spark.storage.StorageLevelobject SqlNetworkWordCount {  def main(args: Array[String]) {    if (args.length < 2) {      System.err.println("Usage: NetworkWordCount  ")      System.exit(1)    }    StreamingExamples.setStreamingLogLevels()    // Create the context with a 2 second batch size    val sparkConf = new SparkConf().setAppName("SqlNetworkWordCount").setMaster("local[4]")    val ssc = new StreamingContext(sparkConf, Seconds(2))    // Create a socket stream on target ip:port and count the    // words in input stream of \n delimited text (eg. generated by 'nc')    // Note that no duplication in storage level only for running locally.    // Replication necessary in distributed scenario for fault tolerance.    //Socke作為資料來源    val lines = ssc.socketTextStream(args(0), args(1).toInt, StorageLevel.MEMORY_AND_DISK_SER)    //words DStream    val words = lines.flatMap(_.split(" "))    // Convert RDDs of the words DStream to DataFrame and run SQL query    //調用foreachRDD方法,遍曆DStream中的RDD    words.foreachRDD((rdd: RDD[String], time: Time) => {      // Get the singleton instance of SQLContext      val sqlContext = SQLContextSingleton.getInstance(rdd.sparkContext)      import sqlContext.implicits._      // Convert RDD[String] to RDD[case class] to DataFrame      val wordsDataFrame = rdd.map(w => Record(w)).toDF()      // Register as table      wordsDataFrame.registerTempTable("words")      // Do word count on table using SQL and print it      val wordCountsDataFrame =        sqlContext.sql("select word, count(*) as total from words group by word")      println(s"========= $time =========")      wordCountsDataFrame.show()    })    ssc.start()    ssc.awaitTermination()  }}/** Case class for converting RDD to DataFrame */case class Record(word: String)/** Lazily instantiated singleton instance of SQLContext */object SQLContextSingleton {  @transient  private var instance: SQLContext = _  def getInstance(sparkContext: SparkContext): SQLContext = {    if (instance == null) {      instance = new SQLContext(sparkContext)    }    instance  }}

運行程式後,再運行下列命令

root@sparkmaster:~# nc -lk 9999Spark is a fast and general cluster computing system for Big DataSpark is a fast and general cluster computing system for Big DataSpark is a fast and general cluster computing system for Big DataSpark is a fast and general cluster computing system for Big DataSpark is a fast and general cluster computing system for Big DataSpark is a fast and general cluster computing system for Big DataSpark is a fast and general cluster computing system for Big Data

處理結果:

========= 1448783840000 ms =========+---------+-----+|     word|total|+---------+-----+|    Spark|   12||   system|   12||  general|   12||     fast|   12||      and|   12||computing|   12||        a|   12||       is|   12||      for|   12||      Big|   12||  cluster|   12||     Data|   12|+---------+-----+========= 1448783842000 ms =========+----+-----+|word|total|+----+-----++----+-----+========= 1448783844000 ms =========+----+-----+|word|total|+----+-----++----+-----+

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.