一、介绍

  1. flume自带的Http Source可以通过Http Post接收事件。

  2. 场景:对于有些应用程序环境,它可能不能部署Flume SDK及其依赖项,或客户端代码倾向于通过HTTP而不是Flume的PRC发送数据的情况,此时HTTP SOURCE可以用来将数据接收到Flume中。

  3. 从客户端的角度看,HTTP SOURCE表现的像web服务器一样能接收flume事件

二、参数

配置参数 默认值 描述
type   http (org.apache.fluem.source.httpSource)
bind   绑定的IP地址或主机名
port   绑定的端口号
enableSSL false  
keystore   使用的keystore文件的路径
keystorePassword   能够进入keystore的密码
handler JSONHandler HTTP SOURCE使用的处理程序类
handler.*   传给处理程序类的任何参数 可以 通过使用此参数(*)配置传入
    1. 为了安全传输,http source也支持SSL,SSL支持的相关例子可以参见我的关于flume之Avro Source博客

    2. Flume 事件使用一个可插拔的“handler”程序来实现转换,它必须实现的HTTPSourceHandler接口。此处理程序需要一个HttpServletRequest和返回一个flume 事件列表。默认是:JSONHandler。

      例如:xxx.handler=com.dxz.flume_demo.source.HTTPSourceXmlHandler

    3. 自定义的handler如果想传入参数,可以使用handler.*配置

      如:xxx.handler.myparam=zhangsan

    4. 如果配置中没有指定处理程序,HTTP SOURCE将使用与Flume绑定的处理程序,即:JSONHandler,它能处理JSON格式的事件。每个事件可以包含包装为数组的几个事件,尽管Source写入的管道可能有限制的事务能力。

      处理程序接受UTF-8,UTF-16,UTF-32编码的JSON格式的数据,并且将它转换成一个列表的事件。

      格式:

      [ { "headers":{"":"","":""
                       },
           "body":"the first event"
         },
         { "headers":{"":"","":""
                       },
           "body":"the second event"
         }
         
      ]

配置文件http_source.conf

  1. a1.sources=r1
  2. a1.sinks=k1
  3. a1.channels=c1
  4.  
  5. a1.sources.r1.type=http
  6. a1.sources.r1.bind=localhost
  7. a1.sources.r1.port=50000
  8. a1.sources.r1.channels=c1
  9.  
  10. a1.sinks.k1.type=logger
  11. a1.sinks.k1.channel=c1
  12.  
  13. a1.channels.c1.type=memory
  14. a1.channels.c1.capacity=1000
  15. a1.channels.c1.transactionCapacity=100

启动:cd到bin目录下执行

  1. flume-ng.cmd agent -conf ../conf -conf-file ../conf/http_source.conf -name a1 -property flume.root.logger=INFO,console

3) 测试:

  1. $ curl -X POST -d'[{"headers":{"h1":"v1","h2":"v2"},"body":"hello body"}]' http://192.168.1.102:50000

4) 服务器端结果

2.http source handler自定义例子

假定xml请求格式,期望格式如下:

  1. <events>
  2. <event>
  3. <headers><header1>value1</header1></headers>
  4. <body>test</body>
  5. </event>
  6. <event>
  7. <headers><header1>value1</header1></headers>
  8. <body>test2</body>
  9. </event>
  10. </events>

现在要求flume http source可以处理这种请求的xml格式

操作步骤如下:

1)建立maven工程,pom.xml文件如下

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4.  
  5. <groupId>com.dxz</groupId>
  6. <artifactId>flume-demo</artifactId>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <packaging>jar</packaging>
  9.  
  10. <name>flume-demo</name>
  11. <url>http://maven.apache.org</url>
  12.  
  13. <properties>
  14. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  15. </properties>
  16.  
  17. <dependencies>
  18. <dependency>
  19. <groupId>junit</groupId>
  20. <artifactId>junit</artifactId>
  21. <version>3.8.1</version>
  22. <scope>test</scope>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.apache.flume</groupId>
  26. <artifactId>flume-ng-core</artifactId>
  27. <version>1.6.0</version>
  28. <scope>compile</scope>
  29. </dependency>
  30. </dependencies>
  31. </project>

2)开发代码 ,自定义handler类

  1. package com.dxz.flume_demo.source;
  2.  
  3. import com.google.common.base.Preconditions;
  4. import org.apache.flume.Context;
  5. import org.apache.flume.Event;
  6. import org.apache.flume.event.EventBuilder;
  7. import org.apache.flume.source.http.HTTPBadRequestException;
  8. import org.apache.flume.source.http.HTTPSourceHandler;
  9. import org.slf4j.Logger;
  10. import org.slf4j.LoggerFactory;
  11. import org.w3c.dom.Document;
  12. import org.w3c.dom.Element;
  13. import org.w3c.dom.Node;
  14. import org.w3c.dom.NodeList;
  15. import org.xml.sax.SAXException;
  16.  
  17. import javax.servlet.http.HttpServletRequest;
  18. import javax.xml.parsers.DocumentBuilder;
  19. import javax.xml.parsers.DocumentBuilderFactory;
  20.  
  21. import java.nio.charset.Charset;
  22. import java.util.ArrayList;
  23. import java.util.HashMap;
  24. import java.util.List;
  25. import java.util.Map;
  26.  
  27. public class HTTPSourceXMLHandler implements HTTPSourceHandler {
  28. private final String ROOT = "events";
  29. private final String EVENT_TAG = "event";
  30. private final String HEADERS_TAG = "headers";
  31. private final String BODY_TAG = "body";
  32.  
  33. private final String CONF_INSERT_TIMESTAMP = "insertTimestamp";
  34. private final String TIMESTAMP_HEADER = "timestamp";
  35. private final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
  36.  
  37. // Document builders are not thread-safe.
  38. // So make sure we have one for each thread.
  39. private final ThreadLocal<DocumentBuilder> docBuilder = new ThreadLocal<DocumentBuilder>();
  40.  
  41. private boolean insertTimestamp;
  42. private static final Logger LOG = LoggerFactory.getLogger(HTTPSourceXMLHandler.class);
  43.  
  44. public List<Event> getEvents(HttpServletRequest httpServletRequest) throws HTTPBadRequestException, Exception {
  45. if (docBuilder.get() == null) {
  46. docBuilder.set(documentBuilderFactory.newDocumentBuilder());
  47. }
  48. Document doc;
  49. final List<Event> events;
  50. try {
  51. doc = docBuilder.get().parse(httpServletRequest.getInputStream());
  52. Element root = doc.getDocumentElement();
  53.  
  54. root.normalize();
  55. // Verify that the root element is "events"
  56. Preconditions.checkState(ROOT.equalsIgnoreCase(root.getTagName()));
  57.  
  58. NodeList nodes = root.getElementsByTagName(EVENT_TAG);
  59. LOG.info("get nodes={}", nodes);
  60.  
  61. int eventCount = nodes.getLength();
  62. events = new ArrayList<Event>(eventCount);
  63. for (int i = 0; i < eventCount; i++) {
  64. Element event = (Element) nodes.item(i);
  65. // Get all headers. If there are multiple header sections,
  66. // combine them.
  67. NodeList headerNodes = event.getElementsByTagName(HEADERS_TAG);
  68. Map<String, String> eventHeaders = new HashMap<String, String>();
  69. for (int j = 0; j < headerNodes.getLength(); j++) {
  70. Node headerNode = headerNodes.item(j);
  71. NodeList headers = headerNode.getChildNodes();
  72. for (int k = 0; k < headers.getLength(); k++) {
  73. Node header = headers.item(k);
  74.  
  75. // Read only element nodes
  76. if (header.getNodeType() != Node.ELEMENT_NODE) {
  77. continue;
  78. }
  79. // Make sure a header is inserted only once,
  80. // else the event is malformed
  81. Preconditions.checkState(!eventHeaders.containsKey(header.getNodeName()),
  82. "Header expected only once " + header.getNodeName());
  83. eventHeaders.put(header.getNodeName(), header.getTextContent());
  84. }
  85. }
  86. Node body = event.getElementsByTagName(BODY_TAG).item(0);
  87. if (insertTimestamp) {
  88. eventHeaders.put(TIMESTAMP_HEADER, String.valueOf(System.currentTimeMillis()));
  89. }
  90. System.out.println("httpServletRequest.getCharacterEncoding()="+httpServletRequest.getCharacterEncoding());
  91. System.out.println("body.getTextContent()=" + body.getTextContent());
  92. events.add(EventBuilder.withBody(
  93. body.getTextContent().getBytes(Charset.defaultCharset()), eventHeaders));
  94. }
  95. } catch (SAXException ex) {
  96. throw new HTTPBadRequestException("Request could not be parsed into valid XML", ex);
  97. } catch (Exception ex) {
  98. throw new HTTPBadRequestException(
  99. "Request is not in expected format. " + "Please refer documentation for expected format.", ex);
  100. }
  101. return events;
  102. }
  103.  
  104. public void configure(Context context) {
  105. insertTimestamp = context.getBoolean(CONF_INSERT_TIMESTAMP, false);
  106. }
  107. }

3)在该工程的flume-demo目录下执行命令mvn package,会将该工程打成jar包,会生产target目录,从中找到flume-demo.jar,将其拷贝到flume的lib目录下

4)flume配置文件:http_source_xml.conf

  1. a1.sources=r1
  2. a1.sinks=k1
  3. a1.channels=c1
  4.  
  5. a1.sources.r1.type=http
  6. a1.sources.r1.bind=localhost
  7. a1.sources.r1.port=50000
  8. a1.sources.r1.channels=c1
  9. a1.sources.r1.handler=com.dxz.flume_demo.source.HTTPSourceXMLHandler
  10. a1.sources.r1.insertTimestamp=true
  11.  
  12. a1.sinks.k1.type=logger
  13. a1.sinks.k1.channel=c1
  14.  
  15. a1.channels.c1.type=memory
  16. a1.channels.c1.capacity=1000
  17. a1.channels.c1.transactionCapacity=100

5)启动服务

  1. flume-ng.cmd agent -conf ../conf -conf-file ../conf/http_source_xml.conf -name a1 -property flume.root.logger=INFO,console

6)测试:

7)结果:

转自:

https://blog.csdn.net/liuxiao723846/article/details/63342490

flume http source示例讲解的更多相关文章

  1. 一次flume exec source采集日志到kafka因为单条日志数据非常大同步失败的踩坑带来的思考

    本次遇到的问题描述,日志采集同步时,当单条日志(日志文件中一行日志)超过2M大小,数据无法采集同步到kafka,分析后,共踩到如下几个坑.1.flume采集时,通过shell+EXEC(tail -F ...

  2. 把Flume的Source设置为 Spooling directory source

    把Flume的Source设置为 Spooling directory source,在设定的目录下放置需要读取的文件,一些文件在读取过程中会报错. 文件格式和报错如下: 实验一 读取汉子和“:&qu ...

  3. (ZZ)WPF经典编程模式-MVVM示例讲解

    http://www.cnblogs.com/xjxz/archive/2012/11/14/WPF.html 本篇从两个方面来讨论MVVM模式: MVVM理论知识 MVVM示例讲解 一,MVVM理论 ...

  4. Flume:source和sink

    Flume – 初识flume.source和sink 目录基本概念常用源 Source常用sink 基本概念  什么叫flume? 分布式,可靠的大量日志收集.聚合和移动工具.  events ...

  5. 012——VUE中todos示例讲解class中应用表达式

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  6. FLUME KAFKA SOURCE 和 SINK 使用同一个 TOPIC

    FLUME KAFKA SOURCE 和 SINK 使用同一个 TOPIC 最近做了一个事情,过滤下kakfa中的数据后,做这个就用到了flume,直接使用flume source 和 flume s ...

  7. 【机器学习】【条件随机场CRF-2】CRF的预测算法之维特比算法(viterbi alg) 详解 + 示例讲解 + Python实现

    1.CRF的预测算法条件随机场的预测算法是给定条件随机场P(Y|X)和输入序列(观测序列)x,求条件概率最大的输出序列(标记序列)y*,即对观测序列进行标注.条件随机场的预测算法是著名的维特比算法(V ...

  8. PHP服务器端API原理及示例讲解(接口开发)

    http://www.jb51.net/article/136816.htm 下面小编就为大家分享一篇PHP服务器端API原理及示例讲解(接口开发),具有很好的参考价值,希望对大家有所帮助 相信大家都 ...

  9. 示例讲解PostgreSQL表分区的三种方式

    我最新最全的文章都在南瓜慢说 www.pkslow.com,欢迎大家来喝茶! 1 简介 表分区是解决一些因单表过大引用的性能问题的方式,比如某张表过大就会造成查询变慢,可能分区是一种解决方案.一般建议 ...

随机推荐

  1. linux通过安装包安装nginx和jdk

    1.安装prce(重定向支持)和openssl(https支持,如果不需要https可以不安装.) yum -y install pcre* yum -y install openssl* 2.下载n ...

  2. time,datetime模块

    time & datetime 模块 在平常的代码中,我们常常需要与时间打交道.在Python中,与时间处理有关的模块就包括:time,datetime,calendar(很少用,不讲),下面 ...

  3. 20165313 《Java程序设计》第七周学习总结

    教材学习总结 1.下载安装MySQL数据库管理系统. 2.MySQL数据库基本操作. 3.利用JAVA程序对MySQL数据库系统进行查找,更新,添加和删除操作. 学习中的问题与解决方案 1.运行书上安 ...

  4. 浅谈malloc()和free()工作原理

    编程之路刚刚开始,错误难免,希望大家能够指出.  malloc()和free()是我经常需要用到的函数,一般情况下,C程序使用malloc()在堆上分配内存,free()释放内存,两者的参数和返回值就 ...

  5. python英文与中文的词频统计

    1.统计英文单词, # 1.准备utf-8编码的文本文件file(已在文件夹中定义了 一个名叫“head.txt.rtf”文本文件,详情请见截图) def getTxt(): #3对文本预处理(包括) ...

  6. 【BZOJ1452】【JSOI2009】count

    暴力出奇迹……原题: 图片题面好评(图片样例差评 我最开始的思路: 容斥,变成每次询问((1,1),(x,y))这个矩阵中颜色为c的个数,然后三维偏序!cdq分治! 但是2e5的询问好像并不大丈夫?乘 ...

  7. this关键字的使用8/22

    实质就是:this代表当前对象目录: 1.this(name) 调用同一个类中参数为 public Person(String name)这个构造方法 2.this.say() 同一个类中,某一个方法 ...

  8. Module Sources

    转自:https://www.terraform.io/docs/modules/sources.html 主要记录module source 的格式 The source argument in a ...

  9. Makefile introduction (very old presentation)

  10. java 连接 hiveserver2 例子

    启动了  hiveserver2 以后才能使用 程序连接 .目前的 使用的 是  server2 版本.和以前的版本驱动包名不同: package hadoop; import java.sql.Co ...