Why does sbt fail to find KafkaUtils?

2019-07-30 09:06发布

问题:

I have this error in my code (wordCount from Kafka) compiled with SBT

[error] /home/hduser/sbt_project/project1/src/main/scala/sparkKafka.scala:4:35:            object kafka is not a member of package org.apache.spark.streaming`
[error] import org.apache.spark.streaming.kafka.KafkaUtils
 not found: value KafkaUtils
[error] val lines = KafkaUtils.createStream(ssc, "localhost:2181", "spark-stream           ing-consumer-group", Map("customer" -> 2))

The file build.sbt contains these dependencies:

libraryDependencies += "org.apache.spark" % "spark-core_2.12" % "2.4.0"
libraryDependencies += "org.apache.spark" % "spark-streaming_2.12" % "2.4.0"
libraryDependencies += "org.apache.spark" % "spark-streaming-kafka-0-10_2.12" % "2.4.0"

How can I correctly import KafkaUtils?

回答1:

KafkaUtils is in the org.apache.spark.streaming.kafka010 package (note that the namespace for the import includes the version kafka010).

From Spark Streaming Kafka Documentation:

import org.apache.spark.streaming.kafka010._
// ...

// val streamingContext = ...

val kafkaParams = Map[String, Object](
  "bootstrap.servers" -> "localhost:9092",
  "key.deserializer" -> classOf[StringDeserializer],
  "value.deserializer" -> classOf[StringDeserializer],
  "group.id" -> "use_a_separate_group_id_for_each_stream",
  "auto.offset.reset" -> "latest",
  "enable.auto.commit" -> (false: java.lang.Boolean)
)

val topics = Array("topicA", "topicB")
val stream = KafkaUtils.createDirectStream[String, String](
  streamingContext,
  PreferConsistent,
  Subscribe[String, String](topics, kafkaParams)
)

Note: It's usually recommended to use Spark Structured Streaming with Kafka instead.