pom.xml
<?xml version="1.0" encoding="UTF-8"?>
开启zookeeper和kafka集群。
创建主题
kafka-topics.sh --create --topic kafka_spark --partitions 3 --replication-factor 1 --zookeeper hadoop01:2181,hadoop02:2181,hadoop03:2181
启动生产者
kafka-console-producer.sh --broker-list hadoop01:9092 --topic kafka_spark
SparkStreaming_Kafka_createDirectStream.scala
import kafka.serializer.StringDecoderimport org.apache.spark.{SparkConf, SparkContext}import org.apache.spark.streaming.{Seconds, StreamingContext}import org.apache.spark.streaming.dstream.{DStream, InputDStream}import org.apache.spark.streaming.kafka.KafkaUtils//todo:利用sparkStreaming对接kafka实现单词计数----采用Direct(低级API)object SparkStreaming_Kafka_createDirectStream { def main(args: Array[String]): Unit = { //1、创建sparkConf val sparkConf: SparkConf = new SparkConf() .setAppName("SparkStreaming_Kafka_createDirectStream") .setMaster("local[2]") //2、创建sparkContext val sc = new SparkContext(sparkConf) sc.setLogLevel("WARN") //3、创建StreamingContext val ssc = new StreamingContext(sc,Seconds(5)) ssc.checkpoint("./Kafka_Direct") //4、配置kafka相关参数 val kafkaParams=Map("metadata.broker.list"->"hadoop01:9092,hadoop02:9092,hadoop03:9092","group.id"->"spark_direct") //5、定义topic val topics=Set("kafka_direct0") //6、通过 KafkaUtils.createDirectStream接受kafka数据,这里采用是kafka低级api偏移量不受zk管理 val dstream: InputDStream[(String, String)] = KafkaUtils.createDirectStream[String,String,StringDecoder,StringDecoder](ssc,kafkaParams,topics) //7、获取kafka中topic中的数据 val topicData: DStream[String] = dstream.map(_._2) //8、切分每一行,每个单词计为1 val wordAndOne: DStream[(String, Int)] = topicData.flatMap(_.split(" ")).map((_,1)) //9、相同单词出现的次数累加 val result: DStream[(String, Int)] = wordAndOne.reduceByKey(_+_) //10、打印输出 result.print() //开启计算 ssc.start() ssc.awaitTermination() }}
创建主题
kafka-topics.sh --create --topic kafka_direct0 --partitions 3 --replication-factor 1 --zookeeper hadoop01:2181,hadoop02:2181,hadoop03:2181
启动生产者
kafka-console-producer.sh --broker-list hadoop01:9092 --topic kafka_direct0