Flink使用BucketingSink自定义多目录写入

由于平台的不稳定性,小时解析日志老是出错需要人为干涉。最近在想能不能通过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

在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
如果你想使用 Flink 批量将数据写入 HBase,可以自定义一个 HBaseSinkFunction。下面是一个简单的示例: ```java public class HBaseBatchSinkFunction extends RichSinkFunction<List<Tuple2<String, String>>> { private transient Connection connection; private transient BufferedMutator bufferedMutator; @Override public void open(Configuration parameters) throws Exception { Configuration config = HBaseConfiguration.create(); config.set("hbase.zookeeper.quorum", "localhost"); config.set("hbase.zookeeper.property.clientPort", "2181"); config.set("zookeeper.znode.parent", "/hbase"); config.set("hbase.client.write.buffer", "10000000"); config.set("hbase.client.retries.number", "3"); connection = ConnectionFactory.createConnection(config); TableName tableName = TableName.valueOf("my_table"); BufferedMutatorParams params = new BufferedMutatorParams(tableName); params.writeBufferSize(1024 * 1024); bufferedMutator = connection.getBufferedMutator(params); } @Override public void invoke(List<Tuple2<String, String>> values, Context context) throws Exception { List<Put> puts = new ArrayList<>(); for (Tuple2<String, String> value : values) { Put put = new Put(Bytes.toBytes(value.f0)); put.addColumn(Bytes.toBytes("my_cf"), Bytes.toBytes("my_col"), Bytes.toBytes(value.f1)); puts.add(put); } bufferedMutator.mutate(puts); } @Override public void close() throws Exception { if (bufferedMutator != null) { bufferedMutator.flush(); bufferedMutator.close(); } if (connection != null) { connection.close(); } } } ``` 在这个自定义的 HBaseSinkFunction 中,我们使用 BufferedMutator 批量写入数据。在 open() 方法中,我们获取 HBase 连接和缓冲器。在 invoke() 方法中,我们将数据转换为 Put 对象,并添加到缓冲器中。最后,在 close() 方法中,我们刷新缓冲器并关闭连接。 在你的 Flink 程序中,你可以使用这个自定义的 HBaseSinkFunction,例如: ```java DataStream<Tuple2<String, String>> dataStream = ...; dataStream.addSink(new HBaseBatchSinkFunction()); ``` 这样,你就可以批量将数据写入 HBase 了。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值