我正在尝试创建连接到Spark消费者的Kafka生产者。生产者工作正常,但Spark中的消费者由于某种原因不读取主题中的数据。我在docker-compose中使用spotify / kafka图像运行kafka。
这是我的消费者:
object SparkConsumer {
def main(args: Array[String]) {
val spark = SparkSession
.builder()
.appName("KafkaSparkStreaming")
.master("local[*]")
.getOrCreate()
val ssc = new StreamingContext(spark.sparkContext, Seconds(3))
val topic1 = "topic1"
def kafkaParams = Map[String, Object](
"bootstrap.servers" -> "localhost:9092",
"key.deserializer" -> classOf[StringDeserializer],
"value.deserializer" -> classOf[StringDeserializer],
"group.id" -> "group1",
"auto.offset.reset" -> "latest",
"enable.auto.commit" -> (false: java.lang.Boolean)
)
val lines = KafkaUtils.createDirectStream[String, String](
ssc,
LocationStrategies.PreferConsistent,
ConsumerStrategies.Subscribe[String, String](Set(topic1), kafkaParams)
)
lines.print()
}
Kafka Producer看起来像这样:
object KafkaProducer {
def main(args: Array[String]) {
val events = 10
val topic = "topic1"
val brokers = "localhost:9092"
val random = new Random()
val props = new Properties()
props.put("bootstrap.servers", brokers)
props.put("client.id", "KafkaProducerExample")
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer")
val producer = new KafkaProducer[String, String](props)
val t = System.currentTimeMillis()
for (nEvents <- Range(0, events)) {
val key = null
val values = "2017-11-07 04:06:03"
val data = new ProducerRecord[String, String](topic, key, values)
producer.send(data)
System.out.println("sent : " + data.value())
}
System.out.println("sent per second: " + events * 1000 / (System.currentTimeMillis() - t))
producer.close()
}
}
更新:
我的Docker-compose文件与Kafka:
version: '3.3'
services:
kafka:
image: spotify/kafka
ports:
- "9092:9092"
答案 0 :(得分:2)
这是使用Kafka和Docker的常见问题。首先,您应该检查zookeeper中针对您的主题的配置。您可以在Kafka容器中使用Zookeeper脚本。可能在创建主题时,ADVERTISED_HOST是您的服务名称。因此,当消费者尝试连接到代理时,这将返回“kafka”作为代理位置。因为您在docker网络之外运行使用者,所以您的使用者永远不会连接到代理以供使用。尝试使用ADVERTISED_HOST = localhost为您的kafka容器设置env。