我试图设置一个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))

但这会引发以下错误
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)

最佳答案

一个应用程序只能有一个SparkContextStreamingContext是在SparkContext上创建的。只需使用SparkContext创建ssc StreamingContext

val sc = new SparkContext(conf)
val ssc = new StreamingContext(sc, Seconds(15))

如果使用以下构造函数。
StreamingContext(conf: SparkConf, batchDuration: Duration)

它在内部创建另一个SparkContext
this(StreamingContext.createNewSparkContext(conf), null, batchDuration)
SparkContext可以通过以下方式从StreamingContext获取:
ssc.sparkContext

关于scala - SparkContext和StreamingContext可以在同一程序中共存吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40623109/

10-13 00:05