大数据flume自定义类型(代码片段)

赵广陆 赵广陆     2023-02-16     255

关键词:


1 自定义 Interceptor

1.1 案例需求

使用 Flume 采集服务器本地日志,需要按照日志类型的不同,将不同种类的日志发往不同的分析系统。

1.2 需求分析:Interceptor和Multiplexing ChannelSelector案例

在实际的开发中,一台服务器产生的日志类型可能有很多种,不同类型的日志可能需要发送到不同的分析系统。此时会用到 Flume 拓扑结构中的 Multiplexing 结构,Multiplexing的原理是,根据 event 中 Header 的某个 key 的值,将不同的 event 发送到不同的 Channel中,所以我们需要自定义一个Interceptor,为不同类型的 event 的 Header 中的 key 赋予
不同的值。
在该案例中,我们以端口数据模拟日志,以是否包含”bigdata”模拟不同类型的日志,我们需要自定义 interceptor 区分数据中是否包含”bigdata”,将其分别发往不同的分析系统(Channel)。

1.3 实现步骤

(1)创建一个 maven 项目,并引入以下依赖。

<dependency>
<groupId>org.apache.flume</groupId>
<artifactId>flume-ng-core</artifactId>
<version>1.9.0</version>
</dependency>

(2)定义 CustomInterceptor 类并实现 Interceptor 接口。


package com.bigdata.interceptor;

import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.Interceptor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class TypeInterceptor implements Interceptor 
    //声明一个存放事件的集合
    private List<Event> addHeaderEvents;

    @Override
    public void initialize() 
//初始化存放事件的集合
        addHeaderEvents = new ArrayList<>();
    

    //单个事件拦截
    @Override
    public Event intercept(Event event) 
//1.获取事件中的头信息
        Map<String, String> headers = event.getHeaders();
//2.获取事件中的 body 信息
        String body = new String(event.getBody());
//3.根据 body 中是否有"bigdata"来决定添加怎样的头信息
        if (body.contains("bigdata")) 
//4.添加头信息
            headers.put("type", "first");
         else 
//4.添加头信息
            headers.put("type", "second");
        
        return event;
    

    //批量事件拦截
    @Override
    public List<Event> intercept(List<Event> events) 
//1.清空集合
        addHeaderEvents.clear();
//2.遍历 events
        for (Event event : events) 
//3.给每一个事件添加头信息
            addHeaderEvents.add(intercept(event));
        
//4.返回结果
        return addHeaderEvents;
    

    @Override
    public void close() 
    

    public static class Builder implements Interceptor.Builder 
        @Override
        public Interceptor build() 
            return new TypeInterceptor();
        

        @Override
        public void configure(Context context) 
        
    

(3)编辑 flume 配置文件
为 hadoop102 上的 Flume1 配置 1 个 netcat source,1 个 sink group (2 个 avro sink),
并配置相应的 ChannelSelector 和 interceptor。

# Name the components on this agent
a1.sources = r1
a1.sinks = k1 k2
a1.channels = c1 c2
# Describe/configure the source
a1.sources.r1.type = netcat
a1.sources.r1.bind = localhost
a1.sources.r1.port = 44444
a1.sources.r1.interceptors = i1
a1.sources.r1.interceptors.i1.type =
com.bigdata.flume.interceptor.CustomInterceptor$Builder
a1.sources.r1.selector.type = multiplexing
a1.sources.r1.selector.header = type
a1.sources.r1.selector.mapping.first = c1
a1.sources.r1.selector.mapping.second = c2
# Describe the sink
a1.sinks.k1.type = avro
a1.sinks.k1.hostname = hadoop103
a1.sinks.k1.port = 4141
a1.sinks.k2.type=avro
a1.sinks.k2.hostname = hadoop104
a1.sinks.k2.port = 4242
# Use a channel which buffers events in memory
a1.channels.c1.type = memory
a1.channels.c1.capacity = 1000
a1.channels.c1.transactionCapacity = 100
# Use a channel which buffers events in memory
a1.channels.c2.type = memory
a1.channels.c2.capacity = 1000
a1.channels.c2.transactionCapacity = 100
# Bind the source and sink to the channel
a1.sources.r1.channels = c1 c2
a1.sinks.k1.channel = c1
a1.sinks.k2.channel = c2

为 hadoop103 上的 Flume4 配置一个 avro source 和一个 logger sink。

a1.sources = r1
a1.sinks = k1
a1.channels = c1
a1.sources.r1.type = avro
a1.sources.r1.bind = hadoop103
a1.sources.r1.port = 4141
a1.sinks.k1.type = logger
a1.channels.c1.type = memory
a1.channels.c1.capacity = 1000
a1.channels.c1.transactionCapacity = 100
a1.sinks.k1.channel = c1
a1.sources.r1.channels = c1

为 hadoop104 上的 Flume3 配置一个 avro source 和一个 logger sink。

a1.sources = r1
a1.sinks = k1
a1.channels = c1
a1.sources.r1.type = avro
a1.sources.r1.bind = hadoop104
a1.sources.r1.port = 4242
a1.sinks.k1.type = logger
a1.channels.c1.type = memory
a1.channels.c1.capacity = 1000
a1.channels.c1.transactionCapacity = 100
a1.sinks.k1.channel = c1
a1.sources.r1.channels = c1

(4)分别在 hadoop102,hadoop103,hadoop104 上启动 flume 进程,注意先后顺序。
(5)在 hadoop102 使用 netcat 向 localhost:44444 发送字母和数字。
(6)观察 hadoop103 和 hadoop104 打印的日志。

2 自定义 Source

2.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() //backoff 步长getMaxBackOffSleepInterval()//backoff 最长时间
configure(Context context)//初始化 context(读取配置文件内容)
process()//获取数据封装成 event 并写入 channel,这个方法将被循环调用。
使用场景:读取 MySQL 数据或者其他文件系统。

2.2 需求:自定义Source

使用 flume 接收数据,并给每条数据添加前缀,输出到控制台。前缀可从 flume 配置文件中配置。

2.3 分析:自定义Source

2.4 编码

(1)导入 pom 依赖

<dependencies>
<dependency>
<groupId>org.apache.flume</groupId>
<artifactId>flume-ng-core</artifactId>
<version>1.9.0</version>
</dependency>

(2)编写代码

package com.bigdata;
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.util.HashMap;
public class MySource extends AbstractSource implements
        Configurable, PollableSource 
    //定义配置文件将来要读取的字段
    private Long delay;
    private String field;
    //初始化配置信息
    @Override
    public void configure(Context context) 
        delay = context.getLong("delay");
        field = context.getString("field", "Hello!");
    
    @Override
    public Status process() throws EventDeliveryException 
        try 
//创建事件头信息
            HashMap<String, String> hearderMap = new HashMap<>();
//创建事件
            SimpleEvent event = new SimpleEvent();
//循环封装事件
            for (int i = 0; i < 5; i++) 
//给事件设置头信息
                event.setHeaders(hearderMap);
//给事件设置内容
                event.setBody((field + i).getBytes());
//将事件写入 channel
                getChannelProcessor().processEvent(event);
                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;
    

2.5 测试

(1)打包
将写好的代码打包,并放到 flume 的 lib 目录(/opt/module/flume)下。
(2)配置文件

# Name the components on this agent
a1.sources = r1
a1.sinks = k1
a1.channels = c1
# Describe/configure the source
a1.sources.r1.type = com.bigdata.MySource
a1.sources.r1.delay = 1000
#a1.sources.r1.field = bigdata
# 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

(3)开启任务

[bigdata@hadoop102 flume]$ pwd
/opt/module/flume
[bigdata@hadoop102 flume]$ bin/flume-ng agent -c conf/ -f
job/mysource.conf -n a1 -Dflume.root.logger=INFO,console

(4)结果展示

3 自定义 Sink

3.1 介绍

Sink 不断地轮询 Channel 中的事件且批量地移除它们,并将这些事件批量写入到存储或索引系统、或者被发送到另一个 Flume Agent。
Sink 是完全事务性的。在从 Channel 批量删除数据之前,每个 Sink 用 Channel 启动一个事务。批量事件一旦成功写出到存储系统或下一个 Flume Agent,Sink 就利用 Channel 提交事务。事务一旦被提交,该 Channel 从自己的内部缓冲区删除事件。
Sink 组件目的地包括hdfs、logger、avro、thrift、ipc、file、null、HBase、solr、自定义。官方提供的 Sink 类型已经很多,但是有时候并不能满足实际开发当中的需求,此时我们就需要根据实际需求自定义某些 Sink。
官方也提供了自定义 sink 的接口:
https://flume.apache.org/FlumeDeveloperGuide.html#sink 根据官方说明自定义MySink 需要继承 AbstractSink 类并实现 Configurable 接口。
实现相应方法:
configure(Context context)//初始化 context(读取配置文件内容)
process()//从 Channel 读取获取数据(event),这个方法将被循环调用。
使用场景:读取 Channel 数据写入 MySQL 或者其他文件系统。

3.2 需求

使用 flume 接收数据,并在 Sink 端给每条数据添加前缀和后缀,输出到控制台。前后缀可在 flume 任务配置文件中配置。
流程分析:

3.3 编码

package com.bigdata;

import org.apache.flume.*;
import org.apache.flume.conf.Configurable;
import org.apache.flume.sink.AbstractSink;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MySink extends AbstractSink implements Configurable 
    //创建 Logger 对象
    private static final Logger LOG =
            LoggerFactory.getLogger(AbstractSink.class);
    private String prefix;
    private String suffix;

    @Override
    public Status process() throws EventDeliveryException 
//声明返回值状态信息
        Status status;
//获取当前 Sink 绑定的 Channel
        Channel ch = getChannel();
//获取事务
        Transaction txn = ch.getTransaction();
//声明事件
        Event event;
//开启事务
        txn.begin();
//读取 Channel 中的事件,直到读取到事件结束循环
        while (true) 
            event = ch.take();
            if (event != null) 
                break;
            
        
        try 
//处理事件(打印)
            LOG.info(prefix + new String(event.getBody()) +
                    suffix);
//事务提交
            txn.commit();
            status = Status.READY;
         catch (Exception e) 
//遇到异常,事务回滚
            txn.rollback();
            status = Status.BACKOFF;
         finally 
//关闭事务
            txn.close();
        
        return status;
    

    @Override
    public void configure(Context context) 
//读取配置文件内容,有默认值
        prefix = context.getString("prefix", "hello:");
//读取配置文件内容,无默认值
        suffix = context.getString("suffix");
    

3.4 测试

(1)打包
将写好的代码打包,并放到 flume 的 lib 目录(/opt/module/flume)下。
(2)配置文件

# Name the components on this agent
a1.sources = r1
a1.sinks = k1
a1.channels = c1
# Describe/configure the source
a1.sources.r1.type = netcat
a1.sources.r1.bind = localhost
a1.sources.r1.port = 44444
# Describe the sink
a1.sinks.k1.type = com.bigdata.MySink
#a1.sinks.k1.prefix = bigdata:
a1.sinks.k1.suffix = :bigdata
# 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

(3)开启任务

[bigdata@hadoop102 flume]$ bin/flume-ng agent -c conf/ -f
job/mysink.conf -n a1 -Dflume.root.logger=INFO,console
[bigdata@hadoop102 ~]$ nc localhost 44444
hello
OK
bigdata
OK

(4)结果展示

打怪升级之小白的大数据之旅(七十三)<flume高级>(代码片段)

打怪升级之小白的大数据之旅(七十三)Flume高级上次回顾上一章介绍了Flume的内部原理,本章就Flume的扩展知识进行讲解,本章的重点就是了解并学会使用Flume的自定义组件自定义组件在上一章介绍了内部原理,所以下... 查看详情

大数据技术之flumeflume进阶企业真实面试题(代码片段)

...义Source1.7自定义Sink2企业真实面试题2.1你是如何实现Flume数据传输的监控的?2.2Flume的Source,Sink,Channel的作用?你们Source是什么类型?2.3Flume的ChannelSelectors2.4Flume参数调优2.5Flume的事务机制2.6Flume采集数据会丢失吗?1Fl... 查看详情

大数据技术之flumeflume进阶企业真实面试题(代码片段)

...义Source1.7自定义Sink2企业真实面试题2.1你是如何实现Flume数据传输的监控的?2.2Flume的Source,Sink,Channel的作用?你们Source是什么类型?2.3Flume的ChannelSelectors2.4Flume参数调优2.5Flume的事务机制2.6Flume采集数据会丢失吗?1Fl... 查看详情

大数据技术之flumeflume进阶企业真实面试题(代码片段)

文章目录1Flume进阶1.1Flume事务1.2FlumeAgent内部原理1.3Flume拓扑结构1.3.1简单串联1.3.2复制和多路复用1.3.3负载均衡和故障转移1.3.4聚合1.4Flume企业开发案例1.4.1复制和多路复用1.4.2负载均衡和故障转移1.4.3聚合1.5自定义Interceptor1.6自定义S... 查看详情

flume基础:自定义interceptor(代码片段)

1)案例需求使用Flume采集服务器本地日志,需要按照日志类型的不同,将不同种类的日志发往不同的分析系统。2)需求分析  在实际的开发中,一台服务器产生的日志类型可能有很多种,不同类型的日志可能需要发送到不同... 查看详情

大数据技术之kafkakafkaapikafka监控flume对接kafkakafka面试题(代码片段)

文章目录1KafkaAPI1.1ProducerAPI1.1.1消息发送流程1.1.2异步发送API1.1.3同步发送API1.2ConsumerAPI1.2.1自动提交offset1.2.2手动提交offset1.2.3自定义存储offset1.3自定义Interceptor1.3.1拦截器原理1.3.2拦截器案例2Kafka监控2.1KafkaEagle3Flume对接Kafka4Kafka面 查看详情

大数据技术之kafkakafkaapikafka监控flume对接kafkakafka面试题(代码片段)

文章目录1KafkaAPI1.1ProducerAPI1.1.1消息发送流程1.1.2异步发送API1.1.3同步发送API1.2ConsumerAPI1.2.1自动提交offset1.2.2手动提交offset1.2.3自定义存储offset1.3自定义Interceptor1.3.1拦截器原理1.3.2拦截器案例2Kafka监控2.1KafkaEagle3Flume对接Kafka4Kafka面 查看详情

大数据技术之flume(代码片段)

文章目录第1章Flume概述1.1Flume定义1.2Flume基础架构1.2.1Agent1.2.2Source1.2.3Sink1.2.4Channel1.2.5Event第2章Flume入门2.1案例12.1.1判断44444端口是否被占用2.1.2在flume目录下创建job文件夹并且创建flume文件。2.1.3使用netcat工具向本机的44444端口发送... 查看详情

常用的大数据采集工具(代码片段)

天津网站建设为了高效采集大数据,依据采集环境及数据类型选择适当的大数据采集方法及平台至关重要。下面介绍一些常用的大数据采集平台和工具。1、FlumeFlume作为Hadoop的组件,是由Cloudera专门研发的分布式日志收集... 查看详情

大数据技术之flumeflume概述flume快速入门(代码片段)

...署2.1.1安装地址2.1.2安装部署2.2Flume入门案例2.2.1监控端口数据官方案例2.2.2实时监控单个追加文件2.3.3实时监控目录下多个新文件2.2.4实时监控目录下的多个追加文件1Flume概述1.1Flume定义Flume是Cloudera提供的一个高可用的,高可... 查看详情

大数据技术之flumeflume概述flume快速入门(代码片段)

...署2.1.1安装地址2.1.2安装部署2.2Flume入门案例2.2.1监控端口数据官方案例2.2.2实时监控单个追加文件2.3.3实时监控目录下多个新文件2.2.4实时监控目录下的多个追加文件1Flume概述1.1Flume定义Flume是Cloudera提供的一个高可用的,高可... 查看详情

大数据技术之flumeflume概述flume快速入门(代码片段)

...署2.1.1安装地址2.1.2安装部署2.2Flume入门案例2.2.1监控端口数据官方案例2.2.2实时监控单个追加文件2.3.3实时监控目录下多个新文件2.2.4实时监控目录下的多个 查看详情

flume自定义source(代码片段)

模拟编写了一个Flume1.7中TAILDIR的功能实现,通过手动控制文件的读取位置来达到对文件的读写,防止flume挂了之后重复消费的情况。以下是代码实现,仅做参考,生产上直接用TAILDIR读取文件内容即可,若要读取一个目录下的子目... 查看详情

flume中自定义sinkinterceptor(代码片段)

SinkProcessor:============================FailOver:Loadbalancing://负载均衡处理器//round_robin轮询1-2-3-1-2-3-...//random随机1-3-2-3-1-...1、round_robin轮询1-2-3-1-2-3-...2、random随机:自定义Sink&&InterCeptor==== 查看详情

flume(代码片段)

...Flume快速入门2.1Flume安装部署2.2Flume入门案例2.2.1监控端口数据官方案例2.2.2实时监控单个追加文件2.2.3实时监控目录下多个新文件2.2.4实时监控目录下的多个追加文件第3章Flume进阶3.1Flume事务3.2FlumeAgent内部原理3.3Flume拓扑结构3.4Flume... 查看详情

flume自定义反序列化器deserializer(代码片段)

...ent进行传输。解决思路:   解决上述需求可以通过自定义拦截器和自定义反序列化器来实现。网上关于自定义拦截器的资料比较多,但考虑到拦截器的定位和使用场景,拦截器不应用于多个event拆分组合,并若flume有并发处... 查看详情

flume(代码片段)

...署2.1.1安装地址2.1.2安装部署2.2Flume入门案例2.2.1监控端口数据官方案例2.2.2实时监控单个追加文件-exec2.2.3实时监控目录下多个新文件-spooldir2.2.4实时监控目录下的多个追加文件-taildir3Flume进阶3.1Flume事务3.2FlumeAgent内部原理3.3Flume拓... 查看详情

自定义sourcesink(代码片段)

1导入pom依赖2<dependencies>3<dependency>4<groupId>org.apache.flume</groupId>5<artifactId>flume-ng-core</artifactId>6<version>1.7.0</version>7</dependency>89</dependencies>10编写代码11packagecom.baway.flume;1213importorg.apache.flume... 查看详情