介绍
Sink不断地轮询Channel中的事件且批量地移除它们,并将这些事件批量写入到存储或索引系统、或者被发送到另一个Flume Agent。
Sink是完全事务性的。在从Channel批量删除数据之前,每个Sink用Channel启动一个事务。批量事件一旦成功写出到存储系统或下一个Flume Agent,Sink就利用Channel提交事务。事务一旦被提交,该Channel从自己的内部缓冲区删除事件。
Sink组件目的地包括hdfs、logger、avro、thrift、ipc、file、null、HBase、solr、自定义。官方提供的Sink类型已经很多,但是有时候并不能满足实际开发当中的需求,此时我们就需要根据实际需求自定义某些Sink。
官方也提供了自定义sink的接口:
https://flume.apache.org/FlumeDeveloperGuide.html#sink根据官方说明自定义MySink需要继承AbstractSink类并实现Configurable接口。
实现相应方法:
configure(Context
context)//初始化context(读取配置文件内容)
process()//从Channel读取获取数据(event),这个方法将被循环调用。
使用场景:读取Channel数据写入MySQL或者其他文件系统。
开发实例
1、创建Maven,添加依赖
https://blog.csdn.net/qq_42502354/article/details/105938029
2、编写代码
package com.caron.flume.sink;
import org.apache.flume.*;
import org.apache.flume.conf.Configurable;
import org.apache.flume.sink.AbstractSink;
import java.io.IOException;
/**
* @author Caron
* @create 2020-05-05-21:56
* @Description
* @Version
*/
public class MySink extends AbstractSink implements Configurable {
public void configure(Context context) {
}
/**
* 该方法调用时,回从channel中拉取数据并处理
* @return 处理的状态
* @throws EventDeliveryException
*/
public Status process() throws EventDeliveryException {
Status status = null;
// 开启事务
Channel ch = getChannel();
Transaction txn = ch.getTransaction();
txn.begin();
try {
// 拉取数据
Event event;
while ((event = ch.take()) == null){
Thread.sleep(100);
}
//如果成功获取数据
storeSomeData(event);
// Send the Event to the external repository.
// storeSomeData(e);
txn.commit();
status = Status.READY;
} catch (Throwable t) {
txn.rollback();
// Log exception, handle individual exceptions as needed
status = Status.BACKOFF;
// re-throw all Errors
if (t instanceof Error) {
throw (Error)t;
}
}finally {
txn.close();
}
return status;
}
/**
* 储存数据
* @param event
*/
private void storeSomeData(Event event) throws IOException {
//将数据打印到控制台
byte[] body = event.getBody();
System.out.write(body);
System.out.println();
}
}
3、打包
将写好的代码打包,并放到flume的lib目录(/opt/module/flume)下
4、配置文件
# Name the components on this agent
a1.sources = r1
a1.sinks = k1
a1.channels = c1
# Describe/configure the source
a1.sources.r1.type = netcat
a1.sources.r1.bind = 0.0.0.0
a1.sources.r1.port = 44444
# Describe the sink
a1.sinks.k1.type = com.caron.flume.sink.MySink
#a1.sinks.k1.prefix = caron-
#a1.sinks.k1.suffix = :caron-
# Use a channel which buffers events in memory
a1.channels.c1.type = memory
a1.channels.c1.capacity = 1000
a1.channels.c1.transactionCapacity = 100
# Bind the source and sink to the channel
a1.sources.r1.channels = c1
a1.sinks.k1.channel = c1
5、开启任务
bin/flume-ng agent -n a1 -c conf/ -f job/mysink/sink.conf -Dflume.root.logger=INFO,console
6、测试
nc localhost 44444
结果: