需求
每隔五秒输出5次数据
pom文件
<dependencies>
<dependency>
<groupId>org.apache.flume</groupId>
<artifactId>flume-ng-core</artifactId>
<version>1.9.0</version>
</dependency>
</dependencies>
代码
package com.longer.source;
import org.apache.flume.Context;
import org.apache.flume.EventDeliveryException;
import org.apache.flume.PollableSource;
import org.apache.flume.conf.Configurable;
import org.apache.flume.event.SimpleEvent;
import org.apache.flume.source.AbstractSource;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
public class MySource extends AbstractSource implements Configurable, PollableSource {
//定义配置文件将来要读取的字段
private String pre;
private String tail;
private Long delay;
//初始化配置信息
@Override
public void configure(Context context) {
pre=context.getString("pre");
tail=context.getString("tail","-tail");
delay=context.getLong("delay",5000L);
}
@Override
public Status process() throws EventDeliveryException {
try {
//创建事件头信息
HashMap<String, String> headerMap = new HashMap<>();
//循环封装事件
for (int i = 0; i < 5; i++) {
//创建事件
SimpleEvent simpleEvent = new SimpleEvent();
//给事件设置头信息
simpleEvent.setHeaders(headerMap);
//给事件设置内容
simpleEvent.setBody((pre + i + tail).getBytes(StandardCharsets.UTF_8));
//讲事件写入channel
getChannelProcessor().processEvent(simpleEvent);
}
Thread.sleep(delay);
}catch (Exception e){
e.printStackTrace();
return Status.BACKOFF;
}
return Status.READY;
}
@Override
public long getBackOffSleepIncrement() {
return 0;
}
@Override
public long getMaxBackOffSleepInterval() {
return 0;
}
}
flume
# Name the components on this agent
a1.sources = r1
a1.sinks = k1
a1.channels = c1
# Describe/configure the source
a1.sources.r1.type = com.longer.source.MySource
a1.sources.r1.pre = longer
a1.sources.r1.tail = short
# Describe the sink
a1.sinks.k1.type=logger
# 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
启动
bin/flume-ng agent --conf conf/ --name a1 --conf-file job/group5/flume.conf -Dflume.root.logger=INFO,console