S4Node源码分析
上一篇我们谈到Tools包含了S4中的所有命令,而启动一个Node就是调用S4Node这个类。S4Node 的任务是将收到的参数进行解析,得到S4NodeArgs中参数相应的值。
public static class S4NodeArgs {
@Parameter(names = { "-c", "-cluster" }, description = "Cluster name", required = true)
String clusterName = null;
@Parameter(names = "-baseConfig", description = "S4 base configuration file", required = false)
String baseConfigFilePath = null;
@Parameter(names = "-zk", description = "Zookeeper connection string", required = false)
String zkConnectionString = "localhost:2181";
@Parameter(names = { "-namedStringParameters", "-p" }, description = "Comma-separated list of "
+ "inline configuration parameters, taking precedence over homonymous configuration parameters from "
+ "configuration files. Syntax: '-p=name1=value1,name2=value2 '. "
+ "NOTE: application parameters should be injected in the application configuration/deployment step."
+ "Only parameters relevant to the node should be injected here, e.g. metrics logging configuration", hidden = false, converter = ParsingUtils.InlineConfigParameterConverter.class)
List<String> extraNamedParameters = new ArrayList<String>();
}
以得到的值为参数,调用startNode(S4NodeArgs nodeArgs)方法,该方法构造一个Guice的ingector,主要是将命令行的参数以及incubator-s4-master\incubator-s4-master\subprojects\s4-base\src\main\resources中的default.s4.base.properties中的变量注入到S4Bootstrap类中,然后调用S4Bootstrap的start()方法。S4Bootstrap类是S4Node的真正启动程序。
private static void startNode(S4NodeArgs nodeArgs) throws InterruptedException, IOException {
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
logger.error("Uncaught exception in thread {}", t.getName(), e);
}
});
// inject parameter from the command line, including zk string
Map<String, String> inlineParameters = Maps.newHashMap(ParsingUtils
.convertListArgsToMap(nodeArgs.extraNamedParameters));
inlineParameters.put("s4.cluster.zk_address", nodeArgs.zkConnectionString);
Injector injector = Guice.createInjector(Modules.override(
new BaseModule(Resources.getResource("default.s4.base.properties").openStream(), nodeArgs.clusterName))
.with(new ParametersInjectionModule(inlineParameters)));
S4Bootstrap bootstrap = injector.getInstance(S4Bootstrap.class);
try {
bootstrap.start(injector);
} catch (ArchiveFetchException e1) {
logger.error("Cannot fetch module dependencies.", e1);
}
}
如果想了解Guice中Injector的构造及其注入原理,可以参考http://www.kurttlin.com/post/s4-def-guide/3。