1.1.自定義Sink說明
sink是flume中用于指定數(shù)據(jù)下沉地的組件曹傀。自帶的已經(jīng)很多辐脖,對于某些sink如果沒有我們想要的,也可以自定義sink實現(xiàn)將數(shù)據(jù)保存到我們想要的地方去皆愉,例如kafka嗜价,或者mysql,或者文件等等都可以
需求如下:從網(wǎng)絡(luò)端口當(dāng)中發(fā)送數(shù)據(jù)幕庐,自定義sink久锥,使用sink從網(wǎng)絡(luò)端口接收數(shù)據(jù),然后將數(shù)據(jù)保存到本地文件當(dāng)中去翔脱。
1.2.自定義Sink原理實現(xiàn)
自定義MySink
public class MySink extends AbstractSink implements Configurable {
private Context context ;
private String filePath = "";
private String fileName = "";
private File fileDir;
//這個方法會在初始化調(diào)用奴拦,主要用于初始化我們的Context,獲取我們的一些配置參數(shù)
@Override
public void configure(Context context) {
try {
this.context = context;
filePath = context.getString("filePath");
fileName = context.getString("fileName");
fileDir = new File(filePath);
if(!fileDir.exists()){
fileDir.mkdirs();
}
} catch (Exception e) {
e.printStackTrace();
}
}
//這個方法會被反復(fù)調(diào)用
@Override
public Status process() throws EventDeliveryException {
Event event = null;
Channel channel = this.getChannel();
Transaction transaction = channel.getTransaction();
transaction.begin();
while(true){
event = channel.take();
if(null != event){
break;
}
}
byte[] body = event.getBody();
String line = new String(body);
try {
FileUtils.write(new File(filePath+File.separator+fileName),line,true);
transaction.commit();
} catch (IOException e) {
transaction.rollback();
e.printStackTrace();
return Status.BACKOFF;
}finally {
transaction.close();
}
return Status.READY;
}
}
1.3 功能測試
將代碼使用打包插件届吁,打成jar包错妖,注意一定要將commons-langs這個依賴包打進去,放到flume的lib目錄下
開發(fā)flume的配置文件:
a1.sources = r1
a1.sinks = k1
a1.channels = c1
# Describe/configure the source
a1.sources.r1.type = netcat
a1.sources.r1.bind = node-1
a1.sources.r1.port = 5678
a1.sources.r1.channels = c1
# # Describe the sink
a1.sinks.k1.type = cn.itcast.flumesink.MySink
a1.sinks.k1.filePath=/export/servers
a1.sinks.k1.fileName=filesink.txt
# # 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
1.4啟動flume疚沐,并且使用telnet測試:
bin/flume-ng agent -c conf -f conf/filesink.conf -n a1 -Dflume.root.logger=INFO,console
Telnet node-1 5678 連接到機器端口上輸入數(shù)據(jù)暂氯。