自定义Source
将通过for循环的方式在造数据,并定义两个配置项,一个是有默认值,一个没有默认值,分别的对配置项进行测试。测试时的Flume为:自定义source+logger sink。
Java代码如下:
public class MySource extends AbstractSource implements Configurable, PollableSource {
// 定义全局的前缀和后缀
private String prefix;
private String suffix;
public void configure (Context context) {
// 读取配置信息,给前后缀赋值
// 前缀没有默认值
prefix = context.getString("prefix");
// 后缀有默认值,默认值为default-suffix
suffix = context.getString("suffix", "default-suffix");
}
/**
* 1、接受数据,我们这里通过for循环造数据
* 2、封装为事件
* 3、讲事件传给channel
*/
public Status process () throws EventDeliveryException {
Status status = null;
try {
// 1、接受数据
for (int i = 0; i < 5; i++) {
// 2、构建事件对象
SimpleEvent event = new SimpleEvent();
// 3、给事件设置body
event.setBody((prefix + "--" + i + "--" + suffix).getBytes());
// 4、将事件传给channel
/*
* processEvent方法执行过程
* 先走拦截器
* 再走channel selector
* 为被选择器选择的每个channel进行Put事务处理,如果Put出现异常,则进行回滚
*/
getChannelProcessor().processEvent(event);
status = Status.READY;
}
} catch (Exception e) {
e.printStackTrace();
status = Status.BACKOFF;
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return status;
}
public long getBackOffSleepIncrement () {
return 0;
}
public long getMaxBackOffSleepInterval () {
return 0;
}
}
将代码打包并上传到指定目录下。
配置文件内容如下:
# Name the components on this agent
a2.sources = r2
a2.sinks = k2
a2.channels = c2
# Describe/configure the source
a2.sources.r2.type = com.starnet.source.MySource
a2.sources.r2.prefix = hello
a2.sources.r2.suffix = word
# Describe the sink
a2.sinks.k2.type = logger
# 配置logger的最大字节数,默认是16
# a2.sinks.k2.maxBytesToLog = 50
# Use a channel which buffers events in memory
a2.channels.c2.type = memory
a2.channels.c2.capacity = 1000
a2.channels.c2.transactionCapacity = 100
# Bind the source and sink to the channel
a2.sources.r2.channels = c2
a2.sinks.k2.channel = c2
为prefix和suffix都配置了vlaue的运行结果如下:
将prefix和suffix配置都去掉,运行结果如下:
因为logger sink默认最长只有16字节,所以后面的被截断 了
可以将其配置成50,然后查看结果如下: