一、引言
在大数据领域,Flume 作为高可用的分布式日志采集系统,其核心价值在于实现数据从源头到存储系统的可靠传输。
二、时间戳拦截器(Timestamp Interceptor)
2.1 核心功能
向 Event 的 Header 中注入当前时间戳(默认键为timestamp
,值为System.currentTimeMillis()
的毫秒值)。
支持自定义 Header 键名(通过headerName
参数),并可配置是否覆盖已有同名键值(preserveExisting
,默认false
)。
2.2 典型场景
当 Flume 对接 HDFS 时,若存储路径包含时间转义符(如%y-%m-%d
),需确保 Event 携带时间戳。此时有两种方案:
- 使用 HDFS 本地时间:通过
sinks.k1.hdfs.useLocalTimeStamp = true
直接使用服务端时间。 - 使用时间戳拦截器:通过拦截器强制为每条数据注入时间戳,确保时间一致性。
2.3 配置示例
# 定义Source及其拦截器
a1.sources = r1
a1.sources.r1.type = exec
a1.sources.r1.command = tail -F /opt/data/c.txt
a1.sources.r1.channels = c1
# 配置时间戳拦截器
a1.sources.r1.interceptors = i1
a1.sources.r1.interceptors.i1.type = timestamp # 拦截器类型
a1.sources.r1.interceptors.i1.headerName = event-time # 可选:自定义Header键名
a1.sources.r1.interceptors.i1.preserveExisting = false # 可选:是否保留原始值(默认false)
# 配置HDFS Sink(使用时间转义符)
a1.sinks = k1
a1.sinks.k1.type = hdfs
a1.sinks.k1.hdfs.path = /flume/events/%y-%m-%d/%H%M/%S # 依赖Header中的timestamp
a1.sinks.k1.hdfs.round = true
a1.sinks.k1.hdfs.roundValue = 10
a1.sinks.k1.hdfs.roundUnit = minute
三、Host 拦截器(Host Interceptor)
3.1 核心功能
向 Event 的 Header 中注入数据源的主机名或 IP 地址,常用于标识数据来源节点。
关键参数:
preserveExisting
:是否覆盖已有键(默认false
)。
useIP
:是否使用 IP 地址(true
)或主机名(false
,默认)。
hostHeader
:自定义 Header 键名(默认host
)。
3.2 实战场景
当多节点部署 Flume 时,通过 Host 拦截器可在数据中标记来源节点,便于后续按节点统计或路由。以下为 HTTP Source 结合 HDFS 存储的示例:
# 定义HTTP Source
a1.sources = r1
a1.sources.r1.type = http
a1.sources.r1.bind = bigdata01 # 绑定主机名
a1.sources.r1.port = 6666 # 监听端口
# 配置Host拦截器(记录IP地址)
a1.sources.r1.interceptors = i2
a1.sources.r1.interceptors.i2.type = host
a1.sources.r1.interceptors.i2.useIP = true # 使用IP地址
a1.sources.r1.interceptors.i2.hostHeader = hostname # 自定义键名为hostname
# 配置HDFS Sink(使用主机名作为文件名前缀)
a1.sinks.s1.hdfs.path = /flume/%Y/%m/%d/%H%M
a1.sinks.s1.hdfs.filePrefix = %{hostname}- # 引用Header中的hostname
a1.sinks.s1.hdfs.fileSuffix = .log
3.3 测试验证
通过curl
模拟数据发送,验证 Header 是否包含目标键值:
curl -X POST -d '{"headers":{"state":"USER"},"body":"test data"}' http://bigdata01:6666
四、静态拦截器(Static Interceptor)
4.1 核心功能
允许用户自定义固定的 Key-Value 对注入 Event 的 Header,适用于需要添加静态元数据(如环境标识、数据类型)的场景。
配置方式:通过keyValuePairs
参数指定多个键值对,格式为key1=value1,key2=value2
。
4.2 配置示例
# 定义静态拦截器
a1.sources.r1.interceptors = i3
a1.sources.r1.interceptors.i3.type = static # 拦截器类型
a1.sources.r1.interceptors.i3.keyValuePairs = env=prod,type=log # 自定义键值对
a1.sources.r1.interceptors.i3.preserveExisting = false # 可选:是否覆盖已有键
4.3 应用场景
在多环境(开发 / 生产)中标记数据所属环境,便于下游系统过滤。
添加数据类型标识(如type=access_log
),简化数据路由逻辑。
五、拦截器链(Interceptor Chain)
Flume 支持串联多个拦截器,按配置顺序依次处理 Event。例如,同时使用时间戳和 Host 拦截器:
a1.sources.r1.interceptors = i1 i2 # 拦截器链,按顺序执行
a1.sources.r1.interceptors.i1.type = timestamp
a1.sources.r1.interceptors.i2.type = host