还是针对学习七中的那个需求,我们现在换一种实现方式,采用拦截器来实现。

先回想一下,spooldir source可以将文件名作为header中的key:basename写入到event的header当中去。试想一下,如果有一个拦截器可以拦截这个event,然后抽取header中这个key的值,将其拆分成3段,每一段都放入到header中,这样就可以实现那个需求了。

遗憾的是,flume没有提供可以拦截header的拦截器。不过有一个抽取body内容的拦截器:RegexExtractorInterceptor,看起来也很强大,以下是一个官方文档的示例:

If the Flume event body contained 1:2:3.4foobar5 and the following configuration was used

a1.sources.r1.interceptors.i1.regex = (\\d):(\\d):(\\d)
a1.sources.r1.interceptors.i1.serializers = s1 s2 s3
a1.sources.r1.interceptors.i1.serializers.s1.name = one
a1.sources.r1.interceptors.i1.serializers.s2.name = two
a1.sources.r1.interceptors.i1.serializers.s3.name = three
The extracted event will contain the same body but the following headers will have been added one=>1, two=>2, three=>3

大概意思就是,通过这样的配置,event body中如果有1:2:3.4foobar5 这样的内容,这会通过正则的规则抽取具体部分的内容,然后设置到header当中去。

于是决定打这个拦截器的主义,觉得只要把代码稍微改改,从拦截body改为拦截header中的具体key,就OK了。翻开源码,哎呀,很工整,改起来没难度,以下是我新增的一个拦截器:RegexExtractorExtInterceptor:

[java] view plaincopy
  1. package com.besttone.flume;
  2. import java.util.List;
  3. import java.util.Map;
  4. import java.util.regex.Matcher;
  5. import java.util.regex.Pattern;
  6. import org.apache.commons.lang.StringUtils;
  7. import org.apache.flume.Context;
  8. import org.apache.flume.Event;
  9. import org.apache.flume.interceptor.Interceptor;
  10. import org.apache.flume.interceptor.RegexExtractorInterceptorPassThroughSerializer;
  11. import org.apache.flume.interceptor.RegexExtractorInterceptorSerializer;
  12. import org.slf4j.Logger;
  13. import org.slf4j.LoggerFactory;
  14. import com.google.common.base.Charsets;
  15. import com.google.common.base.Preconditions;
  16. import com.google.common.base.Throwables;
  17. import com.google.common.collect.Lists;
  18. /**
  19. * Interceptor that extracts matches using a specified regular expression and
  20. * appends the matches to the event headers using the specified serializers</p>
  21. * Note that all regular expression matching occurs through Java's built in
  22. * java.util.regex package</p>. Properties:
  23. * <p>
  24. * regex: The regex to use
  25. * <p>
  26. * serializers: Specifies the group the serializer will be applied to, and the
  27. * name of the header that will be added. If no serializer is specified for a
  28. * group the default {@link RegexExtractorInterceptorPassThroughSerializer} will
  29. * be used
  30. * <p>
  31. * Sample config:
  32. * <p>
  33. * agent.sources.r1.channels = c1
  34. * <p>
  35. * agent.sources.r1.type = SEQ
  36. * <p>
  37. * agent.sources.r1.interceptors = i1
  38. * <p>
  39. * agent.sources.r1.interceptors.i1.type = REGEX_EXTRACTOR
  40. * <p>
  41. * agent.sources.r1.interceptors.i1.regex = (WARNING)|(ERROR)|(FATAL)
  42. * <p>
  43. * agent.sources.r1.interceptors.i1.serializers = s1 s2
  44. * agent.sources.r1.interceptors.i1.serializers.s1.type =
  45. * com.blah.SomeSerializer agent.sources.r1.interceptors.i1.serializers.s1.name
  46. * = warning agent.sources.r1.interceptors.i1.serializers.s2.type =
  47. * org.apache.flume.interceptor.RegexExtractorInterceptorTimestampSerializer
  48. * agent.sources.r1.interceptors.i1.serializers.s2.name = error
  49. * agent.sources.r1.interceptors.i1.serializers.s2.dateFormat = yyyy-MM-dd
  50. * </code>
  51. * </p>
  52. *
  53. * <pre>
  54. * Example 1:
  55. * </p>
  56. * EventBody: 1:2:3.4foobar5</p> Configuration:
  57. * agent.sources.r1.interceptors.i1.regex = (\\d):(\\d):(\\d)
  58. * </p>
  59. * agent.sources.r1.interceptors.i1.serializers = s1 s2 s3
  60. * agent.sources.r1.interceptors.i1.serializers.s1.name = one
  61. * agent.sources.r1.interceptors.i1.serializers.s2.name = two
  62. * agent.sources.r1.interceptors.i1.serializers.s3.name = three
  63. * </p>
  64. * results in an event with the the following
  65. *
  66. * body: 1:2:3.4foobar5 headers: one=>1, two=>2, three=3
  67. *
  68. * Example 2:
  69. *
  70. * EventBody: 1:2:3.4foobar5
  71. *
  72. * Configuration: agent.sources.r1.interceptors.i1.regex = (\\d):(\\d):(\\d)
  73. * <p>
  74. * agent.sources.r1.interceptors.i1.serializers = s1 s2
  75. * agent.sources.r1.interceptors.i1.serializers.s1.name = one
  76. * agent.sources.r1.interceptors.i1.serializers.s2.name = two
  77. * <p>
  78. *
  79. * results in an event with the the following
  80. *
  81. * body: 1:2:3.4foobar5 headers: one=>1, two=>2
  82. * </pre>
  83. */
  84. public class RegexExtractorExtInterceptor implements Interceptor {
  85. static final String REGEX = "regex";
  86. static final String SERIALIZERS = "serializers";
  87. // 增加代码开始
  88. static final String EXTRACTOR_HEADER = "extractorHeader";
  89. static final boolean DEFAULT_EXTRACTOR_HEADER = false;
  90. static final String EXTRACTOR_HEADER_KEY = "extractorHeaderKey";
  91. // 增加代码结束
  92. private static final Logger logger = LoggerFactory
  93. .getLogger(RegexExtractorExtInterceptor.class);
  94. private final Pattern regex;
  95. private final List<NameAndSerializer> serializers;
  96. // 增加代码开始
  97. private final boolean extractorHeader;
  98. private final String extractorHeaderKey;
  99. // 增加代码结束
  100. private RegexExtractorExtInterceptor(Pattern regex,
  101. List<NameAndSerializer> serializers, boolean extractorHeader,
  102. String extractorHeaderKey) {
  103. this.regex = regex;
  104. this.serializers = serializers;
  105. this.extractorHeader = extractorHeader;
  106. this.extractorHeaderKey = extractorHeaderKey;
  107. }
  108. @Override
  109. public void initialize() {
  110. // NO-OP...
  111. }
  112. @Override
  113. public void close() {
  114. // NO-OP...
  115. }
  116. @Override
  117. public Event intercept(Event event) {
  118. String tmpStr;
  119. if(extractorHeader)
  120. {
  121. tmpStr = event.getHeaders().get(extractorHeaderKey);
  122. }
  123. else
  124. {
  125. tmpStr=new String(event.getBody(),
  126. Charsets.UTF_8);
  127. }
  128. Matcher matcher = regex.matcher(tmpStr);
  129. Map<String, String> headers = event.getHeaders();
  130. if (matcher.find()) {
  131. for (int group = 0, count = matcher.groupCount(); group < count; group++) {
  132. int groupIndex = group + 1;
  133. if (groupIndex > serializers.size()) {
  134. if (logger.isDebugEnabled()) {
  135. logger.debug(
  136. "Skipping group {} to {} due to missing serializer",
  137. group, count);
  138. }
  139. break;
  140. }
  141. NameAndSerializer serializer = serializers.get(group);
  142. if (logger.isDebugEnabled()) {
  143. logger.debug("Serializing {} using {}",
  144. serializer.headerName, serializer.serializer);
  145. }
  146. headers.put(serializer.headerName, serializer.serializer
  147. .serialize(matcher.group(groupIndex)));
  148. }
  149. }
  150. return event;
  151. }
  152. @Override
  153. public List<Event> intercept(List<Event> events) {
  154. List<Event> intercepted = Lists.newArrayListWithCapacity(events.size());
  155. for (Event event : events) {
  156. Event interceptedEvent = intercept(event);
  157. if (interceptedEvent != null) {
  158. intercepted.add(interceptedEvent);
  159. }
  160. }
  161. return intercepted;
  162. }
  163. public static class Builder implements Interceptor.Builder {
  164. private Pattern regex;
  165. private List<NameAndSerializer> serializerList;
  166. // 增加代码开始
  167. private boolean extractorHeader;
  168. private String extractorHeaderKey;
  169. // 增加代码结束
  170. private final RegexExtractorInterceptorSerializer defaultSerializer = new RegexExtractorInterceptorPassThroughSerializer();
  171. @Override
  172. public void configure(Context context) {
  173. String regexString = context.getString(REGEX);
  174. Preconditions.checkArgument(!StringUtils.isEmpty(regexString),
  175. "Must supply a valid regex string");
  176. regex = Pattern.compile(regexString);
  177. regex.pattern();
  178. regex.matcher("").groupCount();
  179. configureSerializers(context);
  180. // 增加代码开始
  181. extractorHeader = context.getBoolean(EXTRACTOR_HEADER,
  182. DEFAULT_EXTRACTOR_HEADER);
  183. if (extractorHeader) {
  184. extractorHeaderKey = context.getString(EXTRACTOR_HEADER_KEY);
  185. Preconditions.checkArgument(
  186. !StringUtils.isEmpty(extractorHeaderKey),
  187. "必须指定要抽取内容的header key");
  188. }
  189. // 增加代码结束
  190. }
  191. private void configureSerializers(Context context) {
  192. String serializerListStr = context.getString(SERIALIZERS);
  193. Preconditions.checkArgument(
  194. !StringUtils.isEmpty(serializerListStr),
  195. "Must supply at least one name and serializer");
  196. String[] serializerNames = serializerListStr.split("\\s+");
  197. Context serializerContexts = new Context(
  198. context.getSubProperties(SERIALIZERS + "."));
  199. serializerList = Lists
  200. .newArrayListWithCapacity(serializerNames.length);
  201. for (String serializerName : serializerNames) {
  202. Context serializerContext = new Context(
  203. serializerContexts.getSubProperties(serializerName
  204. + "."));
  205. String type = serializerContext.getString("type", "DEFAULT");
  206. String name = serializerContext.getString("name");
  207. Preconditions.checkArgument(!StringUtils.isEmpty(name),
  208. "Supplied name cannot be empty.");
  209. if ("DEFAULT".equals(type)) {
  210. serializerList.add(new NameAndSerializer(name,
  211. defaultSerializer));
  212. } else {
  213. serializerList.add(new NameAndSerializer(name,
  214. getCustomSerializer(type, serializerContext)));
  215. }
  216. }
  217. }
  218. private RegexExtractorInterceptorSerializer getCustomSerializer(
  219. String clazzName, Context context) {
  220. try {
  221. RegexExtractorInterceptorSerializer serializer = (RegexExtractorInterceptorSerializer) Class
  222. .forName(clazzName).newInstance();
  223. serializer.configure(context);
  224. return serializer;
  225. } catch (Exception e) {
  226. logger.error("Could not instantiate event serializer.", e);
  227. Throwables.propagate(e);
  228. }
  229. return defaultSerializer;
  230. }
  231. @Override
  232. public Interceptor build() {
  233. Preconditions.checkArgument(regex != null,
  234. "Regex pattern was misconfigured");
  235. Preconditions.checkArgument(serializerList.size() > 0,
  236. "Must supply a valid group match id list");
  237. return new RegexExtractorExtInterceptor(regex, serializerList,
  238. extractorHeader, extractorHeaderKey);
  239. }
  240. }
  241. static class NameAndSerializer {
  242. private final String headerName;
  243. private final RegexExtractorInterceptorSerializer serializer;
  244. public NameAndSerializer(String headerName,
  245. RegexExtractorInterceptorSerializer serializer) {
  246. this.headerName = headerName;
  247. this.serializer = serializer;
  248. }
  249. }
  250. }

简单说明一下改动的内容:

增加了两个配置参数:

extractorHeader   是否抽取的是header部分,默认为false,即和原始的拦截器功能一致,抽取的是event body的内容

extractorHeaderKey 抽取的header的指定的key的内容,当extractorHeader为true时,必须指定该参数。

按照第七讲的方法,我们将该类打成jar包,作为flume的插件放到了/var/lib/flume-ng/plugins.d/RegexExtractorExtInterceptor/lib目录下,重新启动flume,将该拦截器加载到classpath中。

最终的flume.conf如下:

[plain] view plaincopy
  1. tier1.sources=source1
  2. tier1.channels=channel1
  3. tier1.sinks=sink1
  4. tier1.sources.source1.type=spooldir
  5. tier1.sources.source1.spoolDir=/opt/logs
  6. tier1.sources.source1.fileHeader=true
  7. tier1.sources.source1.basenameHeader=true
  8. tier1.sources.source1.interceptors=i1
  9. tier1.sources.source1.interceptors.i1.type=com.besttone.flume.RegexExtractorExtInterceptor$Builder
  10. tier1.sources.source1.interceptors.i1.regex=(.*)\\.(.*)\\.(.*)
  11. tier1.sources.source1.interceptors.i1.extractorHeader=true
  12. tier1.sources.source1.interceptors.i1.extractorHeaderKey=basename
  13. tier1.sources.source1.interceptors.i1.serializers=s1 s2 s3
  14. tier1.sources.source1.interceptors.i1.serializers.s1.name=one
  15. tier1.sources.source1.interceptors.i1.serializers.s2.name=two
  16. tier1.sources.source1.interceptors.i1.serializers.s3.name=three
  17. tier1.sources.source1.channels=channel1
  18. tier1.sinks.sink1.type=hdfs
  19. tier1.sinks.sink1.channel=channel1
  20. tier1.sinks.sink1.hdfs.path=hdfs://master68:8020/flume/events/%{one}/%{three}
  21. tier1.sinks.sink1.hdfs.round=true
  22. tier1.sinks.sink1.hdfs.roundValue=10
  23. tier1.sinks.sink1.hdfs.roundUnit=minute
  24. tier1.sinks.sink1.hdfs.fileType=DataStream
  25. tier1.sinks.sink1.hdfs.writeFormat=Text
  26. tier1.sinks.sink1.hdfs.rollInterval=0
  27. tier1.sinks.sink1.hdfs.rollSize=10240
  28. tier1.sinks.sink1.hdfs.rollCount=0
  29. tier1.sinks.sink1.hdfs.idleTimeout=60
  30. tier1.channels.channel1.type=memory
  31. tier1.channels.channel1.capacity=10000
  32. tier1.channels.channel1.transactionCapacity=1000
  33. tier1.channels.channel1.keep-alive=30

我把source type改回了内置的spooldir,而不是上一讲自定义的source,然后添加了一个拦截器i1,type是自定义的拦截器:com.besttone.flume.RegexExtractorExtInterceptor$Builder,正则表达式按“.”分隔抽取三部分,分别放到header中的key:one,two,three当中去,即a.log.2014-07-31,通过拦截器后,在header当中就会增加三个key: one=a,two=log,three=2014-07-31。这时候我们在tier1.sinks.sink1.hdfs.path=hdfs://master68:8020/flume/events/%{one}/%{three}。

就实现了和前面第七讲一模一样的需求。

也可以看到,自定义拦截器的改动成本非常小,比自定义source小多了,我们这就增加了一个类,就实现了该功能。

flume学习(八):自定义拦截器相关推荐

  1. Struts学习之自定义拦截器

    * 所有的拦截器都需要实现Interceptor接口或者继承Interceptor接口的扩展实现类     * 要重写init().intercept().destroy()方法         * ...

  2. struts2基础----自定义拦截器

    这一章,我们开始struts2中拦截器的学习. 自定义拦截器 一.增加一个自定义的拦截器为类 package com.huhx.interceptor;import com.opensymphony. ...

  3. Hadoop生态圈-Flume的组件之自定义拦截器(interceptor)

    Hadoop生态圈-Flume的组件之自定义拦截器(interceptor) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 本篇博客只是举例了一个自定义拦截器的方法,测试字节传输速 ...

  4. Flume的开发之 自定义 source 自定义 sink 自定义拦截器

    一:开发相关 加入 jar 包依赖: <dependency> <groupId>org.apache.flume</groupId> <artifactId ...

  5. flume拦截器及自定义拦截器

    拦截器做什么呢? 时间拦截器 以时间拦截器为例.会在Event的header中添加一个属性进去,属性的key叫做timestamp, value是当前的毫秒值. 问题是写到header然后呢?有啥用呢 ...

  6. flume自定义拦截器开发步骤

    步骤如下: 1.新建一个java项目,不需要依赖spring等一系列依赖.只需要加上你用的 工具类的依赖.flume的依赖不用加,因为服务器里面有. 2.实现Interceptor接口,重写里面的in ...

  7. 【Flume】(四)IDEA编写自定义拦截器

    IDEA编写自定义拦截器 IDEA中导入以下依赖: <!-- https://mvnrepository.com/artifact/org.apache.flume/flume-ng-core ...

  8. Flume四:多路复用(ChannelSelector之Multiplexing)+自定义拦截器

    案例: 自定义拦截器 pom.xml <dependency><groupId>org.apache.flume</groupId><artifactId&g ...

  9. 【学习】SpringBoot之自定义拦截器

    /*** 自定义拦截器**/ @Configuration//声明这是一个拦截器 public class MyInterceptor extends WebMvcConfigurerAdapter ...

  10. Hadoop生态Flume(三)拦截器(Interceptor)介绍与使用(1)

    转载自 Flume中的拦截器(Interceptor)介绍与使用(一) Flume中的拦截器(interceptor) 用户Source读取events发送到Sink的时候,在events heade ...

最新文章

  1. COJ 2192: Wells弹键盘 (dp)
  2. 【Python-ML】感知器学习算法(perceptron)
  3. SQL Server扩展事件(Extended Events)-- 将现有 SQL 跟踪脚本转换为扩展事件会话
  4. mediastream2使用指南(转载)
  5. 不连续曲线 highcharts_无人车运动规划中常用的方法:多项式曲线
  6. 用 FastJSON 将 JSON 字符串转换为 Map
  7. 关于Jeecg互联网化dubbo改造方案(下)
  8. gridcontrol选中多行数据进行复制_终于整理全了,数据核对的6钟方法,掌握它们数据核对你就是大神...
  9. 基于Keras的YOLOv4目标检测平台
  10. STM32 寄存器库和固件库
  11. python的config模块_python中ConfigParse模块的用法
  12. qps多少才算高并发_AGV小车价格多少才算合适?
  13. Android Studio向项目中导入module
  14. (1)numpy.power
  15. matlab调用摄像头人脸识别,matlab-调用摄像头人脸识别
  16. JAVA中计算五子棋平局的算法_五子棋计算思路
  17. ASU计算机科学专业大学排名,2013年U.S.News美国大学排名--计算机科学专业研究生排名...
  18. 家里宽带网络连接第二台路由器实验一
  19. Android 应用的动画实践--View Animation篇
  20. 数据库【MySQL数据库介绍】

热门文章

  1. 阶段1 语言基础+高级_1-3-Java语言高级_06-File类与IO流_10 打印流_1_打印流_概述和使用...
  2. 阶段1 语言基础+高级_1-3-Java语言高级_05-异常与多线程_第4节 等待唤醒机制_8_等待唤醒机制代码实现_包子类包子铺类...
  3. Can not find the tag library descriptor for http://java.sun.com/jsp/jst1/core
  4. ASPNET--Basic Info
  5. 第十七章 特殊成员_使用typedef简化函数指针的声明
  6. 在GRIDVIEW中合并单元格
  7. Effective C++读书笔记05
  8. WCF 4.0路由服务Routing Service
  9. java异常的基本概念和处理流程
  10. 杭电acm2030汉字统计