Flume中自定义Source和自定义Sink

自定义Source

Source是负责接收数据到Flume Agent的组件。Source组件可以处理各种类型、各种格式的日志数据,包括avro、thrift、exec、jms、spooling directory、netcat、sequence generator、syslog、http、legacy。官方提供的source类型已经很多,但是有时候并不能满足实际开发当中的需求,此时我们就需要根据实际需求自定义某些source。
根据官方说明自定义MySource需要继承AbstractSource类并实现Configurable和PollableSource接口。

需求:使用flume接收数据,并给每条数据添加前缀,
    输出到控制台。前缀可从flume配置文件中配置。
    创建maven module,加入依赖
    <dependencies>
    <dependency>
        <groupId>org.apache.flume</groupId>
        <artifactId>flume-ng-core</artifactId>
        <version>1.9.0</version>
</dependency>

</dependencies>  
import org.apache.flume.Context;
import org.apache.flume.Event;
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;

/**
 * 用for循环去模拟生产数据
 * 然后通过配置文件的方式将这个时间的body加上前缀和后缀
 */

public class Mysource extends AbstractSource implements Configurable, PollableSource {
    private String prefis;
    private String suffix;

    //负责接收数据的具体逻辑
    @Override
    public Status process() throws EventDeliveryException {
        Status status = null;
        try {
            for (int i = 0; i < 5; i++) {
                SimpleEvent event = new SimpleEvent();
                event.setBody((prefis + "===" + i + "====" + suffix).getBytes());
                getChannelProcessor().processEvent(event);
                Thread.sleep(2000);
            }
            status=Status.READY;
        } catch (Exception e) {
            e.printStackTrace();
            status = Status.BACKOFF;
        }
        return status;
    }

    @Override
    public long getBackOffSleepIncrement() {
        return 0;
    }

    @Override
    public long getMaxBackOffSleepInterval() {
        return 0;
    }

    @Override
    public void configure(Context context) {
        prefis = context.getString("prefix");
        suffix = context.getString("suffix", "biedata");
    }

测试:将写好的代码打包,放到flume/lib/下。
修改配置文件:在flume/job 下 vim Mysource-flume-logger.conf
添加如下配置文件:

# Name the components on this agent
a2.sources = r1 
a2.sinks = k1
a2.channels = c1 

# Describe/configure the source
a2.sources.r1.type =  MySource的绝对路径
a2.sources.r1.prefix = qianzhui
a2.sources.r1.suffix = houzhui

# 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 

观察测试结果:每2s会打印数据到控制台

自定义Sink

Sink不断地轮询Channel中的事件且批量地移除它们,并将这些事件批量写入到存储或索引系统、或者被发送到另一个Flume Agent。
Sink是完全事务性的。在从Channel批量删除数据之前,每个Sink用Channel启动一个事务。批量事件一旦成功写出到存储系统或下一个Flume Agent,Sink就利用Channel提交事务。事务一旦被提交,该Channel从自己的内部缓冲区删除事件。
根据官方说明自定义MySink需要继承AbstractSink类并实现Configurable接口。

需求:使用flume接收数据,并在Sink端给每条数据添加前缀和后缀,
输出到控制台。前后缀可在flume任务配置文件中配置。
import org.apache.flume.*;
import org.apache.flume.conf.Configurable;
import org.apache.flume.sink.AbstractSink;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 通过logger4j的方式打印数据
 * 通过配置文件将传送过来的数据加点前缀和后缀
 */
public class MySink extends AbstractSink implements Configurable {
    //定义的前缀后缀
    private String prefix;
    private String suffix;
    //定义全局的logger对象
    private Logger logger = LoggerFactory.getLogger(MySink.class);
    @Override
    //sink往外写数据的逻辑
    public Status process() throws EventDeliveryException {

        //1.定义状态
        Status status=null;
        //2.获取与sink绑定的channel
        Channel channel = getChannel();
        //3.从channel获取事务
        Transaction transaction = channel.getTransaction();
        //4.开始事务
        transaction.begin();
        try {
            //5.从channnel拿数据
            Event event = channel.take();
            //6.判断当前的这个event是不是为null
            if (event!=null){
                //7.通过logger打印日志(这个是将数据往外写的逻辑)
                logger.info( prefix+"-->"+new String(event.getBody())+"<--"+suffix);
            }
            //8.把事务提交
            transaction.commit();
            //9.将准备好的状态返回
            status=Status.READY;
        }catch (Exception e){
            e.printStackTrace();
            //10.将退避的状态放回
            status=Status.BACKOFF;
            //11.将事务回滚
            transaction.rollback();
        }finally {
            //12.关闭事务
            transaction.close();
        }
        return status;
    }

    @Override
    public void configure(Context context) {
    prefix=context.getString("aaa");
    suffix=context.getString("suffix", "abc");
    }
}

测试:将写好的代码打包,放到flume/lib/下。
添加配置文件:

# Name the components on this agent
a2.sources = r1 
a2.sinks = k1
a2.channels = c1 

# Describe/configure the source
a2.sources.r1.type = netcat
a2.sources.r1.bind = localhost
a2.sources.r1.port = 44444

# Describe the sink
a2.sinks.k1.type = MySink的绝对路径
a2.sinks.k1.aaa = qianzhui


# 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 

观察结果即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Flume是一个分布式、可靠、可扩展的日志收集、聚合、传输系统。它使用拦截器来处理数据流,可以在数据流经过某个拦截器时对数据进行预处理、过滤、转换等操作。 下面给出一个自定义Flume拦截器,用于将数据转换为JSON格式。该拦截器可以将文本数据转换为JSON格式,并添加时间戳和其他元数据,方便后续处理和分析。 ```java package com.example.flume.interceptor; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.flume.Context; import org.apache.flume.Event; import org.apache.flume.interceptor.Interceptor; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class JSONInterceptor implements Interceptor { private Gson gson; @Override public void initialize() { gson = new GsonBuilder().create(); } @Override public Event intercept(Event event) { // 获取原始数据 String data = new String(event.getBody()); // 将数据转换为JSON格式 Map<String, Object> jsonMap = new HashMap<String, Object>(); jsonMap.put("timestamp", System.currentTimeMillis()); jsonMap.put("data", data); String json = gson.toJson(jsonMap); // 构造新的Event Event newEvent = EventBuilder.withBody(json.getBytes(), event.getHeaders()); return newEvent; } @Override public List<Event> intercept(List<Event> events) { List<Event> interceptedEvents = new ArrayList<Event>(); for (Event event : events) { interceptedEvents.add(intercept(event)); } return interceptedEvents; } @Override public void close() { // do nothing } public static class Builder implements Interceptor.Builder { @Override public void configure(Context context) { // do nothing } @Override public Interceptor build() { return new JSONInterceptor(); } } } ``` 上述代码,我们首先在`initialize()`方法创建了一个Gson对象,用于将数据转换为JSON格式。然后在`intercept()`方法,我们获取原始数据,将其封装成一个Map对象,并添加时间戳等元数据。接着使用Gson将Map对象转换为JSON格式,并构造一个新的Event对象返回。 最后,我们还需要在Flume的配置文件添加相关配置,以启用该拦截器: ```conf agent.sources = source1 agent.sinks = sink1 agent.channels = channel1 agent.sources.source1.type = netcat agent.sources.source1.bind = localhost agent.sources.source1.port = 44444 agent.sinks.sink1.type = logger agent.channels.channel1.type = memory # 添加JSONInterceptor拦截器 agent.sources.source1.interceptors = i1 agent.sources.source1.interceptors.i1.type = com.example.flume.interceptor.JSONInterceptor$Builder agent.sources.source1.channels = channel1 agent.sinks.sink1.channel = channel1 ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值