大数据Flume自定义类型

简介: 大数据Flume自定义类型

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

相关实践学习
简单用户画像分析
本场景主要介绍基于海量日志数据进行简单用户画像分析为背景,如何通过使用DataWorks完成数据采集 、加工数据、配置数据质量监控和数据可视化展现等任务。
SaaS 模式云数据仓库必修课
本课程由阿里云开发者社区和阿里云大数据团队共同出品,是SaaS模式云原生数据仓库领导者MaxCompute核心课程。本课程由阿里云资深产品和技术专家们从概念到方法,从场景到实践,体系化的将阿里巴巴飞天大数据平台10多年的经过验证的方法与实践深入浅出的讲给开发者们。帮助大数据开发者快速了解并掌握SaaS模式的云原生的数据仓库,助力开发者学习了解先进的技术栈,并能在实际业务中敏捷的进行大数据分析,赋能企业业务。 通过本课程可以了解SaaS模式云原生数据仓库领导者MaxCompute核心功能及典型适用场景,可应用MaxCompute实现数仓搭建,快速进行大数据分析。适合大数据工程师、大数据分析师 大量数据需要处理、存储和管理,需要搭建数据仓库?学它! 没有足够人员和经验来运维大数据平台,不想自建IDC买机器,需要免运维的大数据平台?会SQL就等于会大数据?学它! 想知道大数据用得对不对,想用更少的钱得到持续演进的数仓能力?获得极致弹性的计算资源和更好的性能,以及持续保护数据安全的生产环境?学它! 想要获得灵活的分析能力,快速洞察数据规律特征?想要兼得数据湖的灵活性与数据仓库的成长性?学它! 出品人:阿里云大数据产品及研发团队专家 产品 MaxCompute 官网 https://www.aliyun.com/product/odps&nbsp;
目录
相关文章
|
25天前
|
存储 消息中间件 监控
【Flume】Flume在大数据分析领域的应用
【4月更文挑战第4天】【Flume】Flume在大数据分析领域的应用
|
7月前
|
SQL 分布式计算 监控
大数据Flume快速入门
大数据Flume快速入门
57 0
|
7月前
|
SQL 存储 监控
大数据Flume企业开发实战
大数据Flume企业开发实战
36 0
|
6月前
|
数据采集 消息中间件 监控
大数据组件-Flume集群环境搭建
大数据组件-Flume集群环境搭建
116 0
|
6月前
|
Oracle 大数据 关系型数据库
大数据组件-Flume集群环境的启动与验证
大数据组件-Flume集群环境的启动与验证
94 0
|
7月前
|
存储 监控 数据可视化
大数据Flume数据流监控
大数据Flume数据流监控
77 0
|
7月前
|
SQL 负载均衡 监控
大数据Flume特性
大数据Flume特性
61 1
|
7月前
|
消息中间件 存储 安全
大数据技Flume快速入门
大数据技Flume快速入门
53 0
|
8月前
|
消息中间件 JSON 监控
|
10月前
|
数据采集 大数据 数据处理
大数据数据采集的数据采集(收集/聚合)的Flume之数据采集流程的Interceptor的Regex Interceptor
大数据的发展让数据采集变得越来越重要,而Flume则是一款非常优秀的开源数据采集工具。在Flume中,Interceptor是一个非常重要的概念,可以对数据进行拦截、过滤和转换,从而实现更加灵活高效的数据采集流程。
62 0

热门文章

最新文章