hadoop中,组件配置是由Hadoop的Configuration的一个实例实现。(在源码包的org.apache.hadoop.conf中可以找到)先上个类图:这只是部分的,Configuraation涉及的方法很多,不一一例举了。

在这里面我们看到的是整个hadoop的核心包的conf package里面涉及到全部类和接口。

在书中,我们可以看到一个XML文档以及一个利用configuration实例来读取XML文档的程序。这里搬过来,方便下面的学习分析。

<?xml version="1.0"?>
<configuration>
<property>
<name>color</name>
<value>yellow</value>
<description>Color</description>
</property> <property>
<name>size</name>
<value>10</value>
<description>Size</description>
</property> <property>
<name>weight</name>
<value>heavy</value>
<final>true</final>
<description>Weight</description>
</property> <property>
<name>size-weight</name>
<value>${size},${weight}</value>
<description>Size and weight</description>
</property>
</configuration>

java实例代码如下:

    Configuration conf = new Configuration();
conf.addResource("configuration-1.xml");
assertThat(conf.get("color"), is("yellow"));
assertThat(conf.getInt("size", 0), is(10));
assertThat(conf.get("breadth", "wide"), is("wide"));

在这里我们主要首先关注一个get(String name)方法.

public String get(String name) {
return substituteVars(getProps().getProperty(name));
}

首先应该从addResource()说起,如conf.addResource("configuration-1.xml"),这里实现了类似懒加载的方法来实现资源的读取,也就是说在add完成XML文件的时候,是不会去更新属性列表的,只有当有需要读取属性值的时候才会进行资源的加载。要注意的是,在addResource()的时候,会将给定的资源放到一个资源private
ArrayList 里面,然后会调用reloadConfiguration方法:

public synchronized void reloadConfiguration() {
properties = null; // 清除之前加载进来的全部属性
finalParameters.clear(); // 因为可以在属性里面标注final属性,所以在这里可以将全部的final属性全部也清除掉。
}

读取属性的时候,就会先调用getProps()方法,这个方法里面调用了Configuration类里面的一个核心方法,loadResources():

private void loadResources(Properties properties, ArrayList resources, boolean quiet) {
//三个参数,properties用来存储加载出来的属性,resources表明资源列表, quiet表示静默模式,默认不会存储新加进来的资源文件,只会进行临时加载。
if(loadDefaults) {
for (String resource : defaultResources) {
loadResource(properties, resource, quiet);
} //support the hadoop-site.xml as a deprecated case
if(getResource("hadoop-site.xml")!=null) {
loadResource(properties, "hadoop-site.xml", quiet);
}
} for (Object resource : resources) {
loadResource(properties, resource, quiet);
}
}

这里提供了三张资源加载的方式,但是最后是由loadResource(properties, resource, quiet)这一方法来实现的。这里主要的实现是利用java DOM API 对所有的resource进行遍历,将全部的属性值加载到这里面来。初始化代码如下:

     DocumentBuilderFactory docBuilderFactory
= DocumentBuilderFactory.newInstance();
//实例化一个工厂类
      docBuilderFactory.setIgnoringComments(true);

      //忽略开头的命名空间等信息
docBuilderFactory.setNamespaceAware(true);
try {
docBuilderFactory.setXIncludeAware(true);
} catch (UnsupportedOperationException e) {
LOG.error("Failed to set setXIncludeAware(true) for parser "
+ docBuilderFactory
+ ":" + e,
e);
}
      DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
Document doc = null;
Element root = null;

因为有string url inputstream三种格式的参数传进来,前两种都会转成URL的形式送到builder.parse()来解析。

由上面大家也看到了,采用了DOM的解析方式。熟悉XML的人都知道,还有一种比较流行的解析方式,SAX解析。在这里,相对的XML文档不会太多,所以解析的效果也不会有明显的差异,都是可行的。但是DOM的解析方式更为的直观、直接。

部分的for循环当中的代码:

        NodeList fields = prop.getChildNodes();
String attr = null;
String value = null;
boolean finalParameter = false;
for (int j = 0; j < fields.getLength(); j++) {
Node fieldNode = fields.item(j);
if (!(fieldNode instanceof Element))
continue;
Element field = (Element)fieldNode;
if ("name".equals(field.getTagName()) && field.hasChildNodes())
attr = ((Text)field.getFirstChild()).getData().trim();
if ("value".equals(field.getTagName()) && field.hasChildNodes())
value = ((Text)field.getFirstChild()).getData();
if ("final".equals(field.getTagName()) && field.hasChildNodes())
finalParameter = "true".equals(((Text)field.getFirstChild()).getData());
}

最后经过

properties.setProperty(attr, value);

放入结合当中,这样就产生了get()方法调用substituteVars方法的getPros()的方法。

在学习上述的代码的时候,我慢慢体会到了,java私有方法和公有方法的一些使用的要点。那就是在使用私有方法的时候,应该尽可能的降低其对于全局变量的依赖性,可以在调用私有方法前尽可能的去掉一些不要的逻辑,让私有方法好好的工作。像configuration这个类,从addResource到loadResource,都是极尽可能的消除方法后端的一些影响因素,将更多的逻辑分担出来,使得代码的阅读更加的简单明了,这是一个程序员应该有的品质吧。

最后要说一下,这里面还有一个用于属性导出的函数,也是一个比较值得学习的方法,这里就把代码贴出来。

public static void dumpConfiguration(Configuration conf,
Writer out) throws IOException {
Configuration config = new Configuration(conf,true);
config.reloadConfiguration();
JsonFactory dumpFactory = new JsonFactory();
JsonGenerator dumpGenerator = dumpFactory.createJsonGenerator(out);
dumpGenerator.writeStartObject();
dumpGenerator.writeFieldName("properties");
dumpGenerator.writeStartArray();
dumpGenerator.flush();
for (Map.Entry<Object,Object> item: config.getProps().entrySet()) {
dumpGenerator.writeStartObject();
dumpGenerator.writeStringField("key", (String) item.getKey());
dumpGenerator.writeStringField("value",
config.get((String) item.getKey()));
dumpGenerator.writeBooleanField("isFinal",
config.finalParameters.contains(item.getKey()));
dumpGenerator.writeStringField("resource",
config.updatingResource.get(item.getKey()));
dumpGenerator.writeEndObject();
}
dumpGenerator.writeEndArray();
dumpGenerator.writeEndObject();
dumpGenerator.flush();
}

最新文章

  1. 【处理手记】U盘读不出+卷标丢失+像读卡器+大小0+无媒体
  2. 简单的bat命令去获取wsdl的源码
  3. Mono.Posix.dll文件
  4. lucene 3.0.2 + 多文件夹微博数据(时间,微博)构建索引
  5. javascript实例学习之二——类新浪微博的输入框
  6. jsonUtil 工具类
  7. 都是iconv惹的祸
  8. How to modify Code Comments[AX2012]
  9. 关于Unity3D中的版本管理 .
  10. C primer plus 读书笔记第九章
  11. android Gallery滑动不流畅的解决
  12. JavaScript实例技巧精选(12)—计算星座与属相
  13. 100%解决ios上audio不能自动播放的问题
  14. 企业信息化-Excel快速生成系统
  15. Gradle 依赖管理
  16. 解决Pycharm更新package出现的问题:AttributeError:module &#39;pip&#39; has no attribute &#39;main&#39;
  17. SSM_CRUD新手练习(7)Spring单元测试分页请求
  18. 老树新芽,在ES6下使用Express
  19. session的取代者:Json Web Tokens----在客户端存储登陆状态
  20. 给JSON中put的value=null时,这对key=value会被隐藏掉。

热门文章

  1. window.location.href跳转问题
  2. 【bzoj3671】[Noi2014]随机数生成器 贪心
  3. PAT天梯赛练习题——L3-005. 垃圾箱分布(暴力SPFA)
  4. java面试题之sleep()和wait()方法的区别
  5. jvm gc回收机制
  6. java 数据库连接的几个步骤
  7. charts 画饼图
  8. Chapter 4-5
  9. idea 自定义工具栏
  10. android 活动