Kafka依赖

  1. <dependency>
  2. <groupId>org.apache.spark</groupId>
  3. <artifactId>spark-streaming-kafka-0-10_2.12</artifactId>
  4. <version>3.0.0</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.fasterxml.jackson.core</groupId>
  8. <artifactId>jackson-core</artifactId>
  9. <version>2.10.1</version>
  10. </dependency>

Kafka数据源

  1. package com.streaming
  2. import org.apache.kafka.clients.consumer.{ConsumerConfig, ConsumerRecord}
  3. import org.apache.spark.SparkConf
  4. import org.apache.spark.streaming.dstream.InputDStream
  5. import org.apache.spark.streaming.kafka010.{ConsumerStrategies, KafkaUtils, LocationStrategies}
  6. import org.apache.spark.streaming.{Seconds, StreamingContext}
  7. object Spark_Kafka {
  8. def main(args: Array[String]): Unit = {
  9. val sparkConf = new SparkConf().setMaster("local[*]").setAppName("SparkStreaming")
  10. val ssc = new StreamingContext(sparkConf, Seconds(3))
  11. val kafkaPara: Map[String, Object] = Map[String, Object](
  12. ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG -> "hadoop102:9092,hadoop103:9092,hadoop104:9092",
  13. ConsumerConfig.GROUP_ID_CONFIG -> "hao",
  14. "key.deserializer" -> "org.apache.kafka.common.serialization.StringDeserializer",
  15. "value.deserializer" -> "org.apache.kafka.common.serialization.StringDeserializer"
  16. )
  17. val kafkaDataDS: InputDStream[ConsumerRecord[String, String]] = KafkaUtils.createDirectStream[String, String](
  18. ssc,
  19. LocationStrategies.PreferConsistent,
  20. ConsumerStrategies.Subscribe[String, String](Set("hao"), kafkaPara)
  21. )
  22. kafkaDataDS.map(_.value()).print()
  23. ssc.start()
  24. ssc.awaitTermination()
  25. }
  26. }