SparkContext和StreamingContext可以在同一个程序中共存吗?

mad*_*die 8 scala apache-spark spark-streaming

我正在尝试设置一个Sparkstreaming代码,该代码从Kafka服务器读取行,但使用在另一个本地文件中编写的规则来处理它.我正在为流数据创建streamingContext,并为其他应用所有其他spark功能的sparkContext创建 - 比如字符串操作,读取本地文件等

val sparkConf = new SparkConf().setMaster("local[*]").setAppName("ReadLine")
val ssc = new StreamingContext(sparkConf, Seconds(15))
ssc.checkpoint("checkpoint")

    val topicMap = topics.split(",").map((_, numThreads.toInt)).toMap
    val lines = KafkaUtils.createStream(ssc, zkQuorum, group, topicMap).map(_._2)
    val sentence = lines.toString

    val conf = new SparkConf().setAppName("Bi Gram").setMaster("local[2]")
    val sc = new SparkContext(conf)
    val stringRDD = sc.parallelize(Array(sentence))
Run Code Online (Sandbox Code Playgroud)

但这会引发以下错误

Exception in thread "main" org.apache.spark.SparkException: Only one SparkContext may be running in this JVM (see SPARK-2243). To ignore this error, set spark.driver.allowMultipleContexts = true. The currently running SparkContext was created at:
org.apache.spark.SparkContext.<init>(SparkContext.scala:82)
org.apache.spark.streaming.StreamingContext$.createNewSparkContext(StreamingContext.scala:874)
org.apache.spark.streaming.StreamingContext.<init>(StreamingContext.scala:81)
Run Code Online (Sandbox Code Playgroud)

Roc*_*ang 14

一个应用程序只能有一个SparkContext.StreamingContext是创建的SparkContext.只需要使用SparkContext创建ssc StreamingContext

val sc = new SparkContext(conf)
val ssc = new StreamingContext(sc, Seconds(15))
Run Code Online (Sandbox Code Playgroud)

如果使用以下构造函数.

StreamingContext(conf: SparkConf, batchDuration: Duration)
Run Code Online (Sandbox Code Playgroud)

它内部创造另一个 SparkContext

this(StreamingContext.createNewSparkContext(conf), null, batchDuration)
Run Code Online (Sandbox Code Playgroud)

SparkContext可以得到StreamingContext通过

ssc.sparkContext
Run Code Online (Sandbox Code Playgroud)