由于平台的不稳定性,小时解析日志老是出错需要人为干涉。最近在想能不能通过flink实时解析日志入库。查了一下网上的资料可以使用BucketingSink来将数据写入到HDFS上。于是想根据自定义文件目录来实行多目录写入。
添加pom依赖`
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-connector-filesystem_2.11</artifactId>
<version>1.5.3</version>
</dependency>
代码
package com.hfut
import org.apache.flink.api.java.tuple.Tuple2
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment
import org.apache.flink.streaming.api.windowing.assigners.{TumblingEventTimeWindows, TumblingProcessingTimeWindows}
import org.apache.flink.streaming.api.windowing.time.Time
import org.apache.flink.streaming.connectors.fs.Clock
import org.apache.flink.streaming.connectors.fs.bucketing.{Bucketer, BucketingSink}
import org.apache.hadoop.fs.Path
object SocketWindowWordCount {
def main(args: Array[String]) : Unit = {
// get the execution environment
val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment
// get input data by connecting to the socket
val text = env.socketTextStream("localhost", 9000, '\n')
// parse the data, group it, window it, and aggregate the counts
val windowCounts = text
.flatMap { w => w.split("\\s") }
.map { w => WordWithCount(w, 1) }
.keyBy(_.word)
.window(TumblingProcessingTimeWindows.of(Time.seconds(10)))
.reduce{(v1,v2)=>WordWithCount(v1.word,v1.count+v2.count)}
// print the results with a single thread, rather than in parallel
val sink=new BucketingSink[WordWithCount]("D:\\data")
sink.setBucketer(new Bucketer[WordWithCount] {
override def getBucketPath(clock: Clock, path: Path, t: WordWithCount): Path =
new Path(path+"/"+t.word)
})
sink.setBatchSize(1024)
windowCounts.addSink(sink)
//windowCounts.print().setParallelism(1)
env.execute("Socket Window WordCount")
}
// Data type for words with count
case class WordWithCount(word: String, count: Long)
}
结果
默认情况下分桶sink是通过元素到达的系统时间来进行切分的,并用"yyyy-MM-dd HH"的时间格式来命名桶,这个时间格式与当前的系统时间传入SimpleDateFormat来形成一个桶的路径,当遇到一个新的时间后就会创建一个新的桶。例如:如果你有一个以分钟作为最细粒度的模式,那么你将每分钟获得一个新的分桶。每个分桶本身是一个包含若干分区文件的目录,每个并行的sink实例会创建它自己的分区文件,当分区文件过大时,sink会紧接着其它分区文件创建一个新的分区文件。当一个桶变成非活跃状态时,打开的文件会被刷新和关闭,当一个桶不再被写入时,会被认为是非活跃的。默认情况下,sink会每分钟检查一遍是否非活跃,并关闭超过一分钟没有数据写入的分桶,这种行为可以通过在BucketingSink的setInactiveBucketCheckInterval() 和 setInactiveBucketThreshold()来配置,本例中用setBucketer()来指定一个自定义的bucketer,使用元素或者元组的属性来决定bucketer的目录。
注意:超过一分钟没有数据写入分桶这句话,这样在当前目录下会产生很多pending文件。这对NameNode是很大的压力。上面说通过设置InactiveBucketCheckInterval,InactiveBucketThreshold()
其中setInactiveBucketCheckInterval,InactiveBucketThreshold,batchRolloverInterval都是通过增加触发时间间隔来实现的,而且都跟bucketStates有关
网上也有人说通过调整batchSize大小(默认384M),相对而言384M还是蛮大的。这个参数还是受制于batchRolloverInterval