我设置了 Spark 流,以便它从套接字读取,在将数据发布到兔子队列之前对数据进行一些丰富。
在设置流上下文之前,扩充从通过读取常规文本文件 (Source.fromFile...) 实例化的 Map 中查找信息。
我有一种感觉,这不是真正应该做的方式。另一方面,当使用 StreamingContext 时,我只能从流中读取,而不能像使用 SparkContext 那样从静态文件中读取。
我可以尝试允许多个上下文,但我不确定这是否也是正确的方法。
任何建议将不胜感激。
最佳答案
假设用于扩充的 map 相当小,可以保存在内存中,建议在 Spark 作业中使用该数据的方法是通过广播变量。此类变量的内容将一次发送给每个执行程序,从而避免序列化在闭包中捕获的数据集的开销。
广播变量是在驱动程序中实例化的包装器,并且使用闭包中的 broadcastVar.value
方法“解包”数据。
这将是如何在 DStream 中使用广播变量的示例:
// could replace with Source.from File as well. This is just more practical
val data = sc.textFile("loopup.txt").map(toKeyValue).collectAsMap()
// declare the broadcast variable
val bcastData = sc.broadcast(data)
... initialize streams ...
socketDStream.map{ elem =>
// doing every step here explicitly for illustrative purposes. Usually, one would typically just chain these calls
// get the map within the broadcast wrapper
val lookupMap = bcastData.value
// use the map to lookup some data
val lookupValue = lookupMap.getOrElse(elem, "not found")
// create the desired result
(elem, lookupValue)
}
socketDStream.saveTo...
关于streaming - Spark 流 : enrich stream with reference data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29193339/