q456123 发表于 2015-9-17 08:50:19

修改flume源码,使其HTTPSource具备访问路径功能

  目前有一个需求,就是Flume可以作为一个类似于tomcat的服务器,可以通过post请求进行访问,并且路径需要:ip:port/contextPath格式。
  经过一些资料获悉,httpSource只是httpSource的一个玩具工具,可以说毛坯版,目前仅仅支持的是按照ip:port访问,并不具备servlet这种功能。
  那么打开源码看一下:

  这上面便是httpsource源码了,可以看到主要是5个类:HTTPBadRequestException,HTTPSource,HTTPSourceConfigurationConstants,HTTPSourceHandler,JSONHandler。
  分别的作用是:
  HTTPBadRequestException:定义一些http异常,常用的比如404。
  HTTPSourceConfigurationConstants:主要定义一些source的常量,来自于配置文件。比如:port,host等等
  HTTPSourceHandler:一个接口,作为handler模板。
  JSONHandler:提供的默认实现Handler,选择是[“header”:,"body":]这种格式,笔者对此很不习惯,其实里面提供了好几种event模式,不知道为嘛要选择这种。
  HTTPSource:这个就是主类了,里面有类似于main方法的start方法。
  其实本质上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;

if (sslEnabled) {
SslSocketConnector sslSocketConnector = new HTTPSourceSocketConnector(excludedProtocols);
sslSocketConnector.setKeystore(keyStorePath);
sslSocketConnector.setKeyPassword(keyStorePassword);
sslSocketConnector.setReuseAddress(true);
connectors = sslSocketConnector;
} else {
SelectChannelConnector connector = new SelectChannelConnector();
connector.setReuseAddress(true);
connectors = connector;
}
connectors.setHost(host);
connectors.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);

  好了,大功告成。
页: [1]
查看完整版本: 修改flume源码,使其HTTPSource具备访问路径功能