修改flume源碼,使其HTTPSource具有訪問路徑功能

目前有一個需求,就是Flume能夠做爲一個相似於tomcat的服務器,能夠經過post請求進行訪問,而且路徑須要:ip:port/contextPath格式。java

通過一些資料獲悉,httpSource只是httpSource的一個玩具工具,能夠說毛坯版,目前僅僅支持的是按照ip:port訪問,並不具有servlet這種功能。tomcat

那麼打開源碼看一下:服務器

這上面即是httpsource源碼了,能夠看到主要是5個類:HTTPBadRequestException,HTTPSource,HTTPSourceConfigurationConstants,HTTPSourceHandler,JSONHandler。工具

分別的做用是:post

HTTPBadRequestException:定義一些http異常,經常使用的好比404。blog

HTTPSourceConfigurationConstants:主要定義一些source的常量,來自於配置文件。好比:port,host等等接口

HTTPSourceHandler:一個接口,做爲handler模板。ip

JSONHandler:提供的默認實現Handler,選擇是[「header」:,"body":]這種格式,筆者對此很不習慣,其實裏面提供了好幾種event模式,不知道爲嘛要選擇這種。ssl

HTTPSource:這個就是主類了,裏面有相似於main方法的start方法。get

其實本質上httpSource就是一個嵌入了jetty的服務器,經過接受post請求(目前寫死了只處理post請求)。將數據轉換爲event往下發。因此,修改很簡單。

你只須要在HTTPSourceConfigurationConstants添加一個contextPath參數:

 public static final String CONTEXT_PATH = "contextPath";

而後跳到HTTPSource類,

在前面的聲明中加上:

private volatile String contextPath;

configure方法裏面加上獲取這個path:

contextPath = context.getString(HTTPSourceConfigurationConstants.CONTEXT_PATH);

接下來就是在jetty服務器加上路徑啦,能夠看到這部分代碼:

public void start() {
    Preconditions.checkState(srv == null,
            "Running HTTP Server found in source: " + getName()
            + " before I started one."
            + "Will not attempt to start.");
    srv = new Server();
    // Connector Array
    Connector[] connectors = new Connector[1];


    if (sslEnabled) {
      SslSocketConnector sslSocketConnector = new HTTPSourceSocketConnector(excludedProtocols);
      sslSocketConnector.setKeystore(keyStorePath);
      sslSocketConnector.setKeyPassword(keyStorePassword);
      sslSocketConnector.setReuseAddress(true);
      connectors[0] = sslSocketConnector;
    } else {
      SelectChannelConnector connector = new SelectChannelConnector();
      connector.setReuseAddress(true);
      connectors[0] = connector;
    }

    connectors[0].setHost(host);
    connectors[0].setPort(port);
    srv.setConnectors(connectors);
    try {
      org.mortbay.jetty.servlet.Context root =
        new org.mortbay.jetty.servlet.Context(
          srv, "/", org.mortbay.jetty.servlet.Context.SESSIONS);
      root.addServlet(new ServletHolder(new FlumeHTTPServlet()), "/");
      HTTPServerConstraintUtil.enforceConstraints(root);
      srv.start();
      Preconditions.checkArgument(srv.getHandler().equals(root));
    } catch (Exception ex) {
      LOG.error("Error while starting HTTPSource. Exception follows.", ex);
      Throwables.propagate(ex);
    }
    Preconditions.checkArgument(srv.isRunning());
    sourceCounter.start();
    super.start();
  }

只須要在root.addServlet加上配置的路徑,咱們就能夠根據路徑來訪問:

 root.addServlet(new ServletHolder(new FlumeHTTPServlet()), "/"+contextPath);

好了,大功告成。

相關文章
相關標籤/搜索