为了账号安全,请及时绑定邮箱和手机立即绑定

SparkStreaming 架构及案例实现

一、概述


        Spark Streaming类似于Apache Storm,用于流式数据的处理。根据其官方文档介绍,Spark Streaming有高吞吐量和容错能力强等特点。


        Spark Streaming支持的数据输入源很多,例如:Kafka、Flume、Twitter、ZeroMQ和简单的TCP套接字等等。数据输入后可以用Spark的高度抽象原语如:map、reduce、join、window等进行运算。而结果也能保存在很多地方,如HDFS,数据库等。另外Spark Streaming也能和MLlib(机器学习)以及Graphx完美融合。

二、SparkStreaming与Storm相比


Spark

Storm



开发语言:Scala

开发语言:Clojure

编程模型:DStream

编程模型:Spout/Bolt



3、DStream

Discretized Stream是Spark Streaming的基础抽象,代表持续性的数据流和经过各种Spark原语操作后的结果数据流。在内部实现上,DStream是一系列连续的RDD来表示。每个RDD含有一段时间间隔内的数据,如下图:


对数据的操作也是按照RDD为单位来进行的


计算过程由Spark engine来完成


从图中也能看出它将输入的数据分成多个batch进行处理,严格来说spark streaming 并不是一个真正的实时框架,因为他是分批次进行处理的。

4、DStreams相关操作

4.1、Transformations on DStreams


Transfor mation   

Meaning

map(func)

Return a new DStream by passing each  element of the source DStream through a function func.


flatMap(func)

Similar to map, but each input item can  be mapped to 0 or more output items.

filter(func)

Return a new DStream by selecting only  the records of the source DStream on which func returns true.

repartition(numPartitions)

Changes the level of parallelism in this  DStream by creating more or fewer partitions.

union(otherStream)

Return a new DStream that contains the  union of the elements in the source DStream and otherDStream.

count()

Return a new DStream of single-element  RDDs by counting the number of elements in each RDD of the source DStream.

reduce(func)

Return a new DStream of single-element  RDDs by aggregating the elements in each RDD of the source DStream using a  function func (which takes two arguments and returns one). The function  should be associative so that it can be computed in parallel.

countByValue()

When called on a DStream of elements of  type K, return a new DStream of (K, Long) pairs where the value of each key  is its frequency in each RDD of the source DStream.

reduceByKey(func, [numTasks])      

When called on a DStream of (K, V) pairs,  return a new DStream of (K, V) pairs where the values for each key are  aggregated using the given reduce function. Note: By default, this uses  Spark's default number of parallel tasks (2 for local mode, and in cluster  mode the number is determined by the config property  spark.default.parallelism) to do the grouping. You can pass an optional  numTasks argument to set a different number of tasks.

join(otherStream, [numTasks])

When called on two DStreams of (K, V) and  (K, W) pairs, return a new DStream of (K, (V, W)) pairs with all pairs of  elements for each key.

cogroup(otherStream, [numTasks])

When called on a DStream of (K, V) and  (K, W) pairs, return a new DStream of (K, Seq[V], Seq[W]) tuples.

transform(func)       

Return a new DStream by applying a  RDD-to-RDD function to every RDD of the source DStream. This can be used to  do arbitrary RDD operations on the DStream.

updateStateByKey(func)

Return a new "state" DStream  where the state for each key is updated by applying the given function on the  previous state of the key and the new values for the key. This can be used to  maintain arbitrary state data for each key.

特殊的Transformation


1.UpdateStateByKeyOperation

UpdateStateByKey原语用于记录历史记录,上文中Word Count示例中就用到了该特性。若不用UpdateStateByKey来更新状态,那么每次数据进来后分析完成后,结果输出后将不再保存

 

2.TransformOperation

Transform原语允许DStream上执行任意的RDD-to-RDD函数。通过该函数可以方便的扩展Spark API。此外,MLlib(机器学习)以及Graphx也是通过本函数来进行结合的。

 

3.WindowOperations

Window Operations有点类似于Storm中的State,可以设置窗口的大小和滑动窗口的间隔来动态的获取当前Steaming的允许状态(后面有代码案例)

4.2、  Output Operations on DStreams


        Output Operations可以将DStream的数据输出到外部的数据库或文件系统,当某个Output Operations原语被调用时(与RDD的Action相同),streaming程序才会开始真正的计算过程。

Output  Operation

Meaning

print()

Prints the first ten elements of every  batch of data in a DStream on the driver node running the streaming  application. This is useful for development and debugging.

saveAsTextFiles(prefix, [suffix])

Save this DStream's contents as text  files. The file name at each batch interval is generated based on prefix and  suffix: "prefix-TIME_IN_MS[.suffix]".

saveAsObjectFiles(prefix, [suffix])

Save this DStream's contents as  SequenceFiles of serialized Java objects. The file name at each batch  interval is generated based on prefix and suffix:  "prefix-TIME_IN_MS[.suffix]".

saveAsHadoopFiles(prefix, [suffix])

Save this DStream's contents as Hadoop  files. The file name at each batch interval is generated based on prefix and  suffix: "prefix-TIME_IN_MS[.suffix]".

foreachRDD(func)

The most generic output operator that  applies a function, func, to each RDD generated from the stream. This  function should push the data in each RDD to an external system, such as  saving the RDD to files, or writing it over the network to a database. Note  that the function func is executed in the driver process running the  streaming application, and will usually have RDD actions in it that will  force the computation of the streaming RDDs.

5、实战案例

首先我们需要再一台Linux端安装netCat工具, 可以使用yum安装

yum install -y nc

然后启动nc服务端并监听6666(自定义)端口


nc -lk 6666

架构图如下


netCat获取数据后由Client将数据发送到Server,再有Server发送至SparkStreaming,由于最终由Executor来处理数据,数据发送到Executor端,Executor端应至少有两个线程,一个Receiver负责接收数据,一个Executor用来执行和分析数据,所以在SparkConf处setMaster如果使用本地模式需要写为"local[2]"

5.1、使用SparkStreaming实现WordCount(未实现批次累加功能)

  1. import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}  

  2. import org.apache.spark.streaming.{Seconds, StreamingContext}  

  3. import org.apache.spark.{SparkConf, SparkContext}  

  4.   

  5. object SparkStreamingWordCount {  

  6.   def main(args: Array[String]): Unit = {  

  7.     val conf = new SparkConf()  

  8.       .setAppName("SparkStreamingWordCount")  

  9.       .setMaster("local[2]")  

  10.     val sc = new SparkContext(conf)  

  11.     // 创建SparkStreaming的上下文对象  

  12.     val ssc: StreamingContext = new StreamingContext(sc, Seconds(5))  

  13.   

  14.     // 获取NatCat服务的数据  

  15.     val dStream: ReceiverInputDStream[String] = ssc.socketTextStream("min1",6666)  

  16.   

  17.     // 分析数据  

  18.     val res: DStream[(String, Int)] = dStream.flatMap(_.split(" ")).map((_,1)).reduceByKey(_+_)  

  19.   

  20.     res.print()  

  21.   

  22.     // 提交任务  

  23.     ssc.start()  

  24.   

  25.     // 线程等待, 等待处理下一批次的任务  

  26.     ssc.awaitTermination()  

  27.   

  28.   }  

  29. }  

由上面可以发现,模板代码如下:

  1. val conf = new SparkConf()  

  2.   .setAppName("SparkStreamingWordCount")  

  3.   .setMaster("local[2]")  

  4. val sc = new SparkContext(conf)  

  5. // 创建SparkStreaming的上下文对象  

  6. val ssc: StreamingContext = new StreamingContext(sc, Seconds(5))  

  7.   

  8. // 获取NatCat服务的数据  

  9. val dStream: ReceiverInputDStream[String] = ssc.socketTextStream("min1",6666)  

此时通过控制台可以发现log4j会打印许多日志信息,此时我们可以使用下面代码调高输出级别,使控制台只打印结果

  1. import org.apache.log4j.{Logger, Level}  

  2. import org.apache.spark.Logging  

  3.   

  4. object LoggerLevels extends Logging {  

  5.   

  6.   def setStreamingLogLevels() {  

  7.     val log4jInitialized = Logger.getRootLogger.getAllAppenders.hasMoreElements  

  8.     if (!log4jInitialized) {  

  9.       logInfo("Setting log level to [WARN] for streaming example." +  

  10.         " To override add a custom log4j.properties to the classpath.")  

  11.       Logger.getRootLogger.setLevel(Level.WARN)  

  12.     }  

  13.   }  

  14. }  

此功能还可以使用Transform来实现,并调用上面的LoggerLevels类调高输出级别 

  1. import org.apache.spark.SparkConf  

  2. import org.apache.spark.streaming.dstream.DStream  

  3. import org.apache.spark.streaming.{Milliseconds, StreamingContext}  

  4.   

  5. object TransformDemo {  

  6.   def main(args: Array[String]): Unit = {  

  7.     LoggerLevels.setStreamingLogLevels()  

  8.     val conf = new SparkConf()  

  9.       .setAppName("TransformDemo")  

  10.       .setMaster("local[2]")  

  11.   

  12.     val ssc = new StreamingContext(conf,Milliseconds(5000))  

  13.   

  14.     // 设置检查点, 因为需要用检查点记录历史批次结果处理数据  

  15.     ssc.checkpoint("hdfs://min1:9000/cp-20180611-1")  

  16.   

  17.     // 获取数据  

  18.     val dStream = ssc.socketTextStream("min1",6666)  

  19.   

  20.     // 调用transform进行单词统计  

  21.     val res: DStream[(String, Int)] = dStream.transform(rdd => rdd.flatMap(_.split(" ")).map((_,1)).reduceByKey(_+_))  

  22.   

  23.     res.print()  

  24.     ssc.start()  

  25.     ssc.awaitTermination()  

  26.   

  27.   }  

  28.   

  29.   

  30. }  


5.2、使用updateStateByKey实现WordCount并实现批次累加功能

updateStateByKey 需要传三个参数:


        第一个参数: 需要一个具体操作数据的函数: 该函数的参数列表需要传进来一个迭代器

        Iterator中有三个类型, 分别代表:

            String: 代表元组中的key, 也就是一个个单词

            seq[Int]: 代表当前批次单词出现的次数, 相当于,Seq(1,1,1)

            Option[Int]: 代表上一批次累加的结果, 因为有可能有值, 也有可能没有值, 所以用Option来封装

        在获取Option里的值的时候, 最好用getOrElse, 这样可以给一个初始值

        第二个参数: 指定分区器

        第三个参数: 是否记录上一批次的分区信息

  1. import org.apache.spark.streaming.dstream.DStream  

  2. import org.apache.spark.{HashPartitioner, SparkConf}  

  3. import org.apache.spark.streaming.{Milliseconds, Seconds, StreamingContext}  

  4.   

  5. /**  

  6.   *  实现批次累加功能: updateStateByKey  

  7.   */  

  8. object SparkStreamingACCWC {  

  9.   def main(args: Array[String]): Unit = {  

  10.     LoggerLevels.setStreamingLogLevels()  

  11.     val conf = new SparkConf()  

  12.       .setAppName("SparkStreamingACCWC")  

  13.       .setMaster("local[2]")  

  14.   

  15.     val ssc = new StreamingContext(conf,Seconds(5))  

  16.   

  17.     // 设置检查点, 因为需要用检查点记录历史批次结果处理数据  

  18.     ssc.checkpoint("hdfs://min1:9000/cp-20180611-1")  

  19.   

  20.     // 获取数据  

  21.     val dStream = ssc.socketTextStream("192.168.158.115",6666)  

  22.   

  23.     // 分析数据  

  24.     val tuples = dStream.flatMap(_.split(" ")).map((_,1))  

  25.   

  26.     val res: DStream[(String, Int)] =   

  27.       tuples.updateStateByKey(func, new HashPartitioner(ssc.sparkContext.defaultParallelism),true)//defaultParallelism 并行数(也就是分区数)  

  28.     res.print()  

  29.     ssc.start()  

  30.     ssc.awaitTermination()  

  31.   

  32.   

  33.   }  

  34.   

  35.   /**  

  36.     * updateStateByKey 需要传三个参数:  

  37.     * 第一个参数: 需要一个具体操作数据的函数: 该函数的参数列表需要传进来一个迭代器  

  38.     * Iterator中有三个类型, 分别代表:  

  39.     *       String: 代表元组中的key, 也就是一个个单词  

  40.     *       seq[Int]: 代表当前批次单词出现的次数, 相当于,Seq(1,1,1)  

  41.     *       Option[Int]: 代表上一批次累加的结果, 因为有可能有值, 也有可能没有值, 所以用Option来封装  

  42.     *       在获取Option里的值的时候, 最好用getOrElse, 这样可以给一个初始值  

  43.     * 第二个参数: 指定分区器  

  44.     * 第三个参数: 是否记录上一批次的分区信息  

  45.     */  

  46.   val func = (it: Iterator[(String, Seq[Int], Option[Int])])  => {  

  47.         it.map(x => {  

  48.           (x._1, x._2.sum + x._3.getOrElse(0))  

  49.         })  

  50.   }  

  51. }  

实现批次累加功能的模板代码如下

  1. LoggerLevels.setStreamingLogLevels()  

  2.    val conf = new SparkConf()  

  3.      .setAppName("SparkStreamingACCWC")  

  4.      .setMaster("local[2]")  

  5.   

  6.    val ssc = new StreamingContext(conf,Seconds(5))  

  7.   

  8.    // 设置检查点, 因为需要用检查点记录历史批次结果处理数据  

  9.    ssc.checkpoint("hdfs://min1:9000/cp-20180611-1")  

  10.   

  11.    // 获取数据  

  12.    val dStream = ssc.socketTextStream("192.168.158.115",6666)  


5.3、通过Kafka来获取数据来实现WordCount

需要启动zookeeper及kafka

  1. import org.apache.spark.{HashPartitioner, SparkConf}  

  2. import org.apache.spark.storage.StorageLevel  

  3. import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}  

  4. import org.apache.spark.streaming.kafka.KafkaUtils  

  5. import org.apache.spark.streaming.{Milliseconds, StreamingContext}  

  6.   

  7. object LoadKafkaDataAndWordCount {  

  8.   def main(args: Array[String]): Unit = {  

  9.     LoggerLevels.setStreamingLogLevels()  

  10.     val conf = new SparkConf()  

  11.       .setAppName("SparkStreamingACCWC")  

  12.       .setMaster("local[2]")  

  13.   

  14.     val ssc = new StreamingContext(conf,Milliseconds(5000))  

  15.   

  16.     // 设置检查点, 因为需要用检查点记录历史批次结果处理数据  

  17.     ssc.checkpoint("hdfs://min1:9000/cp-20180611-3")  

  18.   

  19.     // 设置请求kafka的几个必要参数  

  20.     val Array(zkQuorum, group, topics, numThread) = args // zk列表, 消费者组名, 多个topics, topic中的线程数  

  21.   

  22.     // 获取每个topic放到Map里  

  23.     val topicMap: Map[String, Int] = topics.split(",").map((_,numThread.toInt)).toMap  

  24.   

  25.     // 调用kafka工具类来获取kafka集群的数据, 其中key为数据的offset值, value就是数据  

  26.     val data: ReceiverInputDStream[(String, String)] = KafkaUtils.createStream(ssc, zkQuorum, group, topicMap, StorageLevel.MEMORY_AND_DISK)  

  27.   

  28.     // 把offset值过滤掉  

  29.   

  30.     val lines: DStream[String] = data.map(_._2)  

  31.   

  32.     //分析数据  

  33.     val tuples: DStream[(String, Int)] = lines.flatMap(_.split(" ")).map((_,1))  

  34.     val res: DStream[(String, Int)] = tuples.updateStateByKey(func, new HashPartitioner(ssc.sparkContext.defaultParallelism),true)  

  35.   

  36.     res.print()  

  37.   

  38.     ssc.start()  

  39.     ssc.awaitTermination()  

  40.   

  41.   }  

  42.   val func = (it: Iterator[(String, Seq[Int], Option[Int])]) => {  

  43.     it.map{  

  44.       case (x,y,z) => {  

  45.         (x, y.sum + z.getOrElse(0))  

  46.       }  

  47.     }  

  48.   }  

此时通过Kafka的shell命令发送消息,控制台会打印出WordCount结果

6、关于Window Operations窗口操作


窗口操作指的是, 一段时间内数据发送的变化


我们在操作窗口函数是需要传入两个重要的参数:

窗口长度(window length): 代表窗口的持续时间, 也就是指窗口展示的结果数据的范围

滑动间隔(sliding interval): 代表执行窗口操作的间隔, 也就是展示的结果范围之间的时间间隔

这两个参数必须是源DStream批次间隔的倍数

使用窗口函数实现WordCount

  1. import org.apache.spark.{SparkConf, SparkContext}  

  2. import org.apache.spark.streaming.{Seconds, StreamingContext}  

  3. import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}  

  4.   

  5. object WindowOperationWordCount {  

  6.   def main(args: Array[String]): Unit = {  

  7.     LoggerLevels.setStreamingLogLevels()  

  8.     val conf = new SparkConf()  

  9.       .setAppName("WindowOperationWordCount")  

  10.       .setMaster("local[2]")  

  11.   

  12.     val ssc = new StreamingContext(conf,Seconds(5))  

  13.   

  14.     // 设置检查点, 因为需要用检查点记录历史批次结果处理数据  

  15.     ssc.checkpoint("hdfs://min1:9000/cp-20180611-5")  

  16.   

  17.     // 获取数据  

  18.     val dStream = ssc.socketTextStream("192.168.158.115",6666)  

  19.   

  20.     val tuples = dStream.flatMap(_.split(" ")).map((_,1))  

  21.   

  22.     val res: DStream[(String, Int)] = tuples.reduceByKeyAndWindow((x: Int, y: Int) => (x + y),Seconds(10), Seconds(10))  

  23.   

  24.     res.print()  

  25.   

  26.     ssc.start()  

  27.     ssc.awaitTermination()  

  28.   

  29.   

  30.   }  

  31. }  


以上是SparkStreaming 架构及实现案例,pom文件中的Maven依赖如果不知道使用哪个可以留言或联系我~

原文出处

点击查看更多内容
2人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消