0

我需要将在线 Kafka 流式传输期间保存到 HDFS 的事件注入回 DStream PySpark 以进行相同的算法处理。我发现了 Holden Karau 的代码示例,它“等同于像 Kafka 这样的可检查点、可重放、可靠的消息队列”。我想知道是否可以在 PySpark 中实现它:

package com.holdenkarau.spark.testing
import org.apache.spark.streaming._
import org.apache.spark._
import org.apache.spark.rdd.RDD
import org.apache.spark.SparkContext._

import scala.language.implicitConversions
import scala.reflect.ClassTag
import org.apache.spark.streaming.dstream.FriendlyInputDStream

/**
* This is a input stream just for the testsuites. This is equivalent to a
* checkpointable, replayable, reliable message queue like Kafka.
* It requires a sequence as input, and returns the i_th element at the i_th batch
* under manual clock.
*
* Based on TestInputStream class from TestSuiteBase in the Apache Spark project.
*/

class TestInputStream[T: ClassTag](@transient var sc: SparkContext,
  ssc_ : StreamingContext, input: Seq[Seq[T]], numPartitions: Int)
  extends FriendlyInputDStream[T](ssc_) {

  def start() {}

  def stop() {}

  def compute(validTime: Time): Option[RDD[T]] = {
    logInfo("Computing RDD for time " + validTime)
    val index = ((validTime - ourZeroTime) / slideDuration - 1).toInt
    val selectedInput = if (index < input.size) input(index) else Seq[T]()

    // lets us test cases where RDDs are not created
    Option(selectedInput).map{si =>
      val rdd = sc.makeRDD(si, numPartitions)
      logInfo("Created RDD " + rdd.id + " with " + selectedInput)
      rdd
    }
  }
}
4

1 回答 1

0

Spark 提供了两个可用于测试的内置DStream实现,并且在大多数情况下您不需要任何外部实现。

第二个,以简化的形式,在 PySpark 中可用 - pyspark.streaming.StreamingContext.queueStream

ssc = StreamingContext(sc)
ssc.queueStream([
    sc.range(0, 1000),
    sc.range(1000, 2000),
    sc.range(2000, 3000)
])

如果还不够,您可以随时使用新线程将序列化数据原子写入文件系统,然后使用标准基于文件的DStream.

于 2018-04-15T12:51:46.980 回答