201、Spark 2.0之Structured Streaming:wordcount入門案例

Structured Streaming

structured streaming是一種可伸縮的、容錯的、基于Spark SQL引擎的流式計算引擎。你可以使用,與針對靜態(tài)數(shù)據(jù)的批處理計算操作一樣的方式來編寫流式計算操作。隨著數(shù)據(jù)不斷地到達,Spark SQL引擎會以一種增量的方式來執(zhí)行這些操作,并且持續(xù)更新結(jié)算結(jié)果??梢允褂胘ava、scala等編程語言,以及dataset/dataframe api來編寫計算操作,執(zhí)行數(shù)據(jù)流的聚合、基于event的滑動窗口、流式數(shù)據(jù)與離線數(shù)據(jù)的join等操作。所有這些操作都與Spark SQL使用一套引擎來執(zhí)行。此外,structured streaming會通過checkpoint和預(yù)寫日志等機制來實現(xiàn)一次且僅一次的語義。簡單來說,對于開發(fā)人員來說,根本不用去考慮是流式計算,還是批處理,只要使用同樣的方式來編寫計算操作即可,structured streaming在底層會自動去實現(xiàn)快速、可伸縮、容錯、一次且僅一次語義。
spark 2.0僅僅是提供beta版本的structured streaming,所有的相關(guān)api都是實驗性質(zhì)的。

WordCount入門案例

object StructuredNetworkWordCount {
  def main(args: Array[String]): Unit = {
    val spark = SparkSession
      .builder
      .appName("StructuredNetworkWordCount")
      .getOrCreate()

    import spark.implicits._

    // Create DataFrame representing the stream of input lines from connection to localhost:9999
    val lines = spark.readStream
      .format("socket")
      .option("host", "spark-project-1")
      .option("port", 9999)
      .load()

    // Split the lines into words
    val words = lines.as[String].flatMap(_.split(" "))

    // Generate running word count
    val wordCounts = words.groupBy("value").count()

    // Start running the query that prints the running counts to the console
    val query = wordCounts.writeStream
      .outputMode("complete")
      .format("console")
      .start()

    query.awaitTermination()

  }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容