Structured Streaming 是一种基于Spark SQL引擎可扩展容错流处理引擎,可以用在静态数据上表示批处理计算的方式来表示流处理,SparkSQL引擎将负责增量的,持续的运行,并在流数据继续到达时更新最终结果。可以使用Scala、Java、Python或R中的Dataset/DataFrame API来表示流聚合、事件事件窗口、流到批处理连接等。计算在同一个优化后的SparkSQL引擎上执行。最后,系统通过检查点和Write-Ahead日志确保端到端只允许一次错误。简而言之,Structured Streaming 提供了快速、可伸缩、容错、端到端精确一次的流处理,而无需用户对流进行推理。
在内部,默认情况下,Structured Streaming 查询是使用微批处理引擎处理的该引擎将数据流作为一系列小批作业处理,从而实现端到端延迟低至100毫秒,并精确地保证一次容错。然而,从Spark 2.3开始,我们引入了一种新的低延迟处理模式,称为连续处理(Continuous processing),它可以在保证至少一次的情况下实现低至1毫秒的端到端延迟。不需要更改查询中的Dataset/DataFrame操作,就可以根据应用程序需求选择模式。
Quick Example
import org.apache.spark.sql.functions._
import org.apache.spark.sql.SparkSession
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", "localhost")
.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()
Programming Model
Structured Streaming 的关键思想是将实时数据流视为一个不断追加的表。这就产生了一个新的流处理模型,它与批处理模型非常相似。您将把流计算表示为静态表上的标准批处理查询,Spark将其作为无边界输入表上的增量查询运行。让我们更详细地理解这个模型。
Basic Concepts
将输入数据流视为“输入表”。流上到达的每个数据项就像是添加到Input Table中的新行。
对输入进行查询将生成“结果表”。在每个触发器间隔(例如,每1秒),将向Input表追加新行,最终更新Result表。每当结果表被更新时,我们都希望将更改的结果行写入外部接收器。