#SparkStream整合Flume有两种方式:
- 1:Flume采集数据后,把数据保存在Flume这段,然后SparkStream过来拉取数据。这种叫做Poll
- 2:Flume采集数据后,他数据推送给SparkStream,这种叫做Push 用的比较多的是第一种“Poll”
#Poll方式整合步骤
-
1、Flume安装在nginx之后,需要在它的lib文件夹下加上:
scala-library-2.10.5.jar commons-lang3-3.2.jar spark-streaming-flume-sink_2.10-1.6.1.jar
-
这三个jar包。尤其是最后那个spark-streaming-flume-sink_2.10-1.6.1.jar。就是利用它来创建一个socketServer。将数据保存在他的对象缓存中,等待SparkStreaming的程序过来拉取。
#flume的配置文件如下:
# Name the components on this agent
a1.sources = r1
a1.sinks = k1 k2
a1.channels = c1 c2
# source
a1.sources.r1.type = exec
a1.sources.r1.command = tail -F /home/hadoop/flume/logs/test.log
# Describe the sink
a1.sinks.k1.type = org.apache.spark.streaming.flume.sink.SparkSink
a1.sinks.k1.hostname = 192.168.56.204
a1.sinks.k1.port = 9999
a1.sinks.k2.type = logger
# Use a channel which buffers events in memory
a1.channels.c1.type = memory
a1.channels.c1.capacity = 1000
a1.channels.c1.transactionCapacity = 100
a1.channels.c2.type = memory
a1.channels.c2.capacity = 1000
a1.channels.c2.transactionCapacity = 100
# Bind the source and sink to the channel
a1.sources.r1.channels = c1 c2
a1.sources.r1.selector.type = replicating
a1.sinks.k1.channel = c1
a1.sinks.k2.channel = c2
#2、代码实现如下:
package com.liufu.org.streaming
import java.net.{InetAddress, InetSocketAddress}
import org.apache.spark.storage.StorageLevel
import org.apache.spark.{HashPartitioner, SparkConf}
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.streaming.flume.{FlumeUtils, SparkFlumeEvent}
/**
* Created by liufu on 2016/11/19.
*/
object Flume_SparkStream_Poll {
//定义一个累计函数,将以前的数据和现在的数据加起来,然后继续保持在checkpoint
val updateFunc = (it:Iterator[(String, Seq[Int],Option[Int])]) => {
it.map{case(x,y,z) => (x, y.sum + z.getOrElse(0))}
}
def main(args: Array[String]): Unit = {
val conf = new SparkConf().setAppName("streamTest").setMaster("local[2]")
//创建Streamingcomtext对象,然后指定处理数据的时间间隔
val ssc: StreamingContext = new StreamingContext(conf,Seconds(5))
//设置一个文件目录,用于保存以前数据。
ssc.checkpoint("file:///E:/checkpoint")
//读取Flume的数据。
val flumeStream: ReceiverInputDStream[SparkFlumeEvent] =
FlumeUtils.createPollingStream(ssc,Array(new InetSocketAddress("hadoop1",8888)),StorageLevel.MEMORY_AND_DISK)
//将flume的event数据中的body拿出来,组装成一个string,然后切割
val flatMap: DStream[String] = flumeStream.flatMap(msg =>{
new String(msg.event.getBody.array()).split(" ")})
val wordAndOne: DStream[(String, Int)] = flatMap.map((_,1))
val reduced: DStream[(String, Int)] = wordAndOne.updateStateByKey(updateFunc,new HashPartitioner(ssc.sparkContext.defaultParallelism),true)
reduced.print()
//一定要启动streamContext程序,然后一直等待,否则任务不会提交的。
ssc.start()
ssc.awaitTermination()
}
}
#总结:SparkStreaming从Flume那里拿到的数据是一个event,所以我们需要将他的body取出来,然后进行切割,形成DStream,最后进行统计。