二、Pull方式整合
又稱:基於Pull的方式使用自定義的sink。
和第一種直接Push數據到Spark Streaming 的方式相反,Pull方式就是SparkStreaming從Flume裏進行數據的拉取,這種方式會自定義個Flume Sink,遵循如下幾個步驟:
1. Flume 把數據Push到一個sink 裏後,數據先存放在一個緩存中。
2. Spark Streaming使用一個可靠的Flume receiver,然後用事務的方式從sink裏把數據拉過來,這個事務僅僅在當你的數據被Spark Streaming接收到,並且多副本的條件下,這個事務才成功。
第二種方式的可靠性和容錯性比Push要好很多,所以生產環境優先考慮到Pull方式。Pull方式需要配置Flume,然後把數據收集過來後運行到一個自定義的sink裏。步驟如下:
1.General Requirements
選擇一臺機器,運行Flume agent中的自定義sink,然後Flume其他一些管道的數據,可以把數據發送到所選擇的這個agent上面來,即Spark集羣上面的機器是有權限訪問被選擇運行自定義sink的這臺機器。
配置Flume
1. 添加相關依賴:
groupId = org.apache.spark
artifactId = spark-streaming-flume-sink_2.11
version = 2.2.0
groupId = org.scala-lang
artifactId = scala-library
version = 2.11.8
groupId = org.apache.commons
artifactId = commons-lang3
version = 3.5
2.Flume的配置文件:
agent.sinks = spark
agent.sinks.spark.type = org.apache.spark.streaming.flume.sink.SparkSink
agent.sinks.spark.hostname = <hostname of the local machine>
agent.sinks.spark.port = <port to listen on for connection from Spark>
agent.sinks.spark.channel = memoryChannel
配置Spark Streaming的應用
1.依賴
應用上面的依賴關係即可,其中要注意導入FlumeUtil這個類,並且用到的是createPollingStream這個方法,而不是Push方式中的createStream方法
import org.apache.spark.streaming.flume._
val flumeStream = FlumeUtils.createPollingStream(streamingContext, [sink machine hostname], [sink port])
2.編碼
注意:每個輸入的DStream 可以接收多個sinks裏的數據
import org.apache.spark.SparkConf
import org.apache.spark.streaming.flume.FlumeUtils
import org.apache.spark.streaming.{Seconds, StreamingContext}
/**
* Spark Streaming整合Flume的第二種方式
*/
object FlumePullWordCount {
def main(args: Array[String]): Unit = {
if(args.length != 2) {
System.err.println("Usage: FlumePullWordCount <hostname> <port>")
System.exit(1)
}
val Array(hostname, port) = args
val sparkConf = new SparkConf() //.setMaster("local[2]").setAppName("FlumePullWordCount")
val ssc = new StreamingContext(sparkConf, Seconds(5))
//TODO... 如何使用SparkStreaming整合Flume
val flumeStream = FlumeUtils.createPollingStream(ssc, hostname, port.toInt)
flumeStream.map(x=> new String(x.event.getBody.array()).trim)
.flatMap(_.split(" ")).map((_,1)).reduceByKey(_+_).print()
ssc.start()
ssc.awaitTermination()
}
}
3.提交部署
同Push方式,但是此處要注意的是:先啓動flume 後啓動Spark Streaming應用程序
啓動Flume:
flume-ng agent \
--name simple-agent \
--conf $FLUME_HOME/conf \
--conf-file $FLUME_HOME/conf/flume_pull_streaming.conf \
-Dflume.root.logger=INFO,console
spark submit提交:
spark-submit \
--class com.imooc.spark.FlumePullWordCount \
--master local[2] \
--packages org.apache.spark:spark-streaming-flume_2.11:2.2.0 \
/home/hadoop/lib/sparktrain-1.0.jar \
hadoop000 41414
官網地址:http://spark.apache.org/docs/latest/streaming-flume-integration.html#general-requirements-1