文章目录
6、自定义 Source
1)介绍
- Source是负责接收数据到Flume Agent的组件。Source组件可以处理各种类型、各种格式的日志数据,包括avro、thrift、exec、jms、spooling directory、netcat、sequence generator、syslog、http、legacy。官方提供的 source 类型已经很多,但是有时候并不能满足实际开发当中的需求,此时我们就需要根据实际需求自定义某些 source。
- 官方也提供了自定义 source 的接口:
- https://flume.apache.org/FlumeDeveloperGuide.html#source根据官方说明自定义MySource需要继承 AbstractSource 类并实现 Configurable 和 PollableSource 接口。
- 实现相应方法:
- getBackOffSleepIncrement()//暂不用
- getMaxBackOffSleepInterval()//暂不用
- configure(Context context)//初始化context(读取配置文件内容)
- process()//获取数据封装成 event 并写入 channel,这个方法将被循环调用。
- 使用场景:读取MySQL数据或者其他文件系统。
2)需求
- 使用flume接收数据,并给每条数据添加 前缀,输出到控制台。前缀可从 flume 配置文件中配置。
3)分析
4)编码
(1)导入pom依赖
<dependencies>
<dependency>
<groupId>org.apache.flume</groupId>
<artifactId>flume-ng-core</artifactId>
<version>1.9.0</version>
</dependency>
</dependencies>
(2)编写代码
public class MySource extends AbstractSource implements Configurable, PollableSource {
//定义一个全局的前缀后缀
private String prefix;
private String suffix;
//接受数据得到主要逻辑
/**
* 使用for循环生产数据
* 给数据加上前缀后缀,并且是以配置文件传进来
* @return
* @throws EventDeliveryException
*/
@Override
public Status process() throws EventDeliveryException {
//1、定义状态
Status status = null;
try {
//利用for循环生产数据
for (int i = 0; i < 5; i++) {
SimpleEvent event = new SimpleEvent();
event.setBody((prefix + "-"+ i +"-" + suffix).getBytes());
getChannelProcessor().processEvent(event);
Thread.sleep(2000);
}
status = Status.READY;
} catch (Exception e) {
e.printStackTrace();
status=Status.BACKOFF;
}
return status;
}
//获取source退避的增长值
@Override
public long getBackOffSleepIncrement() {
return 0;
}
//获取source退避的最大增长值
@Override
public long getMaxBackOffSleepInterval() {
return 0;
}
//可以获取配置信息
@Override
public void configure(Context context) {
prefix = context.getString("prefix");
suffix = context.getString("suffix", "xiyouji");
}
}
5)测试
(1)打包
- 将写好的代码打包,并放到flume的lib目录(/opt/module/flume-1.9.0)下。
(2)配置文件
[xiaoxq@hadoop105 jobs]$ pwd
/opt/module/flume-1.9.0/jobs
[xiaoxq@hadoop105 jobs]$ vim myselfsource.conf
- 添加如下内容
# Name the components on this agent
a2.sources = r1
a2.sinks = k1
a2.channels = c1
# Describe/configure the source
a2.sources.r1.type = com.xiaoxq.source.MySource
a2.sources.r1.prefix = qian
a2.sources.r1.suffix = hou
# Describe the sink
a2.sinks.k1.type = logger
# Use a channel which buffers events in memory
a2.channels.c1.type = memory
a2.channels.c1.capacity = 1000
a2.channels.c1.transactionCapacity = 100
# Bind the source and sink to the channel
a2.sources.r1.channels = c1
a2.sinks.k1.channel = c1
(3)开启任务
[xiaoxq@hadoop105 flume-1.9.0]$ pwd
/opt/module/flume-1.9.0
[xiaoxq@hadoop105 flume-1.9.0]$ bin/flume-ng agent -c conf/ -f jobs/myselfsource.conf -n a2 -Dflume.root.logger=INFO,console
(4)结果展示