spark-streaming-[8]-Spark Streaming + Kafka Integration Guide0.8.2.1学习笔记中已知:
There are two approaches to this - the old approach using Receivers and Kafka’s high-level API, and a new approach (introduced in Spark 1.3) without using Receivers.
Spark-Streaming获取kafka数据的两种方式-Receiver与Direct的方式,可以从代码中简单理解成Receiver方式是通过zookeeper来连接kafka队列,Direct方式是直接连接到kafka的节点上获取数据了。
一、基于Receiver的方式
这种方式使用Receiver来获取数据。Receiver是使用Kafka的高层次Consumer API来实现的。receiver从Kafka中获取的数据都是存储在Spark Executor的内存中的,然后Spark Streaming启动的job会去处理那些数据。
然而,在默认的配置下,这种方式可能会因为底层的失败而丢失数据。如果要启用高可靠机制,让数据零丢失,就必须启用Spark Streaming的预写日志机制(Write Ahead Log,WAL)。该机制会同步地将接收到的Kafka数据写入分布式文件系统(比如HDFS)上的预写日志中。所以,即使底层节点出现了失败,也可以使用预写日志中的数据进行恢复。
注意
1、Kafka中的topic的partition,与Spark中的RDD的partition是没有关系的。所以,在KafkaUtils.createStream()中,提高partition的数量,只会增加一个Receiver中,读取partition的线程的数量。不会增加Spark处理数据的并行度。
2、可以创建多个Kafka输入DStream,使用不同的consumer group和topic,来通过多个receiver并行接收数据。
3、如果基于容错的文件系统,比如HDFS,启用了预写日志机制,接收到的数据都会被复制一份到预写日志中。因此,在KafkaUtils.createStream()中,设置的持久化级别是StorageLevel.MEMORY_AND_DISK_SER。
二、基于Direct的方式
这种新的不基于Receiver的直接方式,是在Spark 1.3中引入的,从而能够确保更加健壮的机制。替代掉使用Receiver来接收数据后,这种方式会周期性地查询Kafka,来获得每个topic+partition的最新的offset,从而定义每个batch的offset的范围。当处理数据的job启动时,就会使用Kafka的简单consumer api来获取Kafka指定offset范围的数据。
这种方式有如下优点:
1、简化并行读取:如果要读取多个partition,不需要创建多个输入DStream然后对它们进行union操作。Spark会创建跟Kafka partition一样多的RDD partition,并且会并行从Kafka中读取数据。所以在Kafka partition和RDD partition之间,有一个一对一的映射关系。
2、高性能:如果要保证零数据丢失,在基于receiver的方式中,需要开启WAL机制。这种方式其实效率低下,因为数据实际上被复制了两份,Kafka自己本身就有高可靠的机制,会对数据复制一份,而这里又会复制一份到WAL中。而基于direct的方式,不依赖Receiver,不需要开启WAL机制,只要Kafka中作了数据的复制,那么就可以通过Kafka的副本进行恢复。
3、一次且仅一次的事务机制:
基于receiver的方式,是使用Kafka的高阶API来在ZooKeeper中保存消费过的offset的。这是消费Kafka数据的传统方式。这种方式配合着WAL机制可以保证数据零丢失的高可靠性,但是却无法保证数据被处理一次且仅一次,可能会处理两次。因为Spark和ZooKeeper之间可能是不同步的。
基于direct的方式,使用kafka的简单api,Spark Streaming自己就负责追踪消费的offset,并保存在checkpoint中。Spark自己一定是同步的,因此可以保证数据是消费一次且仅消费一次。
以上参考: Spark-Streaming获取kafka数据的两种方式-Receiver与Direct的方式 感谢
Approach 1: Receiver-based Approach
参见: spark-streaming-[6]-KafkaWordCount和KafkaWordCountProducer(Receiver-based Approach)Approach 2: Direct Approach (No Receivers)
示例
第一步具体如下:
具体参见: Kafka-[2]-Documentation-单机QuickStartStart the server
Kafka uses ZooKeeper so you need to first start a ZooKeeper server if you don't already have one. You can use the convenience script packaged with kafka to get a quick-and-dirty single-node ZooKeeper instance.
> bin/zookeeper-server-start.sh config/zookeeper.properties
Now start the Kafka server:
> bin/kafka-server-start.sh config/server.properties
Create a topic
Let's create a topic named "test" with a single partition and only one replica:
> bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic test2
We can now see that topic if we run the list topic command:
> bin/kafka-topics.sh --list --zookeeper localhost:2181 test2
Send some messages
Kafka comes with a command line client that will take input from a file or from standard input and send it out as messages to the Kafka cluster. By default, each line will be sent as a separate message.
Run the producer and then type a few messages into the console to send to the server.
> bin/kafka-console-producer.sh --broker-list localhost:9092 --topic test2
将以下数据粘到console中,粘贴3次,即模拟有3次数据写入Kafka中。(“WWW”出现33次)
[2017-05-07 13:11:24,645] WWW Server environment:java.io.tmpdir=sw8vdr0000gn/T/ (org.apache.zookeeper.server.ZooKeeperServer)
[2017-05-07 13:11:24,645] WWW Server environment:java.compiler=<NA> (org.apache.zookeeper.server.ZooKeeperServer)
[2017-05-07 13:11:24,645] WWW Server environment:os.name=Mac OS X (org.apache.zookeeper.server.ZooKeeperServer)
[2017-05-07 13:11:24,645] WWW Server environment:os.arch=x86_64 (org.apache.zookeeper.server.ZooKeeperServer)
[2017-05-07 13:11:24,645] WWW Server environment:os.version=10.10.5 (org.apache.zookeeper.server.ZooKeeperServer)
[2017-05-07 13:11:24,645] WWW Server environment:user.name=hjw (org.apache.zookeeper.server.ZooKeeperServer)
[2017-05-07 13:11:24,645] WWW Server environment:user.home=/Users/hjw (org.apache.zookeeper.server.ZooKeeperServer)
[2017-05-07 13:11:24,645] WWW Server environment:user.dir=ka/kafka_2.11-0.10.2.1 (org.apache.zookeeper.server.ZooKeeperServer)
[2017-05-07 13:11:24,653] WWW tickTime set to 3000 (org.apache.zookeeper.server.ZooKeeperServer)
[2017-05-07 13:11:24,653] WWW minSessionTimeout set to -1 (org.apache.zookeeper.server.ZooKeeperServer)
[2017-05-07 13:11:24,653] WWW maxSessionTimeout set to -1 (org.apache.zookeeper.server.ZooKeeperServer)
第二步运行sparkstreaming DirectKafkaWordCount
参数:localhost:9092 test2
其中Kafka的offset为从头开始读取数据
val kafkaParams = Map[String, String]("metadata.broker.list" -> brokers,"auto.offset.reset"->"smallest")
输出:
-------------------------------------------
Time: 1494141102000 ms
-------------------------------------------
(-1,6)
(environment:os.name=Mac,3)
(X,3)
(environment:java.compiler=<NA>,3)
(OS,3)
([2017-05-07,33)
(3000,3)
((org.apache.zookeeper.server.ZooKeeperServer),33)
(13:11:24,653],9)
...
17/05/07 15:11:42 INFO VerifiableProperties: Verifying properties
17/05/07 15:11:42 INFO VerifiableProperties: Property auto.offset.reset is overridden to smallest
17/05/07 15:11:42 INFO VerifiableProperties: Property group.id is overridden to
17/05/07 15:11:42 INFO VerifiableProperties: Property zookeeper.connect is overridden to
-------------------------------------------
Time: 1494141102000 ms
-------------------------------------------
(WWW,33)
再次粘贴测试数据一次进入producer:
输出:
-------------------------------------------
Time: 1494142328000 ms
-------------------------------------------
(-1,2)
(environment:os.name=Mac,1)
(X,1)
(environment:java.compiler=<NA>,1)
(OS,1)
([2017-05-07,11)
(3000,1)
((org.apache.zookeeper.server.ZooKeeperServer),11)
(13:11:24,653],3)
...
17/05/07 15:32:08 INFO VerifiableProperties: Verifying properties
17/05/07 15:32:08 INFO VerifiableProperties: Property auto.offset.reset is overridden to smallest
17/05/07 15:32:08 INFO VerifiableProperties: Property group.id is overridden to
17/05/07 15:32:08 INFO VerifiableProperties: Property zookeeper.connect is overridden to
-------------------------------------------
Time: 1494142328000 ms
-------------------------------------------
(WWW,44)
具体代码
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // scalastyle:off println /** * Created by hjw on 17/5/7. */ package com.dt.spark.main.Streaming.Kafka package com.dt.spark.main.Streaming.Kafka.org.apache.spark.examples.streaming import kafka.serializer.StringDecoder import org.apache.log4j.{Level, Logger} import org.apache.spark.{HashPartitioner, SparkConf} import org.apache.spark.streaming._ import org.apache.spark.streaming.kafka._ /** * Consumes messages from one or more topics in Kafka and does wordcount. * Usage: DirectKafkaWordCount <brokers> <topics> * <brokers> is a list of one or more Kafka brokers * <topics> is a list of one or more kafka topics to consume from * * Example: * $ bin/run-example streaming.DirectKafkaWordCount broker1-host:port,broker2-host:port \ * topic1,topic2 */ object DirectKafkaWordCount { ///函数常量定义,返回类型是Some(Int),表示的含义是最新状态 ///函数的功能是将当前时间间隔内产生的Key的value集合,加到上一个状态中,得到最新状态 val updateFunc = (values: Seq[Int], state: Option[Int]) => { val currentCount = values.sum val previousCount = state.getOrElse(0) Some(currentCount + previousCount) } ///入参是三元组遍历器,三个元组分别表示Key、当前时间间隔内产生的对应于Key的Value集合、上一个时间点的状态 ///newUpdateFunc的返回值要求是iterator[(String,Int)]类型的 val newUpdateFunc = (iterator: Iterator[(String, Seq[Int], Option[Int])]) => { ///对每个Key调用updateFunc函数(入参是当前时间间隔内产生的对应于Key的Value集合、上一个时间点的状态)得到最新状态 ///然后将最新状态映射为Key和最新状态 iterator.flatMap(t => updateFunc(t._2, t._3).map(s => (t._1, s))) } def main(args: Array[String]) { Logger.getLogger("org").setLevel(Level.ERROR) if (args.length < 2) { System.err.println(s""" |Usage: DirectKafkaWordCount <brokers> <topics> | <brokers> is a list of one or more Kafka brokers | <topics> is a list of one or more kafka topics to consume from | """.stripMargin) System.exit(1) } val Array(brokers, topics) = args // Create context with 2 second batch interval val sparkConf = new SparkConf().setAppName("DirectKafkaWordCount").setMaster("local[4]") val ssc = new StreamingContext(sparkConf, Seconds(2)) // Create direct kafka stream with brokers and topics val topicsSet = topics.split(",").toSet val kafkaParams = Map[String, String]("metadata.broker.list" -> brokers,"auto.offset.reset"->"smallest") val messages = KafkaUtils.createDirectStream[String, String, StringDecoder, StringDecoder]( ssc, kafkaParams, topicsSet) // Get the lines, split them into words, count the words and print val lines = messages.map(_._2) val words = lines.flatMap(_.split(" ")) val wordCounts = words.map(x => (x, 1L)).reduceByKey(_ + _) wordCounts.print() // updateStateByKey 计算包含"WWW"单次的出现次数 ssc.checkpoint("DirectKafkaWordCount-checkpoint") // Initial RDD input to updateStateByKey val initialRDD = ssc.sparkContext.parallelize(List(("WWW", 0))) val WWWwords = lines.filter(_.contains("WWW")).map(x=>("WWW",1)) val stateDstream = WWWwords.updateStateByKey[Int](newUpdateFunc, new HashPartitioner(ssc.sparkContext.defaultParallelism), true, initialRDD) stateDstream.print() // Start the computation ssc.start() ssc.awaitTermination() } } // scalastyle:on println